调用PInvoke函数xxx使堆栈不平衡

本文关键字:堆栈 不平衡 xxx PInvoke 函数 调用 | 更新日期: 2023-09-27 18:08:43

我在控制台应用程序中使用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试图在输出/ref参数中写入值。我不知道哪里是问题或什么是错误的在我的代码。

请注意,我已经取消了"在模块加载上抑制JIT优化"选项,在工具->选项->调试->常规

请尽快提供帮助。

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

谢谢,Kiran

调用PInvoke函数xxx使堆栈不平衡

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