I have a very simple function in an unmanaged DLL, but I’m not getting the correct return value back from it.
I can confirm that the general PInvoke mechanism is working with one function in my C DLL:
/* Return an integer */
extern "C" __declspec(dllexport) long get_num()
{
return 42;
}
I call the above unmanaged entry point like so from C# .NET:
[DllImport("My_C_DLL.dll")]
extern static long get_num();
// ...
long ans = get_num();
Console.WriteLine("The answer is {0}.", ans);
This works fine, but passing marshalled parameters to another function in the DLL returns a wrong result:
/* Add two integers */
extern "C" __declspec(dllexport) long add_num(long a, long b)
{
long sum = a + b;
return sum;
}
Called from C# as:
[DllImport("My_C_DLL.dll")]
extern static long add_num(long a, long b);
long a = 6, b = 12;
long sum = add_num(a, b);
Console.WriteLine("The answer is {0}.", sum);
This gives me back a result of “6”, or whatever I set the input value of a to be.
I’m guessing that some incorrect marshalling of the input values is messing up the call stack, resulting in the bad return value, but where is the error?
Two problems here. First of all C#
longdoes not match Clong. On Windows,Clong is 32 bits. Useintin your C# code to match up with your Clong.The other problem is that the calling conventions probably don’t match. You most likely have
cdeclin your C DLL but the C# default isstdcall. Fix this by changing your p/invoke.