您的位置:首页 > 编程语言 > C#

C#中如何调用C++编写的DLL

2004-11-03 10:48 549 查看
c++经过这么多年的发展已经积累了大量的动态连接库,如果能够在.net环境里应用这些函数库,
可以很大的提高整个应用的开发速度。
使用c++编程的人员肯定对指针不会感到陌生,由于c++中的函数接口好多都可能定义成位指针,
而c#中只有在声明为unsafe code中才能够使用指针。如果想让c++的DLL支持在C#中调用,
那么在C++接口的声明中需要使用下面的这种格式:
extern "C" __declspec(dllexport) void __stdcall popMessage(char* message)
{
MessageBox(NULL, message, "C message from C#!", MB_OK);
}
并且在c#类声明中使用如下的导入编译好的DLL,例如:

[ DllImport( "test.dll", CallingConvention=CallingConvention.Cdecl )]
public static extern void Message(string theMessage);
当然你可以从一个DLL中导入多个方法的声明,例如:
[ DllImport( "test.dll", CallingConvention=CallingConvention.Cdecl )]
public static extern void Func1(string theMessage);
[ DllImport( "test.dll", CallingConvention=CallingConvention.Cdecl )]
public static extern void Func2(string theMessage);
[ DllImport( "test.dll", CallingConvention=CallingConvention.Cdecl )]
public static extern void Func3(string theMessage);

然后你可以在你的c#类中调用上面声明的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dll c# c string c++ .net