类别:程序开发

日期:2022-09-23 浏览:1770 评论:0

最近在编写C#上位机应用程序,需要调用C++的dll,期间遇到dll接口库中char*类型纠结了很久,试过string,StringBuilder,StringBuilder结果都以失败告终,通过查找博客等资料最后找到了救命稻草---IntPtr。例子如下:

C++dll接口函数:

void JT_ReaderVersion(int icomID,char* szReaderVersion,int iRVerMaxLength char* szAPIVersion, int iAPIVerMaxLength);

szReaderVersion和 szAPIVersion参数作为输出参数需要返回其所在地址上的字符串内容。

C#调用该接口函数声明:

[DllImport("JKT135_SD.dll",CharSet=CharSet.Ansi)]
        //①public static extern void JT_ReaderVersion(int iComID, ref StringBuilder szReaderVersion, int iRVerMaxLength, ref StringBuilder szAPIVersion, int iAPIVerMaxLength);
        //②public static extern void JT_ReaderVersion(int iComID, ref Byte[] szReaderVersion, int iRVerMaxLength, ref Byte[] szAPIVersion, int iAPIVerMaxLength);
        //③public static extern void JT_ReaderVersion(int iComID, ref String szReaderVersion, int iRVerMaxLength, ref String szAPIVersion, int iAPIVerMaxLength);
        public static extern void JT_ReaderVersion(int iComID, IntPtr szReaderVersion, int iRVerMaxLength, IntPtr szAPIVersion, int iAPIVerMaxLength);

其间通过查找资料试过StringBuilder,Byte[],string如上面方法①②③所示均失败,提示:有未经处理的异常:0xC0000005:读取位置0xXXXXXX时发生访问冲突。

最后尝试IntPtr类型成功。


注意:访问时需要先为IntPtr分配内存空间,例如:

IntPtr szReaderVersion = Marshal.AllocHGlobal(100);
IntPtr szAPIVersion = Marshal.AllocHGlobal(100);
JKT135_SDdllInterface.JT_ReaderVersion(int.Parse(JT_ReaderVersion_comboBox.Text),  szReaderVersion, int.Parse(iRVerMaxLength_comboBox.Text),  szAPIVersion, int.Parse(iAPIVerMaxLength_comboBox.Text));


本文标题:C#调用C++dll,C++中char*与C#类型的对应关系
本文链接:https://vtzw.com/post/1059.html
作者授权:除特别说明外,本文由 零一 原创编译并授权 零一的世界 刊载发布。
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。
 您阅读本篇文章共花了: 

 可能感兴趣的文章

评论区

发表评论 / 取消回复

必填

选填

选填

◎欢迎讨论,请在这里发表您的看法及观点。