[R] cdecl and stdcall

Duncan Murdoch murdoch at stats.uwo.ca
Wed Sep 21 19:27:47 CEST 2005

On 9/21/2005 9:32 AM, Bogner, Konrad (LfU) wrote:
> Hi,
> I'm trying to load a dynamic link library and it seems to work (is.loaded  -> TRUE). When I run the function, which calls the .Fortran subroutine, R crashes!
> I'v tried the same in S-Plus 2000 and it worked. Therefore I suppose that the dll has been compiled with the stdcall calling convention (and not cdecl). But the problem is that I don't have access to the source code, I've just the dll without any working import library. Maybe someone could be so kind and send me an example how to write a wrapper? I've found one example at the NAG's site (http://www.nag.com/numeric/RunderWindows.asp), but it didn't work. At http://www.cygwin.com/cygwin-ug-net/dll.html there is a description of linking against dlls and how to create a def and an import libraray file, but unfortunately my dll seems to be stripped, because I get the error message "no symbols" after running  the command "nm".
> I'm using R 2.1.0 (windows xp) and CYGWIN (gnu compilers,..)

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:


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

$ pexports teststdcall.dll
LIBRARY teststdcall.dll
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 

ar cr callstdcall.a callstdcall.o
ranlib callstdcall.a
gcc  --shared -s  -o callstdcall.dll callstdcall.def callstdcall.a 
-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.

More information about the R-help mailing list