Skip to content
Prev 77636 / 398502 Next

cdecl and stdcall

On 9/21/2005 9:32 AM, Bogner, Konrad (LfU) wrote:
You are likely to run into problems mixing Cygwin code with R.  R uses 
MinGW, not Cygwin.  You can probably get away with writing a DLL using 
Cygwin tools and calling it from R, but you may well find that there are 
subtle problems.  I'd suggest switching to MinGW.

The MinGW wiki gives instructions for linking to foreign DLLs on this page:

http://www.mingw.org/MinGWiki/index.php/CreateImportLibraries

For example, I've got a DLL with these exports:

$ pexports teststdcall.dll
LIBRARY teststdcall.dll
EXPORTS
dostdcall at 8

(pexports is a MinGW utility; not part of our standard toolset, but you 
can get the MinGW utils at the same place as the rest of MinGW).

Put those 3 lines in a file teststdcall.def, then

$ dlltool -d teststdcall.def -l libteststdcall.a

creates the import library.  (If your exports have names in a different 
format, you may need some different options here; see the Wiki.)

Set up your C wrapper something like this:

$ less callstdcall.c
__stdcall double dostdcall(double x);

void callit(double *x)
{
     double y;
     y = dostdcall(*x);
     *x = y;
}

You then need to set an environment variable PKG_LIBS to tell Rcmd SHLIB 
to look at your import library:

$ export PKG_LIBS="-L. -lteststdcall"

and then create your DLL to be called by R:

$ Rcmd SHLIB callstdcall.c
making callstdcall.d from callstdcall.c
gcc   -If:/R/svn/r-devel/R/include -Wall -O2   -c callstdcall.c -o 
callstdcall.o

ar cr callstdcall.a callstdcall.o
ranlib callstdcall.a
gcc  --shared -s  -o callstdcall.dll callstdcall.def callstdcall.a 
-Lf:/R/svn/r
-devel/R/src/gnuwin32  -L. -lteststdcall -lg2c -lR

Then in R

 > dyn.load('callstdcall.dll')
 > .C('callit', x=as.double( <some value> ))

will call it for you.

Duncan Murdoch

P.S. There's supposed to be a way in MinGW to avoid creating the import 
library, i.e. to link directly against the .dll, but I don't know what 
it is, and it's less flexible than this approach.