C calls the implementation of dll written by C++

  • 2020-05-19 05:34:25
  • OfStack

To write dll, first open VS to create a new C++ console program, then select dll and empty document after the next step. And then you add a class and you add a method. Method head with fixed form of extern"C" s s 7en (dllexport). For example, the following code:

C + + dll code:


extern"C"__declspec(dllexport) char* ShowImages(BYTE img[],int w,int h){;}

C# call dll is also basically fixed format, as follows: unsafe is added here because it is useful for Pointers [no Pointers need unsafe], C# must be added with Pointers

unsafe, and the generation in the project properties allows unsafe code to be checked.

One more point is that C# calls DLL by adding a namespace


using System.Runtime.InteropServices; 

The code style is as follows:

C# calling code:


[DllImport("dll The name .dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
unsafe public static extern byte* ShowImages(byte[] src, int w, int h);

Write dll as above and most likely the reason the call failed is that there is no corresponding data type for C++ C#.

One last thing to mention is that a method with a pointer return value must be global in C++, and private in the body of the method will fail. The reason is that the body of the method is released, even though it is return, it has no effect.
I have encountered this problem before, C++ has a pointer address in return, and then C# calls it, and the data is 78 mess. At that time, I was very depressed, but I finally found out that the reason is that the pointer return will still be released when it comes out, so the data is 78 mess. The solution, of course, is to set pointer variables to global variables.


Related articles: