你会如何声明DLL导入签名?

这是使用.NET的pHash的后续post

您如何在.NET中声明以下C ++声明?

int ph_dct_imagehash(const char* file,ulong64 &hash); 

到目前为止我有

 [DllImport(@"pHash.dll")] public static extern int ph_dct_imagehash(string file, ref ulong hash); 

但我现在正在跟踪错误

 ulong hash1 = 0, hash2 = 0; string firstImage = @"C:\Users\dance2die\Pictures\2011-01-23\177.JPG"; string secondImage = @"C:\Users\dance2die\Pictures\2011-01-23\176.JPG"; ph_dct_imagehash(firstImage, ref hash1); ph_dct_imagehash(secondImage, ref hash2); 

在此处输入图像描述

它基本上说我的ph_dtc_imagehash声明是错误的。
我在这做错了什么?

堆栈不平衡表示C ++代码使用cdecl而您的C#使用stdcall调用约定。 将您的DLLImport更改为:

 [DLLImport(@"pHash.dll", CallingConvention=CallingConvention.Cdecl)] 

C#中的函数签名(返回值和参数)是正确的。

检查调用约定。 如果未在DllImport属性上指定一个,则默认为WinApi(stdcall)。 您发布的C片段未指定调用约定,并且至少在VC ++中,默认调用约定为cdecl。

所以你应该尝试:

 [DllImport(@"pHash.dll", CallingConvention=CallingConvention.Cdecl)] public static extern int ph_dct_imagehash(string file, ref ulong hash); 

尝试将DllImportAttribute.CharSet属性显式设置为CharSet.Auto ,就像您没有指定它一样,它将默认为Ansi 。 这可能会导致问题,因为您的声明似乎没问题。

即使这不是问题,每当Dll函数处理文本时,都要习惯指定CharSet属性。