c# - 在 c# 和 c 函数之间传递值和指针

标签 c# c++ c

我正在尝试使用开源 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/

相关文章:

c++ - 这个函数和 lambda 有什么区别?

objective-c - 在 Objective-C 中如何加二?

c - 使用 UTF-16 编码从管道读取 PowerShell 输出

c# - 如何显示 Servicestack api 站点的 "cover page"/重定向到另一个网站

c# - 编辑现有 WP8 项目时出错

c# - 生成具有方法类型的类的方法列表

c++ - 函数指针是否不支持 C++ 中的实例类型

c++ - Makefile 中的 "Optional"目标文件目标?

c# - 在 asp.net core DI 中添加通用服务

c - 跟踪日期并允许菜单选择的银行系统