C#调用C++dll,C++中char*与C#类型的对应关系

来源:互联网 发布:网络语言的利弊作文 编辑:程序博客网 时间:2024/05/21 10:12

最近在编写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));


0 0
原创粉丝点击