Here you see the steps for using a simple C++ dll in C# in .Net Framework 4.
1. Open Visual C++ Win 32 Project
2. In Application Setting Chose Dll & select Empty Project
3. The Solution will Look like
4. Add New Item(*.cpp) in Source Folder
5. Select cpp File
6. Write Down the simple Code in 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;
}
}
7. Now export *.res file in Resource Folder For Version information
8. Now Solution Explorer will looks like
9. After Compile you will see the Debug Folder as
10. Now Our Unmanaged Dll is Ready. We build a Managed C# App
11. Design is like
12. Code is as follows
[DllImport("OurDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int subtract(int a, int b);
private void 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);
}
13. Out put will be
14. In case of Previous Version of .net Code will be (3.5)
[DllImport("OurDll.dll")]
public static extern int subtract(int a, int b);
private void 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);
}
15. Out put will be same for both
Few Words:
extern "C"-> which help to show all code within brackets from outside
__declspec(dllexport) int add(int a,int b)-> a prefix which makes DLL functions available from your external application
In .net Frame Work 3.5 or Previous the code is like
[DllImport("OurDll.dll")]
public static extern int add(int a, int b);
For .net Frame Work 4 the code will be,
[DllImport("OurDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int add(int a,int b);
if only write, like framework 3.5 [DllImport("OurDll.dll")]
you get an exception like … the managed PInvoke signature does not match the unmanaged signature …"
--------------------------------------
Now you can call an C++ dll from your C# application (.net frame work 4)
Thank You!
Tanmay Sarkar