Test environment: VS2010 Windows7
1. Create a new project, select the Win32 console program, enter the project name Dll_test, then click OK
2.
3. Click Next
4. Select DLL Click Finish, click Dll_test.cpp file
extern "C" __declspec (dllexport) int add (int a,int b); int add (int a,int b) {return a+b;}
Note: (Here is a. cpp file that is not a. c file, so add extern "C") __declspec(dllexport) here syntax rules. As for the DllMain under the Dllmain.cpp file, there is no need to bother. Specifically, you can view MSDN.
4. Write the program according to the above requirements, click Generate
5. You can see that the build succeeded
6 So our DLL file is built successfully. DLL files can be viewed under the Project Debug folder
You can use depends this tool to view the function of DLL file, in File->openfile open your DLL file, you can see the function as add as we write, if not the same, the DLL has a problem.
7. Build a C # Select Windows Forms application and click OK
8. Place the DLL file you just generated under the debug file in the Bin directory (be careful not to put it in the wrong place, you will be prompted to find it),
[DllImport("Dll_test.dll", EntryPoint ="Add", CallingConvention = callingconvention . CDECL)]
Public Static extern int Add (int A,int b);
Note: The public static extern is written, followed by you to import the function return value and function name.
The first parameter represents the DLL file name to load
EntryPoint represents the function entry point, which is:
The use of DllImport needs to be added to the program: using System.Runtime.InteropServices;
In this case, C/C + + DLL files can be called.
9 Running the program:
A simple example of C # + + DLL file invocation