接到好兄弟提出的一个功能需求,需要用C#调用一个C++DLL中的函数并实现回调。经过查阅资料并实际验证,实现了这个功能,特记录备查。
01 新建类并引入命名空间
纯粹是执行API的话,通常的做法是建立一个静态的类,用C#把非托管DLL封装起来。 设置一个静态类
public static class Win32
{
// code
}
引入命名空间
using System.Runtime.InteropServices;
02 引入DLL中的函数
做到这一步,就能在类里声明引入DLL中的函数了,用法如下:
[DllImport(api.dll)] //指明DLL文件名,将该文件放在与程序在同一文件夹下即可正常调用
public static extern int Connect(string ip, ushort port, string username, string password);
//对应原函数定义:int Connect(const char* ip, uint16_t port, const char* username, const char* password);
未完待续
这个内容有很多要记的,先记录一点,有空再补。