c# - 对 PInvoke 函数 xxx 的调用使堆栈不平衡

标签 c# c marshalling output-parameter

我在控制台应用程序中的 C# 代码 (.net 4.0) 中使用 C DLL,但遇到了问题。 当我调用 C 方法时,它引发以下异常。

"A call to PInvoke function 'ProcessFilesC' 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代码

    int ProcessFilesC(
        char **p_FilesOrDirs,
        ImageInfoC **p_vecImageInfo,
        int ***p_vecStackIndexes,
        RectC ***p_vecFaces
    );    

这是我的 C# 代码

    [DllImport(@"..\ref\myCApp.dll", CallingConvention = CallingConvention.StdCall)]
    unsafe private static extern UInt16 ProcessFilesC(
               String[] p_FilesOrDirs,
               ref ImageInfoC[] p_vecImageInfo,
               out Int32[] p_vecStackIndexes,
               out RectC[] p_vecFaces
            );


    public unsafe struct ImageInfoC
    {            
        public String resizedFilePath;      //char*   (in C)
        public Byte isUsable;               //unsigned char (in C)
        public UInt32 imageId;              //long int in (in C)
        public UInt16 stackIndex;           //int (in C)
        public Boolean isBestPhoto;         //unsigned char  (in C)
    }

下面是调用该方法的 C# 代码

    unsafe
        {
             iResult = ProcessFilesC(
                              p_FilesOrDirs,          // Value getting passed to DLL
                              ref p_vecImageInfo,
                              out p_vecStackIndexes,
                              out p_vecFaces
                        );
             Console.WriteLine("ProcessFilesC Complete");
        }

当代码到达此处时,我可以看到该方法正在处理,因为它在控制台中打印,但处理后,它引发了上述异常。

我猜这是由于 C DLL 试图在输出/引用参数中写入值。 我不明白问题出在哪里或者我的代码出了什么问题。

请注意,我已经在“工具”->“选项”->“调试”->“常规”中取消选中“抑制模块加载时的 JIT 优化”选项

请尽快提供帮助。

感谢您花费宝贵的时间阅读这篇文章。

谢谢, 基兰

最佳答案

首先要检查的是调用约定。在大多数情况下,DllImport 属性中指定的调用约定与 native DLL 中的实际调用约定不同。

关于c# - 对 PInvoke 函数 xxx 的调用使堆栈不平衡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15969097/

相关文章:

c# - 如何通过套接字编码(marshal) .Net 接口(interface)?

java - 多个 JaxB 编码配置文件

c# - 在 Azure 或 Amazon 上托管控制台应用程序,可能吗?

c# - 测试接口(interface)是否支持某个方法并调用它的最佳实践是什么?

c - 实现快速选择算法以找到第 k 个最小的数字

arrays - 编码 slice 结果为字符串

c# - 有没有比序列化 XML 更好的东西来在 C# 中存储可以在我自己的程序集中编译的简单数据库?

c# - 如何使用wordProcessingDocument加载wordopenxml(字符串形式)

c - sizeof union 大于预期。这里如何进行类型对齐?

c - 在C程序中添加Shellcode时会打印出Hello World