How would you declare DLL import signature?

2019-04-28 03:37发布

this is a follow-up post of Using pHash from .NET

How would you declare following C++ declaration in .NET?

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

So far i have

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

But I am now getting following error for

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);

enter image description here

It basically says that my declartion of ph_dtc_imagehash is wrong.
What am I doing wrong here?

3条回答
Juvenile、少年°
2楼-- · 2019-04-28 03:57

Check the calling convention. If you don't specify one on the DllImport attribute, it defaults to WinApi (stdcall). The C snippet you posted doesn't specify a calling convention, and at least in VC++ the default calling convention is cdecl.

So you should try:

[DllImport(@"pHash.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern int ph_dct_imagehash(string file, ref ulong hash);
查看更多
小情绪 Triste *
3楼-- · 2019-04-28 04:02

Try explicitly setting DllImportAttribute.CharSet property to CharSet.Auto as if you don't specify it, it will default to Ansi. This may be causing issues as your declaration seems to be fine.

Even if this is not the issue, take habit of specifying the CharSet property whenever a Dll function deals with text.

查看更多
戒情不戒烟
4楼-- · 2019-04-28 04:04

Stack imbalance indicates that the C++ code uses cdecl and your C# uses stdcall calling convention. Change your DLLImport to this:

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

The function signature in C# (return value and parameters) is otherwise correct.

查看更多
登录 后发表回答