1

I am using Visual Studio to create my C++ DLLS. A sample C++ function is

void _stdcall MyFunc(char ** strInput)
{
   MessageBox(NULL,"Hi from C++", L"C++ program", NULL);
}

I can then call this function from R by doing the following

dyn.load("Path\myDll.dll")
.C("MyFunc","Hello")

The above code works fine when called from R 64 bit. However, when I compile my DLL as 32 bit DLL and call it from R 32 bit, it crashes after briefly displaying the messagebox. I know that my DLL is working and is a valid 32 bit DLL since I can call its functions from other programs with no problem. Do you know why R 32 bit would be crashing when R 64 bit can handle the same call with no problem?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • 2
    Try replacing `_stdcall` with `__cdecl`. x64 has a single, universal calling convention, but x86 does not, and you're likely using the wrong one. – ildjarn Jul 12 '12 at 19:58
  • @ildjarn - That was brilliant and solved my problem in a flash!. Thank you so much. Now, could you please type your solution again as an answer so I can accept it? –  Jul 12 '12 at 20:10
  • I suspect you will run into more serious issues once you actually try to transfer values as R is built with MinGW. You may get by via C-language wrappers for all your functions, but that is a lot of work... – Dirk Eddelbuettel Jul 12 '12 at 20:21
  • @DirkEddelbuettel - I am aware of that. Right now, I am just passing in simple strings and returning strings. If my requirements become more complex, I will use Rcpp and get a different compiler –  Jul 12 '12 at 20:34

1 Answers1

2

Reposted from comment:

Replace _stdcall with __cdecl – x64 has a single, universal calling convention, but x86 does not, and you're apparently using the wrong one.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • To add some more information, this link states that the problem with stdcall is that MCVC++ mangles names in the DLL export table. cdecl does not do that ensuring better chance of interoperability between MinGW (used in R) and MSVC++ (used in my DLL) http://stackoverflow.com/questions/6511096/cdecl-or-stdcall-on-windows –  Jul 12 '12 at 21:39
  • @curiouspanda : Name mangling and calling convention are mostly separate issues -- one can prevent name mangling with any calling convention by using `extern "C"`. However, I don't think name mangling was your particular issue since you saw the message box (even if followed by a crash); if it was, you wouldn't have seen the message box at all. – ildjarn Jul 12 '12 at 21:45