也许这个例子可以帮助你:
编写托管 DLL
要创建一个简单的托管 DLL,该 DLL 具有将两个数字相加并返回结果的公共方法,请执行以下步骤:
启动 Microsoft Visual Studio .NET 或 Microsoft Visual Studio 2005。
在文件菜单上,指向新建,然后单击项目。新建项目对话框打开。
在项目类型下,单击 Visual C# 项目。
注意在 Visual Studio 2005 中,单击项目类型下的 Visual C#。
在模板下,单击类库。
在名称文本框中,键入 sManagedDLL,然后单击确定。
在代码视图中打开 Class1.cs 文件。
要声明具有添加两个数字的方法的公共接口,请将以下代码添加到 Class1.cs 文件:
// Interface declaration.
public interface ICalculator
{
int Add(int Number1, int Number2);
};
要在类中实现此公共接口,请将以下代码添加到 Class1.cs 文件中:
// Interface implementation.
public class ManagedClass:ICalculator
{
public int Add(int Number1,int Number2)
{
return Number1+Number2;
}
}
注册托管 DLL 以与 COM 或本机 C++ 一起使用
要将托管 DLL 与 COM 或本机 C++ 一起使用,您必须在 Windows 注册表中注册 DLL 的程序集信息。为此,请按以下步骤操作:
从本机 C++ 代码调用托管 DLL
// Import the type library.
#import "..\ManagedDLL\bin\Debug\ManagedDLL.tlb" raw_interfaces_only
如果您计算机上的路径与此路径不同,请更改类型库的路径。
要声明要使用的命名空间,请将以下代码添加到 CPPClient.cpp 文件中:
using namespace ManagedDLL;
完整的代码清单
//Managed DLL
// Class1.cs
// A simple managed DLL that contains a method to add two numbers.
using System;
namespace ManagedDLL
{
// Interface declaration.
public interface ICalculator
{
int Add(int Number1, int Number2);
};
// Interface implementation.
public class ManagedClass:ICalculator
{
public int Add(int Number1,int Number2)
{
return Number1+Number2;
}
}
}
//C++ Client
// CPPClient.cpp: Defines the entry point for the console application.
// C++ client that calls a managed DLL.
#include "stdafx.h"
#include "tchar.h"
// Import the type library.
#import "..\ManagedDLL\bin\Debug\ManagedDLL.tlb" raw_interfaces_only
using namespace ManagedDLL;
int _tmain(int argc, _TCHAR* argv[])
{
// 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\n", lResult);
// Uninitialize COM.
CoUninitialize();
return 0;
}
参考:
How to call a managed DLL from native Visual C++ code in Visual Studio.NET or in Visual Studio 2005