Simple example of C # C + + DLL file invocation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.