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.

Leave a Comment