|
|
R 教材:R 呼叫外部程式 |
c File name: call_f.f
c For dynamical loading, compile by g77.
c SHELL> g77 -c call_f.f ; g77 -shared -o call_f.so call_f.o
subroutine hello(m, a, b, c, d)
integer i, m
real*8 a(m), b(m), c(m), d
d = 0
do i = 1, m
c(i) = a(i) + b(i)
d = d + c(i)
a(i) = 0
end do
return
end
c Output is a shared library "call_f.so" can called by R.
| |
| or for Windows will like this | |
c File name: call_f.f
c For dynamical loading, compile by Compaq Visual Fortran.
c Here, for fortran 77 syntex.
subroutine hello(m, a, b, c, d)
cDEC$ ATTRIBUTES DLLEXPORT::hello
cDEC$ ATTRIBUTES C, REFERENCE, ALIAS:'hello_'::hello
integer i, m
real*8 a(m), b(m), c(m), d
d = 0
do i = 1, m
c(i) = a(i) + b(i)
d = d + c(i)
a(i) = 0
end do
return
end
c Output is a shared library "call_f.dll" caned call by R.
c For fortran 90 syntex, use "!DEC$" to replace "cDEC$".
|
# File name: call_f.r
dyn.load("call_f.so")
# For Windows will like this
# dyn.load("C:/Windows/Desktop/call_f.dll")
symbol.For("hello")
is.loaded(symbol.For("hello"))
a <- 1 : 9
test.f <- function(a) {
b <- a
d <- vector(mode = "numeric", length = length(a))
e <- vector(mode = "numeric", length = 1)
ret <- .Fortran("hello", m = length(a), a = as.double(a),
b = as.double(b), d = as.double(d), e = as.double(e))
ret
}
test.f(a)
dyn.unload("call_f.so")
# For Windows will like this
# dyn.unload("C:/Windows/Desktop/call_f.dll")
|
/*
File name: call_c.c
For dynamical load compile by gcc.
SHELL> gcc -c call_c.c ; gcc -shared -o call_c.so call_c.o
*/
void hello(int m, double *a, double *b, double *c, double *d){
int i;
d = 0;
for(i = 0; i < m; i++){
c[i] = a[i] + b[i];
*d =+ c[i];
a[i] = 0;
}
}
/* Output is a shared library "call_c.so" can called by R. */
|
# File name: call_c.r
dyn.load("call_c.so")
# For Windows will like this
# dyn.load("C:/Windows/Desktop/call_c.dll")
symbol.C("hello")
is.loaded(symbol.C("hello"))
a <- 1 : 9
test.c <- function(a) {
b <- a
d <- vector(mode = "numeric", length = length(a))
e <- vector(mode = "numeric", length = 1)
ret <- .C("hello", m = length(a), a = as.double(a),
b = as.double(b), d = as.double(d), e = as.double(e))
ret
}
test.c(a)
dyn.unload("call_c.so")
# For Windows will like this
# dyn.unload("C:/Windows/Desktop/call_c.dll")
|
$m [1] 9 $a [1] 0 0 0 0 0 0 0 0 0 $b [1] 1 2 3 4 5 6 7 8 9 $d [1] 2 4 6 8 10 12 14 16 18 $e [1] 90 |
![]() |
![]() |
| 陳韋辰 (04/08/19) --- |