Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a dll dynamic library from C in R (Windows)

Tags:

c

r

dll

I want to create a dll dynamic library from a C source code so that I can load and use it in R. I am now using

R CMD SHLIB foo.c 

in Windows 7 command line. But nothing happened. There is no error message but no dll file was created.

What's wrong with what I have done? Thank you.

like image 848
JACKY Li Avatar asked Apr 13 '13 20:04

JACKY Li


2 Answers

I am sorry if my question is not very clear. But I figured it out how to get things work and possible mistakes. Hopefully it will be useful for someone. Here are the steps:

  1. Install R (latest version is 3.0.0 now). Make sure to add R bin folder to PATH
  2. Install the latest version of Rtools Here. Make sure to add "c:\Rtools\bin;c:\Rtools\gcc-4.6.3\bin;" to PATH
  3. Write your C code, saved in foo.c
  4. In Windows command window, type

    R CMD SHLIB foo.c

then you should have a foo.dll file then you can call it in R. Note that the foo.dll created under 64bits R can only be loaded into 64bits R. If you try to load in 32bits R, you will get error messages.

like image 141
JACKY Li Avatar answered Nov 18 '22 11:11

JACKY Li


Exactly what do you mean by "nothing happened"? Is R in your path?

What does R --version reveal? How about R CMD config CC and R CMD config CFLAGS?

Lastly, if you had Rcpp installed (and your toolchain was correct, including PATH settings and all the rest) the you could do things on the fly a la

R> library(Rcpp)
R> cppFunction('double foo(double x) { return std::sqrt(x); }')
R> foo(4)
[1] 2
R> foo(4.2)
[1] 2.04939
R> unclass(foo)
function (x) 
.Primitive(".Call")(<pointer: 0x7f251ba76530>, x)
R> 

Here we used cppFunction() (and a bunch of tricks inside Rcpp) to compile, link and load a simple (and pretty useless...) C(++) function which takes a square root.

like image 2
Dirk Eddelbuettel Avatar answered Nov 18 '22 12:11

Dirk Eddelbuettel