1. Open Visual C++ Win 32 Project
2. In Application Setting Chose Dll & select Empty Project
3. Add New Item(*.cpp) in Source Folder
4. Select cpp File
5. Write Down the simple Code in cpp file:
#include
extern "C"
{
__declspec(dllexport) int add(int a,int b)
{
return a+b;
}
__declspec(dllexport) int subtract(int a,int b)
{
return a-b;
}
}
6. After Compile you will see the Debug Folder have example.dll and example.lib files.
7. Then create c# console application
8. Code is as follows
[DllImport("example.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);
}
9. In case of Previous Version of .net Code will be (3.5)
Collapse | Copy Code
[DllImport("example.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);
}
10. For .net Frame Work 4 the code will be,
[DllImport("example.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int add(int a,int b);
Note: Out put will be same for both
Now you can call an C++ dll from your C# application (.net frame work 4)