Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Calling unmanaged C++ function by C# using Visual Studio (See related posts)

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.


You need to create an account or log in to post comments to this site.


Click here to browse all 7278 code snippets

Related Posts