gpt4 book ai didi

c# - PInvoke 整数编码返回不正确的结果

转载 作者:行者123 更新时间:2023-12-04 00:47:02 27 4
gpt4 key购买 nike

我在非托管 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# long 与 C long 不匹配。在 Windows 上,C long 是 32 位。在您的 C# 代码中使用 int 以匹配您的 C long

另一个问题是调用约定可能不匹配。您的 C DLL 中很可能有 cdecl,但 C# 默认是 stdcall。通过更改您的 p/invoke 来解决此问题。

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

关于c# - PInvoke 整数编码返回不正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8537440/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com