How would you declare a DLL import signature?

this is a follow up post Using pHash from .NET

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

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

I still have

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

But now I get the 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 ph_dtc_imagehash declaration is incorrect.
What am I doing wrong here?

+6
source share
3 answers

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

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

Otherwise, the correct signature of the function in C # (return value and parameters).

+10
source

Check calling convention. If you do not specify one of the DllImport attributes, WinApi (stdcall) is used by default. You have posted a C code snippet that does not indicate a calling convention, and at least in VC ++, the default default call is cdecl.

So you should try:

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

Try explicitly setting the DllImportAttribute.CharSet property to CharSet.Auto , as if you hadn't specified it, Ansi will be the default. This can cause problems, as your declaration seems to be beautiful.

Even if this is not a problem, get used to specifying the CharSet property whenever the Dll function deals with text.

0
source

Source: https://habr.com/ru/post/890238/


All Articles