c#如何调用C++编写的动态连接库(dll)?

Jerry-He 2010-11-10 09:15:07
我想用C#调用CH375芯片官方提供的C++动态连接库,其主要的两个函数定义如下:

BOOL WINAPI CH375ReadData( // 读取数据块
ULONG iIndex, // 指定CH375设备序号
PVOID oBuffer, // 指向一个足够大的缓冲区,用于保存读取的数据
PULONG ioLength ); // 指向长度单元,输入时为准备读取的长度,返回后为实际读取的长度

BOOL WINAPI CH375WriteData( // 写出数据块
ULONG iIndex, // 指定CH375设备序号
PVOID iBuffer, // 指向一个缓冲区,放置准备写出的数据
PULONG ioLength ); // 指向长度单元,输入时为准备写出的长度,返回后为实际写出的长度

我在网上找了相关的资料,知道C#调用C++动态连接库方法
[DllImport("CH375DLL.DLL", EntryPoint = "CH375ReadData", ExactSpelling = false, SetLastError = true)]
public static extern bool CH375ReadData(?, ?, ?);//读单片机缓存

[DllImport("CH375DLL.DLL", EntryPoint = "CH375WriteData", ExactSpelling = false, SetLastError = true)]
public static extern bool CH375WriteData(?, ?, ?); //写单片机缓存

问题1: C++中函数中的这些参数, 我在C#中以什么参数类型与其对应?
问题2: 能否给个简单的列子,如:发送一段字符串指令

望哪位朋友帮帮忙,这问题捆扰很长时间了,先谢谢了!!!
...全文
308 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
u010562244 2013-06-11
  • 打赏
  • 举报
回复
哥们,最近我也在搞CH375的上位机,能不能看下你的例子?
Jerry-He 2010-11-28
  • 打赏
  • 举报
回复
谢谢大家的回帖,我已问官方拿到一个例子了,如果哪位有需要可以联系我!
bloodish 2010-11-11
  • 打赏
  • 举报
回复
确实疏忽了,请改用uint
gomoku 2010-11-11
  • 打赏
  • 举报
回复
倒也没有必要AllocHGlobal和FreeHGlobal,可以直接传byte[]。
不过1楼bloodish朋友的代码中ref ulong要改为ref uint。


uint index = ...; //uint
uint length = 1024; //uint
byte[] buffer = new byte[length];

CH375ReadData(index, buffer, ref length);
mjp1234airen4385 2010-11-11
  • 打赏
  • 举报
回复
使用完了记得释放内存:Marshal.FreeHGlobal(pointer);
mjp1234airen4385 2010-11-11
  • 打赏
  • 举报
回复
支持2楼的做法。
int iLen = 2048;
IntPtr pointer = Marshal.AllocHGlobal(iLen);
CH375ReadData(iIndex, pointer, ref iLen) ;
chazikai24 2010-11-11
  • 打赏
  • 举报
回复
public static extern  bool CH375ReadData(uint iIndex, System.IntPtr oBuffer, ref uint ioLength) ;


public static extern  bool CH375WriteData(uint iIndex, System.IntPtr iBuffer, ref uint ioLength) ;


第二个问题得看看那个dll的接口说明,或者是dll的demo测试程序。
像我一般拿到这个类,都附带接口说明,以及test程序的
bloodish 2010-11-11
  • 打赏
  • 举报
回复
[DllImport("CH375DLL.DLL", EntryPoint = "CH375ReadData", ExactSpelling = false, SetLastError = true)]
public static extern bool CH375ReadData(ulong iIndex, byte[] oBuffer, ref ulong ioLength);//读单片机缓存

[DllImport("CH375DLL.DLL", EntryPoint = "CH375WriteData", ExactSpelling = false, SetLastError = true)]
public static extern bool CH375WriteData(ulong iIndex, byte[] iBuffer, ref ulong ioLength); //写单片机缓存


oBuffer和iBuffer传入之前,请事先在托管这一级开辟好内存.

至于想写string,可把string转成byte[]再写.

string msg = "hello world";
byte[] buffer = Encoding.Default.GetBytes(msg);

110,526

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧