[R] Trouble with compiling or dyn.load-ing C code

Werner Stuetzle wxs at u.washington.edu
Tue Mar 28 18:42:19 CEST 2006


I am trying to compile a C function and make a dll using MinGW. I 
installed MinGW, Perl, the Murdoch-Sutherland tool collection, and then I 
proceed as in "R for Windows FAQ" Section 8.

Here is my C function:
----------------------------------------------------------------------
/* C function adding two vectors (5-26-05)  */

#include<stdlib.h>

EXPORT void addvectors(double *a, double *b, int *n, double *sum) {
   int i;
   for (i = 0; i < *n; i++) {
     sum[i] = a[i] + b[i];
     }
}
----------------------------------------------------------------------

Here is my command to make the dll and the output:

----------------------------------------------------------------------
z:/Stat534/Spring06/Website/Link-C-R $ c:/Progra~1/R/R-2.2.1/bin/R CMD 
SHLIB add-vectors.C
making add-vectors.d from add-vectors.C
g++   -Ic:/Progra~1/R/R-2.2.1/include -Wall -O2   -c add-vectors.C -o 
add-vectors.o
ar cr add-vectors.a add-vectors.o
ranlib add-vectors.a
g++  --shared -s  -o add-vectors.dll add-vectors.def add-vectors.a 
-Lc:/Progra~1/R/R-2.2.1/src/gnuwin32   -lg2c -lR 
----------------------------------------------------------------------

I get "add-vectors.dll". Here is the R code to load the dll and add two 
vectors:

----------------------------------------------------------------------
dll.filename <-
   "z:\\Stat534\\Spring06\\Website\\Link-C-R\\add-vectors.dll"

dyn.load(dll.filename)

## If the DLL needs to be re-built, it has to be unloaded first.
## dyn.unload(dll.filename)


addvectors <- function(a, b) {
   the.sum <- rep(0, length(a))
   res <- .C("addvectors", as.double(a), as.double(b), as.integer(length(a)),
             as.double(the.sum))
   return(res[[4]])
}

a <- c(1,2,3)
b <- c(4,5,6)
addvectors(a, b)
----------------------------------------------------------------------

Here is what I get when I use addvectors:

----------------------------------------------------------------------
> addvectors(a, b)
Error in .C("addvectors", as.double(a), as.double(b), as.integer(length(a)),  :
 	C entry point "addvectors" not in load table
----------------------------------------------------------------------


What am I doing wrong?

Thanks a lot, W


----------------------------------------------------------------------
Werner Stuetzle                           (206) 685-7431 (w)
Professor, Statistics                     (206) 685-7419 (fax)
Adjunct Professor, CSE                    wxs at stat.washington.edu
Director, ACMS                            www.stat.washington.edu/wxs
Department of Statistics, Box 354322      Office: Padelford B305
University of Washington
Seattle, WA 98195-4322




More information about the R-help mailing list