我正在尝试使用开源 DLL 在 C# 大学项目中的不同方言之间转换 SQL 查询。我在 dll 中有一个函数,它需要一个指向对象的 void 类型指针。我在 c# 中找不到合适的类型来调用这个函数。
我已经尝试使用 IntPtr 作为指向对象的所需指针,但出现以下错误
A call to PInvoke function 'WindowsFormsApp1!WindowsFormsApp1.Form1::SetParserTypes' 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.
c/c++中的函数:
void SetParserTypes(void *parser, short source, short target)
{
if(parser == NULL)
return;
SqlParser *sql_parser = (SqlParser*)parser;
// Run conversion
sql_parser->SetTypes(source, target);
}
我试图在 C# 中使用的函数:
[DllImport(dllName: "DLL_LOCATION", EntryPoint = "SetParserTypes")]
public unsafe static extern void SetParserTypes(void *parser , short source, short target);
我是这样调用这个函数的:
SetParserTypes(&parserObj, 1,2);
在c#中调用函数时出现以下异常
Managed Debugging Assistant 'PInvokeStackImbalance' : 'A call to PInvoke function 'WindowsFormsApp1!WindowsFormsApp1.Form1::SetParserTypes' 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.'
最佳答案
这至少是因为您的参数parser
的类型,它应该声明为System.IntPtr
而不是void*
。
有关 C# 和 C++ 之间类型映射的更多信息,请查看:https://learn.microsoft.com/en-us/dotnet/framework/interop/marshaling-data-with-platform-invoke
关于c# - 在 c# 和 c 函数之间传递值和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56865381/