I already had to do this, and I took a slightly different approach (I tested this procedure in Visual Studio 2012 and 2013).
For the test, I created a C # DLL, called the LibraryCSharp.dll , with the following class and namespace:
using System;
using System.Collections.Generic;
using System.Text;
namespace BibliotecaCSharp
{
public class Teste
{
public int Soma(int a, int b)
{
return a + b;
}
}
}
Now, on the C ++ side, in another project, to run a code from a library in .Net (be it C #, VB etc), the C ++ project must be configured to support the CLR, as shown in the figure: p>
![](https://i.stack.imgur.com/LWufN.png)
Oncetheprojectisconfigured,itisnecessarytoimporttherequiredlibraries,whichisdonewithinthestdafx.h
fileofyourprojectinC++,justaddtheselinestoit:
//Includesebibliotecasespecíficasdoruntimepara.Net#include<mscoree.h>#include<vcclr.h>#pragmacomment(lib,"mscoree.lib")
From now on, you can instantiate classes written in C #, or VB.Net directly from within the C ++ code.
This example project in C ++ is a simple console application, with only one cpp file, but it serves to demonstrate the technique:
#include "stdafx.h"
//Em todos os arquivos que forem acessar a classe, deve-se
//importar as bibliotecas e namespaces
#using <mscorlib.dll>
#using "<CAMINHO DA DLL EM C#>\BibliotecaCSharp.dll"
using namespace System;
using namespace BibliotecaCSharp;
int SomaCSharp(int a, int b)
{
//Cria uma instância da classe desejada
Teste^ t = gcnew Teste();
return t->Soma(a, b);
}
int _tmain(int argc, _TCHAR* argv[])
{
int s = SomaCSharp(1, 2);
_tprintf(TEXT("Soma em C#: %d\n"), s);
return 0;
}
However, as it is, the code in C ++ will give error during execution, because #using "<CAMINHO DA DLL EM C#>\BibliotecaCSharp.dll"
is only for the compiler to find the library, and not for the program to find the library when is running.
To this end, I always copy the dll in C # to the same folder as the executable in C ++, as shown in the figure below:
![](https://i.stack.imgur.com/GqGI5.png)
ItwouldbepossibletocopytoanotherfolderaslongasitisinthePATHsystem,butIfindthesolutiontousethesamefoldersimpler.
Justasacuriosity,thiscopycanbeautomatedthroughthePost-buildeventcommandline,asshowninthefigure: