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

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.

2 Answers

  1. Laurent- Reply


    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.

  2. Lawrence- Reply


    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)

    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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>