【发布时间】:2012-01-22 04:09:12
【问题描述】:
我在一个非托管 DLL 中有一个非常简单的函数,但我没有从中得到正确的返回值。
我可以确认通用 PInvoke 机制正在使用我的 C DLL 中的一个函数:
/* Return an integer */
extern "C" __declspec(dllexport) long get_num()
{
return 42;
}
我从 C# .NET 中调用上述非托管入口点:
[DllImport("My_C_DLL.dll")]
extern static long get_num();
// ...
long ans = get_num();
Console.WriteLine("The answer is {0}.", ans);
这工作正常,但是将编组的参数传递给 DLL 中的另一个函数会返回错误的结果:
/* Add two integers */
extern "C" __declspec(dllexport) long add_num(long a, long b)
{
long sum = a + b;
return sum;
}
从 C# 调用为:
[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);
这会返回“6”的结果,或者我将 a 的输入值设置为的任何值。
我猜是输入值的一些不正确的编组弄乱了调用堆栈,导致返回值错误,但错误在哪里?
【问题讨论】:
-
C dll 中的 sizeof(long) 是什么?
标签: c# .net pinvoke marshalling unmanaged