How to call a managed DLL from native Visual C++ code in Visual Studio.NET or in Visual Studio 2010
Write a Managed DLL
1、创建C#类库项目 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)” 5、执行: 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.
注册程序集
方法A: Register the Managed DLL for Use with COM or with Native C++ 1、打开“开始”菜单,“程序”,找到“Visual Studio 命令提示(2010)” 2、执行: RegAsm.exe ManagedDLL.dll /tlb:ManagedDLL.tlb /codebase 方法B: 打开方案属性 - 生成,勾选“为 COM 互操作注册” 项目打开时需要以管理员权限启动VS2010
Call the Managed DLL from Native C++ Code
1、创建Win32控制台程序项目 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. CoUninitialize(); return 0; 6、Press CTRL+F5 to run the application. 注:ICalculatorPtr 对应 C# 代码中的 ICalculator
参考:
https://support.microsoft.com/en-us/kb/828736
运行时需要在客户机注册ManagedDLL.dll
RegAsm.exe ManagedDLL.dll /codebase
取消注册:
C:\>%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\regasm.exe /unregister testManagedDLL.dll /tlb:testManagedDLL.tlb /codebase