Unmanaged C++ Dll call From Managed C# Application



Here you see the steps for using a simple C++ dll in C# in .Net Framework 4.

1. Open Visual C++ Win 32 Project

image1.gif

2. In Application Setting Chose Dll & select Empty Project

image2.gif

3. The Solution will Look like

image3.gif

4. Add New Item(*.cpp) in Source Folder

image4.gif

5. Select cpp File

image5.gif

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


image7.gif


8. Now Solution Explorer will looks like

image8.gif

9. After Compile you will see the Debug Folder as

image9.gif

10. Now Our Unmanaged Dll is Ready. We build a Managed C# App

image10.gif

11. Design is like

image11.gif

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

image13.gif

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
 

Up Next
    Ebook Download
    View all
    Learn
    View all