C# P/Invoke问题(堆栈不平衡) 我试图用P/Unjk./p>为一个本地C++ ++编写包装器。

C# P/Invoke问题(堆栈不平衡) 我试图用P/Unjk./p>为一个本地C++ ++编写包装器。,c#,c++,pinvoke,C#,C++,Pinvoke,.dll的源代码指定了以下入口点: // .h-file CHROMAPRINT_API ChromaprintContext *chromaprint_new(int algorithm); 以及方法实现: // .cpp-file ChromaprintContext *chromaprint_new(int algorithm) { ChromaprintContextPrivate *ctx = new ChromaprintContextPrivate(); ctx-&

.dll的源代码指定了以下入口点:

// .h-file
CHROMAPRINT_API ChromaprintContext *chromaprint_new(int algorithm);
以及方法实现:

// .cpp-file
ChromaprintContext *chromaprint_new(int algorithm)
{
    ChromaprintContextPrivate *ctx = new ChromaprintContextPrivate();
    ctx->algorithm = algorithm;
    ctx->fingerprinter = new Fingerprinter(CreateFingerprinterConfiguration(algorithm));
    return (ChromaprintContext *)ctx;
}
ChromaprintContextPrivate类型是一种结构:

>// .cpp-file
struct ChromaprintContextPrivate {
    int algorithm;
    Fingerprinter *fingerprinter;
    vector<int32_t> fingerprint;
};
调用
IntPtr ptr=Chromaprint\u New(0)引发以下MDA异常:
对PInvoke函数“MyProject.ChromaprintWrapper!”的调用MyProject.ChromaprintWrapper.LibChromaPrint::chromaprint_new'使堆栈不平衡。这可能是因为托管PInvoke签名与非托管目标签名不匹配。检查PInvoke签名的调用约定和参数是否与目标非托管签名匹配

因此,我了解问题所在(堆栈上的条目数不是预期的)。我假设方法参数
int-algorithm
正常。但我不确定退货类型。它应该是一个结构而不是指针吗

我通过运行.h文件获得了上面的C#代码。返回类型是否错误?应该是什么

什么是
矢量指纹的C#表示

(请参见上面的ChromaprintContextPrivate
结构。)

这是因为参数的实际传递方式,即调用约定

试一试


您很可能需要指定调用约定

请尝试以下操作:

[System.Runtime.InteropServices.DllImportAttribute("libchromaprint.dll", 
     EntryPoint = "chromaprint_new",
     CallingConvention=CallingConvention.Cdecl)]

默认情况下,使用(实际上是STDCALL)使调用Windows API更容易,但这通常不是大多数C++库的默认值。

< p>您需要在DLimPurt属性上声明CDECL调用约定。< /P>
[DllImport("libchromaprint.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr chromaprint_new(int algorithm);
[System.Runtime.InteropServices.DllImportAttribute("libchromaprint.dll", 
     EntryPoint = "chromaprint_new",
     CallingConvention=CallingConvention.Cdecl)]