gpt4 book ai didi

c# - DLLImport:传递短类型参数

转载 作者:行者123 更新时间:2023-11-28 01:09:25 25 4
gpt4 key购买 nike

我正在尝试将短类型的参数传递给从 DLL 导入的 C++ 非托管函数。在我的 C++ DLL 代码中,我有以下函数:

__declspec(dllexport)void ChangeIcon(char *executableFile, char *iconFile,
UINT16 imageCount)
{
// Some code, doesn't matter
}

在 C# 托管代码中,我使用以下代码导入此函数:

[DllImport("IconChanger.dll")]
static extern void ChangeIcon(string executableFile, string iconFile,
ushort imageCount);

然后我称它为:

ushort imageCount = 2;
ChangeIcon("filePath", "iconPath", imageCount);

应用程序很好地执行了函数;但是,会弹出带有以下文本的消息:

Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'foo.exe'. Additional Information: A call to PInvoke function 'bar.IconChanger::ChangeIcon' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

如果我不传最后一个参数,消息就不会弹出,所以肯定是传了short类型的缘故。我也尝试过使用 int,出现了同样的消息。

显然,我在传递这个数值参数时做错了什么。两者之间如何匹配参数?

最佳答案

确保调用约定匹配。如果您未指定调用约定,则假定为 StdCall。但是,对于 C/C++,标准调用约定是 Cdecl。因此,要么在 C++ 函数上使用 __stdcall:

void __declspec(dllexport) __stdcall ChangeIcon(char *executableFile, char *iconFile,
UINT16 imageCount)
{
// Some code, doesn't matter
}

或在 DllImport 上指定 CallingConvention.Cdecl:

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

作为旁注,UInt16不是 CLS 兼容类型,因此您可能需要 Int16如果您需要这种合规性。

关于c# - DLLImport:传递短类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4189468/

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