AccessViolationException when calling the simplest C ++ function I can think of from managed code

I'm trying to figure out how to use managed / unmanaged interoperable code, but I hit the wall that 4 hours of work at Google couldn't get past. I put together 2 projects in visual studio, one of which created a win32 exe and one of them created a Windows.NET application. After somersault, I got the C # code to call the C ++ code correctly, but from here I started getting an AccessViolationException every time I got 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 a C # Windows Forms Application calling it:

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

      

Pretty simple? The call works and I can go into C ++ code (I have enabled unmanaged debugging for the project), but it dies from the array creation string every time with an AccessViolationException. The same code works fine when I run the executable (the C ++ code is in the console application project, I tried to call it with the _tmain function and no problem), but when called into it from .NET it explodes every time.

There should be something obvious that I don't see here, but I haven't come up with anything useful from reading the tutorials, and most of the posts about this exception are from people who have problems with complex marshals or GCHandles. Thanks in advance for any help.

Update: You were at the bottom, but this is weird. At first when I started this, I assumed I couldn't do it (calling functions in executables), but when I tried it - it actually worked, it's a call. It seems to allow you to call a function on an executable, but as soon as you try to allocate any memory it will die. Anyway, thanks for the advice, it seems to be working correctly.

0


a source to share


2 answers


You cannot call functions in executables outside of those executables. You need to compile your code into a DLL.



+2


a source


You have declared your function as extern "C"

, which means it uses it cdecl

as its calling convention. By default DllImport

uses StdCall

as calling convention. This could be the reason for your code to crash.

Try to import your function into .NET code like



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

      

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

0


a source







All Articles