In C #, you can invoke C + + 's unmanaged DLL program through DllImport.
Example of a DLL in C # calling C + + in VS2010:
A. New C + + DLL program
1, new C + + Win32 project, type DLL.
The resulting file structure
Where the "MyDLLFun.cpp" file is the main source file for this project.
2. Add a method in the source file that needs to be called externally.
Here is just a two example method to add:
The method "Add" returns the number of two integers, and the method POW computes the Y-side of X and modifies the value at the parameter x address as a pointer.
The modifier extern "C" contains a double meaning: first, the target being modified by it is "extern", and secondly, the target it modifies is "C". The variables and functions modified by extern "C" are compiled and concatenated in the C language way.
The purpose of __declspec (dllexport) is to put the corresponding function into the DLL dynamic library.
The extern "C" __declspec (dllexport) is added in order to invoke DLL files of unmanaged C + + using DllImport. because using DllImport, you can only invoke DLLs made from C-language functions.
After the method is added, compile the build DLL file.
Second, use DLL programs in C #.
First, copy the newly generated copies to the C # project Bin\Debug directory.
Then, using the DllImport Import DLL program method, for ease of management, create a new class named Cppdll, and here to import the DLL method:
Description: 1) Need to reference namespace using System.Runtime.InteropServices;
2) It is recommended to increase the feature callingconvention= callingconvention.cdecl, otherwise "stack asymmetry" error may occur:
3) The methods in the DLL must be declared as Static,extern.
Finally, call these methods where needed.
Description: In C + +, the function POW is passed as a pointer, that is, the address of the variable, in C # modifier ref means "address", so int* in C + + corresponds to a ref int in C #
Three, a little extension, passing the array in the function.
Adding a function in C + +
In C + +, the function parameter is passed to the first address of an array, and the length of the array, as above. Then the corresponding in C # should be:
Where ref double ary is the address of the first element of an array of type Double, Len is the array length.
Called when it is written as:
Be lazy and use a string to see the results:
C # calls C + + DLL methods