How do I call C++/CLI from C#?

Have you take a look at C++/CLI?

Let me give a very short example. Here is the source file from a Visual C++ -> CLR -> Class Library project. It basically get Windows username and return it.

Please note that, in order to get this compiled, you have to go into project settings and mark "Additional Dependencies" as "Inherit from parent" because we are using those Windows libs (kernel32.lib, user32.lib, ..)

// CSCPP.h

#pragma once

#include "windows.h"

using namespace System;

namespace CSCPP {

    public ref class Class1
    {
        // TODO: Add your methods for this class here.
    public:
        String^ GetText(){
            WCHAR acUserName[100];
            DWORD nUserName = sizeof(acUserName);
            if (GetUserName(acUserName, &nUserName)) {
                String^ name = gcnew String(acUserName);
                return String::Format("Hello {0} !", name);
            }else{
                return gcnew String("Error!");
            }
        }
    };
}

Now created a new C# project and add reference to our first C++/CLI Class Library project. And then call the instance method.

namespace CSTester
{
    class Program
    {
        static void Main(string[] args)
        {
            CSCPP.Class1 instance = new CSCPP.Class1();
            Console.WriteLine(instance.GetText());
        }
    }
}

This gave the following result on my machine:

Hello m3rlinez !

C++/CLI is basically a managed extension over C++ standard. It allows you to utilize CLR classes and data types in your C++/CLI project and also expose this to managed language. You can created a managed wrapper for your old C++ library using this. There are some weird syntaxes such as String^ to define reference type to CLR String. I find "Quick C++/CLI - Learn C++/CLI in less than 10 minutes" to be useful here.


There are at least three ways to call unmanaged code from managed in the same process:

  1. C++/CLI
  2. Platform Invoke
  3. Wrap your C++ in a COM object

At work we use C++/CLI for this, it seems to work.


I would create a standard (non COM/Managed) Dynamic Link Library as described here and then use the DllImport attribute (platform invoke) in the c# code to access the exported functions.

The key point from that article:

Note the __declspec(dllexport) modifier in the method declarations in this code. These modifiers enable the method to be exported by the DLL so that it can be used by other applications. For more information, see dllexport, dllimport.

This is a lighter weight alternative to an actual COM interop wrapper and avoids issues such as registration etc (the DLL can simply be placed in the application directory) .

Another alternative is It Just Works (IJW). This is probably a better choice if you have managed C++ code and need to access this from other .NET languages. But this is only an option if you are able/happy to convert your unmanaged C++ to managed C++ though.