Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Calling Unmanaged C++ Function By C# Using Visual Studio

DZone's Guide to

Calling Unmanaged C++ Function By C# Using Visual Studio

·
Free Resource
Use interop.

In C++, create a dll:

Cpp.h

extern "C" __declspec(dllexport)
                          int add(int a, int b);


Cpp.cpp

int add(int a, int b)
{
	return a + b;
}



In C#, write a wrapper to make use of that function:


using System.Runtime.InteropServices;

// Imports the CPP DLL
namespace ManagedMain
{
    public class Cpp
    {
        [DllImport(
            "Cpp.dll", 
            EntryPoint = "add",
            ExactSpelling = false
            )]
        public static extern Int32 add(Int32 a, Int32 b);
    }
}


and finally make use of it as if it was a ordinary C# member:

Somewhere.cs

this.lbResult.Text = Cpp.add(a, b).ToString();


Why would you do this? Well, the C++-Code may be more performant.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}