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

master chief picture master chief · Feb 6, 2010 · Viewed 83.5k times · Source

I have a class implemented in C++ that's responsible for the arithmetic computation of the program, and an interface using WPF. I process the input with C# but then how can I use my C++ class?

I've seen some comments about making a managed C++ wrapper class to interact with it, but I don't know where to start. Nor do I know how I'd go to compile it along with all the other code. I can't really find a tutorial on this, and the stuff google shows on managed C++ doesn't really seem helpful.

Anything out there to help me out? This doesn't seem unreasonable to me.

EDIT Tried m3rLinEz solution but it's giving me a BadImageFormatException, I think it's because the DLL isn't generated. I did everything as told, dunno what happened. Any ideas?

Answer

Gant picture Gant · Feb 6, 2010

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.