C#调用C++编写的DLL
1 把DLL放在C#工程的Debug文件夹跟Release文件夹,我这里是使用X86编译的就放在了这两文件夹
2 用DLL查看器 Viewdll.exe 查看DLL导出的函数如下图
3 调用代码如下:
using System.Runtime.InteropServices; //包含DllImport的using指令
namespace TB { public partial class FormTB : Form {
//声明外部DLL的函数,这里的DLL函数接口已经从文档得知
[DllImport("USER_COM.dll", EntryPoint = "OpenCOM", CallingConvention = CallingConvention.Cdecl)] public static extern bool OpenCOM(); [DllImport("USER_COM.dll", EntryPoint = "Close_COM", CallingConvention = CallingConvention.Cdecl)] public static extern void Close_COM(); [DllImport("USER_COM.dll", EntryPoint = "COM_RX", CallingConvention = CallingConvention.Cdecl)] public static extern int COM_RX(byte[] RX_buff); [DllImport("USER_COM.dll", EntryPoint = "COM_Send", CallingConvention = CallingConvention.Cdecl)] public static extern int COM_Send(byte cmd, byte data1, byte data2); public FormTB() { InitializeComponent(); } //这里以调用DLL里的OpenCOM()为例 public Thread rec; private void FormTB562_Load(object sender, EventArgs e) { bool op= OpenCOM(); //调用DLL的函数 Console.WriteLine(" op = " + op);
}
} }
如上程序所示,
(1)调用dll需要引用命名空间
using System.Runtime.InteropServices;
(2) USER_COM.dll 为外部调用的DLL
(3) CallingConvention
是指示入口点的调用约定,默认情况下,C 和 C++ 使用的 Cdecl 调用,如果 DLL 里包含有 __stdcall
的关键字, CallingConvention
要设置成 CallingConvention.StdCall
(4) 声明外部函数则使用 public static extern
本文来自博客园,作者:白菜没我白,转载请注明原文链接:https://www.cnblogs.com/xingboy/p/11158487.html