C#调用C++DLL传递结构体数组的终极解决方案
作者:lqh 发布时间:2022-05-31 09:54:30
C#调用C++DLL传递结构体数组的终极解决方案
在项目开发时,要调用C++封装的DLL,普通的类型C#上一般都对应,只要用DllImport传入从DLL中引入函数就可以了。但是当传递的是结构体、结构体数组或者结构体指针的时候,就会发现C#上没有类型可以对应。这时怎么办,第一反应是C#也定义结构体,然后当成参数传弟。然而,当我们定义完一个结构体后想传递参数进去时,会抛异常,或者是传入了结构体,但是返回值却不是我们想要的,经过调试跟踪后发现,那些值压根没有改变过,代码如下。
[DllImport("workStation.dll")]
private static extern bool fetchInfos(Info[] infos);
public struct Info
{
public int OrderNO;
public byte[] UniqueCode;
public float CpuPercent;
};
private void buttonTest_Click(object sender, EventArgs e)
{
try
{
Info[] infos=new Info[128];
if (fetchInfos(infos))
{
MessageBox.Show("Fail");
}
else
{
string message = "";
foreach (Info info in infos)
{
message += string.Format("OrderNO={0}\r\nUniqueCode={1}\r\nCpu={2}",
info.OrderNO,
Encoding.UTF8.GetString(info.UniqueCode),
info.CpuPercent
);
}
MessageBox.Show(message);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
后来,经过查找资料,有文提到对于C#是属于托管内存,现在要传递结构体数组,是属性非托管内存,必须要用Marsh指定空间,然后再传递。于是将结构体变更如下。
StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct Info
{
public int OrderNO;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public byte[] UniqueCode;
public float CpuPercent;
};
但是经过这样的改进后,运行结果依然不理想,值要么出错,要么没有被改变。这究竟是什么原因?不断的搜资料,终于看到了一篇,里面提到结构体的传递,有的可以如上面所做,但有的却不行,特别是当参数在C++中是结构体指针或者结构体数组指针时,在C#调用的地方也要用指针来对应,后面改进出如下代码。
[DllImport("workStation.dll")]
private static extern bool fetchInfos(IntPtr infosIntPtr);
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct Info
{
public int OrderNO;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public byte[] UniqueCode;
public float CpuPercent;
};
private void buttonTest_Click(object sender, EventArgs e)
{
try
{
int workStationCount = 128;
int size = Marshal.SizeOf(typeof(Info));
IntPtr infosIntptr = Marshal.AllocHGlobal(size * workStationCount);
Info[] infos = new Info[workStationCount];
if (fetchInfos(infosIntptr))
{
MessageBox.Show("Fail");
return;
}
for (int inkIndex = 0; inkIndex < workStationCount; inkIndex++)
{
IntPtr ptr = (IntPtr)((UInt32)infosIntptr + inkIndex * size);
infos[inkIndex] = (Info)Marshal.PtrToStructure(ptr, typeof(Info));
}
Marshal.FreeHGlobal(infosIntptr);
string message = "";
foreach (Info info in infos)
{
message += string.Format("OrderNO={0}\r\nUniqueCode={1}\r\nCpu={2}",
info.OrderNO,
Encoding.UTF8.GetString(info.UniqueCode),
info.CpuPercent
);
}
MessageBox.Show(message);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
要注意的是,这时接口已经改成IntPtr了。通过以上方式,终于把结构体数组给传进去了。不过,这里要注意一点,不同的编译器对结构体的大小会不一定,比如上面的结构体
在BCB中如果没有字节对齐的话,有时会比一般的结构体大小多出2两个字节。因为BCB默认的是2字节排序,而VC是默认1 个字节排序。要解决该问题,要么在BCB的结构体中增加字节对齐,要么在C#中多开两个字节(如果有多的话)。字节对齐代码如下。
#pragma pack(push,1)
struct Info
{
int OrderNO;
char UniqueCode[32];
float CpuPercent;
};
#pragma pack(pop)
用Marsh.AllocHGlobal为结构体指针开辟内存空间,目的就是转变化非托管内存,那么如果不用Marsh.AllocHGlobal,还有没有其他的方式呢?
其实,不论C++中的是指针还是数组,最终在内存中还是一个一个字节存储的,也就是说,最终是以一维的字节数组形式展现的,所以我们如果开一个等大小的一维数组,那是否就可以了呢?答案是可以的,下面给出了实现。
[DllImport("workStation.dll")]
private static extern bool fetchInfos(IntPtr infosIntPtr);
[DllImport("workStation.dll")]
private static extern bool fetchInfos(byte[] infos);
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct Info
{
public int OrderNO;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public byte[] UniqueCode;
public float CpuPercent;
};
private void buttonTest_Click(object sender, EventArgs e)
{
try
{
int count = 128;
int size = Marshal.SizeOf(typeof(Info));
byte[] inkInfosBytes = new byte[count * size];
if (fetchInfos(inkInfosBytes))
{
MessageBox.Show("Fail");
return;
}
Info[] infos = new Info[count];
for (int inkIndex = 0; inkIndex < count; inkIndex++)
{
byte[] inkInfoBytes = new byte[size];
Array.Copy(inkInfosBytes, inkIndex * size, inkInfoBytes, 0, size);
infos[inkIndex] = (Info)bytesToStruct(inkInfoBytes, typeof(Info));
}
string message = "";
foreach (Info info in infos)
{
message += string.Format("OrderNO={0}\r\nUniqueCode={1}\r\nCpu={2}",
info.OrderNO,
Encoding.UTF8.GetString(info.UniqueCode),
info.CpuPercent
);
}
MessageBox.Show(message);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#region bytesToStruct
/// <summary>
/// Byte array to struct or classs.
/// </summary>
/// <param name=”bytes”>Byte array</param>
/// <param name=”type”>Struct type or class type.
/// Egg:class Human{...};
/// Human human=new Human();
/// Type type=human.GetType();</param>
/// <returns>Destination struct or class.</returns>
public static object bytesToStruct(byte[] bytes, Type type)
{
int size = Marshal.SizeOf(type);//Get size of the struct or class.
if (bytes.Length < size)
{
return null;
}
IntPtr structPtr = Marshal.AllocHGlobal(size);//Allocate memory space of the struct or class.
Marshal.Copy(bytes, 0, structPtr, size);//Copy byte array to the memory space.
object obj = Marshal.PtrToStructure(structPtr, type);//Convert memory space to destination struct or class.
Marshal.FreeHGlobal(structPtr);//Release memory space.
return obj;
}
#endregion
对于实在想不到要怎么传数据的时候,可以考虑byte数组来传(即便是整型也可以,只要是开辟4字节(在32位下)),只要开的长度对应的上,在拿到数据后,要按类型规则转换成所要的数据,一般都能达到目的。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
来源:http://blog.csdn.net/xxdddail/article/details/11781003


猜你喜欢
- 本文实例为大家分享了java实现砸金蛋抽奖的具体代码,供大家参考,具体内容如下代码如下需求:用户每一次砸金蛋,抽中一等奖的概率为2% 二等奖
- 银行卡大家都使用,在密码输错超过限制次数之后,就容易被锁死,智能到银行柜台才能解锁,那么这一功能如果实现的呢,今天小编通过实例代码给大家详细
- 本文研究的主要是Java ArrayList扩容问题实例详解的相关内容,具体介绍如下。首先我们需要知道ArrayList里面的实质的其实是一
- 本文实例为大家分享了Android实现图片点击放大的具体代码,供大家参考,具体内容如下在我的项目中,有点击图片banner后放大浏览的功能。
- C#删除只读文件的方法: if (File.GetAttributes(FFName).ToString().IndexOf("R
- 进阶JavaSE-三大接口:Comparator、Comparable和Cloneable。Comparable和Comparator这两个
- 在开发android的应用中,有时候需要限制横竖屏切换。只需要在AndroidManifest.xml文件中加入android:screen
- 当前比较成熟一点的应用基本上都会在进入应用之显示一个启动界面.这个启动界面或简单,或复杂,或简陋,或华丽,用意不同,风格也不同.下面来观摩几
- 完整代码:https://github.com/iyuanyb/Downloader多线程下载及断点续传的实现是使用 HTTP/1.1 引入
- 该功能本来可以通过拉动水平和垂直滚动条来实现,但实际使用中,用户更趋向于直接用鼠标拖动页面来实现,很多看图类软件都有这种类似的功能。而.ne
- 今天无意中发现一个圆形进度,想想自己实现一个,如下图:基本思路是这样的:1.首先绘制一个实心圆2.绘制一个白色实心的正方形,遮住实心圆3.在
- 八皇后问题(N皇后问题)的回溯法求解一、问题描述在一个国际象棋棋盘上放置八个皇后,使得任何两个皇后之间不相互攻击,求出所有的布棋方法,并推广
- 接触微信支付之前听说过这是一个坑,,,心里已经有了准备。。。我以为我没准跳坑出不来了,没有想到我填上了,调用成功之后我感觉公司所有的同事都是
- 存储结构二叉树是一种特殊的树,给个结点最多有两个子节点,并且子节点有左右之分,并且兄弟,父亲,孩子可以很方便的通过编号得到1.在二叉树的第i
- 今天为大家介绍一下语音动弹界面的实现,新版本的客户端大家应该都看过了,这里我就只简单的介绍一下控件布局了。你可以在这里看到本控件的完整源码:
- 本文实例展示了DevExpress实现GridView当无数据行时提示消息的方法,具体步骤如下:主要功能代码部分如下:/// <sum
- 前言Android中类加载器有BootClassLoader,URLClassLoader,PathClassLoader,DexClass
- jstat命令简介jstat(Java Virtual Machine Statistics Monitoring Tool)是JDK提供的
- 前言上一篇我们介绍了 Animation 和 AnimationController 的使用,这是最
- 前言对于 InterruptedException,一种常见的处理方式是 “生吞(swallow)” 它 —— 捕捉它,然后什么也不做(或者