Shtong
Shtong

Reputation: 1787

Marshalling double parameters with P/Invoke

I have a problem with a P/Invoke call I'm trying to do. I have to call a C++ class from a C# program. I have the source of this class so what I did is put it in a DLL project and create export functions to access it's main method. That should be enough to do what I need and keep things simple.

My export method looks like this :

extern "C" _declspec(dllexport) void Inference(double *c1, double *c2, double *c3, double *result)
{
    /* somecode */
}

This compiles, and I can see the export in a dumpbin output.

Now the problem is, I can't call this method from my C# code because I always get a PInvokeStackInbalance exception, telling me that

This is likely because the managed PInvoke signature does not match the unmanaged target signature.

I tried calling the method with this :

[DllImport("InferenceEngine.dll")]
extern static unsafe void Inference(double *c1, double *c2, double *c3, double *result);

I also tried this :

[DllImport("InferenceEngine.dll")]
extern static void Inference(ref double c1, ref double c2, ref double c3, ref double result);

... which were both possible ways documented on MSDN but with no luck. Does anyone have any clue about what the problem is ?

Thanks !

Upvotes: 0

Views: 1243

Answers (1)

Tim Robinson
Tim Robinson

Reputation: 54774

You should declare your C++ function as __stdcall, which is the P/Invoke default:

extern "C" _declspec(dllexport) void __stdcall Inference(double *c1, double *c2, double *c3, double *result);

It's also possible to leave the C++ prototype alone and change the P/Invoke declaration:

[DllImport("InferenceEngine.dll", CallingConvention=CallingConvention.Cdecl)]

cdecl isn't used often with P/Invoke, probably because the Windows API is stdcall.

Upvotes: 3

Related Questions