Here, you will learn the steps for using a simple C++ DLL in C# in .NET Framework 4.
Open Visual C++ Win 32 Project.
In Application Settings, chose "DLL" and select "Empty Project".
The solution will look like the following.
Add New Item (*.cpp) in the Source folder.
Select the C++ (.cpp) File type.
Write down the following simple code in this .cpp file.
- #include < stdio.h >
-
- extern "C" {
- __declspec(dllexport) int add(int a, int b) {
- return a + b;
- }
- __declspec(dllexport) int subtract(int a, int b) {
- return a - b;
- }
- }
Now, export *.res file in the "Resource" folder for version information.
Now, the Solution Explorer will look like the following.
After compiling, you will see the Debug folder as below.
Now, our Unmanaged DLL is ready. Let us build a Managed C# App.
The design is like this.
The code is as follows.
- [DllImport("OurDll.dll", CallingConvention = CallingConvention.Cdecl)]
- publicstaticexternint subtract(int a, int b);
-
- privatevoid button2_Click(object sender, EventArgs e) {
- int x = Convert.ToInt32(textBox1.Text);
- int y = Convert.ToInt32(textBox2.Text);
- int z = subtract(x, y);
- MessageBox.Show("Required Answer is " + Convert.ToString(z), "Answer", MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
The output will be like this.
In case of the previous version of .NET (3.5), the code will be like below.
- [DllImport("OurDll.dll")]
- publicstaticexternint subtract(int a, int b);
-
- privatevoid button2_Click(object sender, EventArgs e) {
- int x = Convert.ToInt32(textBox1.Text);
- int y = Convert.ToInt32(textBox2.Text);
- int z = subtract(x, y);
- MessageBox.Show("Required Answer is " + Convert.ToString(z), "Answer", MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
The output will be the same for both.
Explanation
extern "C" helps to show all code within brackets from outside.
__declspec(dllexport) int add(int a,int b) is a prefix which makes DLL functions available from your external application.
In .NET Framework 3.5 or the previous version, the code is like -
- [DllImport("OurDll.dll")]
- publicstaticexternint add(int a, int b);
For ..NET 4 and above, the code will be liek this.
- [DllImport("OurDll.dll", CallingConvention = CallingConvention.Cdecl)]
- publicstaticexternint add(int a,int b);
If you only write framework 3.5 [DllImport("OurDll.dll")], you get an exception -
"… the managed PInvoke signature does not match the unmanaged signature …"
Now, you can call a C++ dll from your C# application (.NET Framework 4)
Thank You!