C#调用C++DLL传递结构体数组的终极解决方案
C#调用C++DLL传递结构体数组的终极解决方案
在项目开发时,要调用C++封装的DLL,普通的类型C#上一般都对应,只要用DllImport传入从DLL中引入函数就可以了。但是当传递的是结构体、结构体数组或者结构体指针的时候,就会发现C#上没有类型可以对应。这时怎么办,第一反应是C#也定义结构体,然后当成参数传弟。然而,当我们定义完一个结构体后想传递参数进去时,会抛异常,或者是传入了结构体,但是返回值却不是我们想要的,经过调试跟踪后发现,那些值压根没有改变过,代码如下。
[DllImport("workStation.dll")]
privatestaticexternboolfetchInfos(Info[]infos);
publicstructInfo
{
publicintOrderNO;
publicbyte[]UniqueCode;
publicfloatCpuPercent;
};
privatevoidbuttonTest_Click(objectsender,EventArgse)
{
try
{
Info[]infos=newInfo[128];
if(fetchInfos(infos))
{
MessageBox.Show("Fail");
}
else
{
stringmessage="";
foreach(Infoinfoininfos)
{
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.Exceptionex)
{
MessageBox.Show(ex.Message);
}
}
后来,经过查找资料,有文提到对于C#是属于托管内存,现在要传递结构体数组,是属性非托管内存,必须要用Marsh指定空间,然后再传递。于是将结构体变更如下。
StructLayoutAttribute(LayoutKind.Sequential,CharSet=CharSet.Ansi,Pack=1)]
publicstructInfo
{
publicintOrderNO;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=32)]
publicbyte[]UniqueCode;
publicfloatCpuPercent;
};
但是经过这样的改进后,运行结果依然不理想,值要么出错,要么没有被改变。这究竟是什么原因?不断的搜资料,终于看到了一篇,里面提到结构体的传递,有的可以如上面所做,但有的却不行,特别是当参数在C++中是结构体指针或者结构体数组指针时,在C#调用的地方也要用指针来对应,后面改进出如下代码。
[DllImport("workStation.dll")]
privatestaticexternboolfetchInfos(IntPtrinfosIntPtr);
[StructLayoutAttribute(LayoutKind.Sequential,CharSet=CharSet.Ansi,Pack=1)]
publicstructInfo
{
publicintOrderNO;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=32)]
publicbyte[]UniqueCode;
publicfloatCpuPercent;
};
privatevoidbuttonTest_Click(objectsender,EventArgse)
{
try
{
intworkStationCount=128;
intsize=Marshal.SizeOf(typeof(Info));
IntPtrinfosIntptr=Marshal.AllocHGlobal(size*workStationCount);
Info[]infos=newInfo[workStationCount];
if(fetchInfos(infosIntptr))
{
MessageBox.Show("Fail");
return;
}
for(intinkIndex=0;inkIndex<workStationCount;inkIndex++)
{
IntPtrptr=(IntPtr)((UInt32)infosIntptr+inkIndex*size);
infos[inkIndex]=(Info)Marshal.PtrToStructure(ptr,typeof(Info));
}
Marshal.FreeHGlobal(infosIntptr);
stringmessage="";
foreach(Infoinfoininfos)
{
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.Exceptionex)
{
MessageBox.Show(ex.Message);
}
}
要注意的是,这时接口已经改成IntPtr了。通过以上方式,终于把结构体数组给传进去了。不过,这里要注意一点,不同的编译器对结构体的大小会不一定,比如上面的结构体
在BCB中如果没有字节对齐的话,有时会比一般的结构体大小多出2两个字节。因为BCB默认的是2字节排序,而VC是默认1个字节排序。要解决该问题,要么在BCB的结构体中增加字节对齐,要么在C#中多开两个字节(如果有多的话)。字节对齐代码如下。
#pragmapack(push,1)
structInfo
{
intOrderNO;
charUniqueCode[32];
floatCpuPercent;
};
#pragmapack(pop)
用Marsh.AllocHGlobal为结构体指针开辟内存空间,目的就是转变化非托管内存,那么如果不用Marsh.AllocHGlobal,还有没有其他的方式呢?
其实,不论C++中的是指针还是数组,最终在内存中还是一个一个字节存储的,也就是说,最终是以一维的字节数组形式展现的,所以我们如果开一个等大小的一维数组,那是否就可以了呢?答案是可以的,下面给出了实现。
[DllImport("workStation.dll")]
privatestaticexternboolfetchInfos(IntPtrinfosIntPtr);
[DllImport("workStation.dll")]
privatestaticexternboolfetchInfos(byte[]infos);
[StructLayoutAttribute(LayoutKind.Sequential,CharSet=CharSet.Ansi,Pack=1)]
publicstructInfo
{
publicintOrderNO;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=32)]
publicbyte[]UniqueCode;
publicfloatCpuPercent;
};
privatevoidbuttonTest_Click(objectsender,EventArgse)
{
try
{
intcount=128;
intsize=Marshal.SizeOf(typeof(Info));
byte[]inkInfosBytes=newbyte[count*size];
if(fetchInfos(inkInfosBytes))
{
MessageBox.Show("Fail");
return;
}
Info[]infos=newInfo[count];
for(intinkIndex=0;inkIndex<count;inkIndex++)
{
byte[]inkInfoBytes=newbyte[size];
Array.Copy(inkInfosBytes,inkIndex*size,inkInfoBytes,0,size);
infos[inkIndex]=(Info)bytesToStruct(inkInfoBytes,typeof(Info));
}
stringmessage="";
foreach(Infoinfoininfos)
{
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.Exceptionex)
{
MessageBox.Show(ex.Message);
}
}
#regionbytesToStruct
///<summary>
///Bytearraytostructorclasss.
///</summary>
///<paramname=”bytes”>Bytearray</param>
///<paramname=”type”>Structtypeorclasstype.
///Egg:classHuman{...};
///Humanhuman=newHuman();
///Typetype=human.GetType();</param>
///<returns>Destinationstructorclass.</returns>
publicstaticobjectbytesToStruct(byte[]bytes,Typetype)
{
intsize=Marshal.SizeOf(type);//Getsizeofthestructorclass.
if(bytes.Length<size)
{
returnnull;
}
IntPtrstructPtr=Marshal.AllocHGlobal(size);//Allocatememoryspaceofthestructorclass.
Marshal.Copy(bytes,0,structPtr,size);//Copybytearraytothememoryspace.
objectobj=Marshal.PtrToStructure(structPtr,type);//Convertmemoryspacetodestinationstructorclass.
Marshal.FreeHGlobal(structPtr);//Releasememoryspace.
returnobj;
}
#endregion
对于实在想不到要怎么传数据的时候,可以考虑byte数组来传(即便是整型也可以,只要是开辟4字节(在32位下)),只要开的长度对应的上,在拿到数据后,要按类型规则转换成所要的数据,一般都能达到目的。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
