C++ 调用 C# dll

How to call a managed DLL from native Visual C++ code in Visual Studio.NET or in Visual Studio 2010

Write a Managed DLL

2、add the following code to the Class1.cs file:
// Interface declaration.
public interface ICalculator
    int Add(int Number1, int Number2);
3、To implement this public interface in a class, add the following code to the Class1.cs file:
// Interface implementation.
public class ManagedClass:ICalculator
    public int Add(int Number1,int Number2)
            return Number1+Number2;
4、打开“开始”菜单,“程序”,找到“Visual Studio 命令提示(2010)”
sn.exe -k MyKeyFile.SNK
6、Copy the MyKeyFile.SNK file to your project folder.
7、Double-click the AssemblyInfo.cs file to open the file in Solution Explorer.
8、Replace the following lines of code in the AssemblyInfo.cs file
[assembly: ComVisible(false)]
[assembly: AssemblyDelaySign(false)]
with the following.
[assembly: ComVisible(true)] 
[assembly: AssemblyDelaySign(false)] 
9、开发项目属性 - 签名,勾选“为程序集签名”,选择MyKeyFile.SNK文件
10、Press CTRL+SHIFT+B to generate the managed DLL.


Register the Managed DLL for Use with COM or with Native C++
1、打开“开始”菜单,“程序”,找到“Visual Studio 命令提示(2010)”
RegAsm.exe ManagedDLL.dll /tlb:ManagedDLL.tlb /codebase

打开方案属性 - 生成,勾选“为 COM 互操作注册”

Call the Managed DLL from Native C++ Code

2、Open the CPPClient.cpp file in Code view.
3、To import the type library that RegAsm.exe generates, add the following code to the CPPClient.cpp file:
// Import the type library.
#import "..\ManagedDLL\bin\Debug\ManagedDLL.tlb" raw_interfaces_only
Change the path of the type library if the path on your computer differs from this path.
4、To declare the namespace to use, add the following code to the CPPClient.cpp file:
using namespace ManagedDLL;

5、To call the managed DLL, add the following code to the _tmain function:
// Initialize COM.
HRESULT hr = CoInitialize(NULL);

// Create the interface pointer.
ICalculatorPtr pICalc(__uuidof(ManagedClass));

long lResult = 0;

// Call the Add method.
pICalc->Add(5, 10, &lResult);

wprintf(L"The result is %d", lResult);

// Uninitialize COM.
return 0;

6、Press CTRL+F5 to run the application.

注:ICalculatorPtr 对应 C# 代码中的 ICalculator



C:\>%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\regasm.exe /unregister testManagedDLL.dll /tlb:testManagedDLL.tlb /codebase