Tistatos
Tistatos

Reputation: 681

Pinvoke C#: delegated function cause crash

I'm trying to use the function below to map another function to be called when data arrives. the C++ function creates a new thread in which my function will be called. it works for a few seconds but then i get an error :(i've turned "enable unmanaged code debugging to see this error") Unhandled exception at 0x7725158e in threadTest.exe: 0xC0000005: Access violation.

If I remove the IntPtr frameData from the delegated function everything works fine, therefore i suspect there is something i should do to the declaration of the delegate class to avoid this from happening.

C# code:

public delegate void HandlerFunction(IntPtr frameData);

[DllImport("Cortex_SDK.dll")]
public extern static int Cortex_SetDataHandlerFunc(HandlerFunction function);


-----
public class myClass
{
    static HandlerFunction myFunction = new HandlerFunction(threadFunction);
    public myClass()
    {
        Cortex.Cortex_SetDataHandlerFunc(myFunction);
    }

    private static void threadFunction(IntPtr FrameData)
    {
    }
}

Upvotes: 2

Views: 779

Answers (1)

David Heffernan
David Heffernan

Reputation: 612954

I expect this is just a calling convention problem. Your C++ code assumes cdecl, but the C# code assumes stdcall. Simply specify cdecl in the P/Invoke and you should be golden.

Upvotes: 4

Related Questions