views:

288

answers:

2

Hi all, I'm trying to learn how to use managed/unmanaged code interop, but I've hit a wall that 4 hours of googling wasn't able to get over. I put together 2 projects in visual studio, one creating a win32 exe, and one creating a windows forms .NET application. After a bunch of mucking around I got the C# code to call into the c++ code correctly, but from here I started getting AccessViolationException everytime I got in there. Here is the code from the .cpp file:

     extern "C" __declspec(dllexport) void QuickTest()
 {
  int iTest = 0;
  int aTestArray[3] = {1,2,3};
  return;
 }

And here is the code from the C# windows forms app calling it:

        [DllImport("UnmanagedEvaluation2.exe")]
        static extern void QuickTest();

Pretty simple right? The call works, and I am able to step into the c++ code (I turned on unmanaged debugging for the project), but it dies on the array creating line every single time with AccessViolationException. The same code runs fine when I run the executable (the c++ code is in a console application project, I tried calling it from the _tmain function and no problems), but when calling into it from .NET it blows up every time.

There has to be something obvious I am missing here, but I haven't come up with anything useful from reading tutorials, and most of the issues posts about that exception are people having problems with complicated marshalings or GCHandles. Thanks in advance for any help.

Update: You were right below, but it's weird. At first when I started this I assumed I wouldn't be able to do that (call into functions in executables), but when I tried it -- it actually did work, the call that is. It seems like it lets you call into a function into an executable, but as soon as you try to allocate any memory it dies. Any way, thanks for the advice, it seems to be working correctly now.

+2  A: 

You can't call functions in executables from outside those executables. You need to compile your code into a DLL.

RichieHindle
OR you need to tell the compiler that some symbols have to be exported. I did make some exe before that exported symbols like dll. It's almost the same, only the configuration and compiler specific dllimport/export specifiers have to be changed.
Klaim
A: 

You have declared your function as extern "C" which means it uses cdecl as its calling convention. By default, DllImport uses StdCall as the calling convention. This may be the reason of your code crashing.

Try importing your function into .NET code as

    [DllImport("UnmanagedEvaluation2.exe", CallingConvention=CallingConvention.Cdecl)]
    static extern void QuickTest();

See http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.callingconvention.aspx for more info.

VladLosev