结构体数组的指针的内容如何从非托管到托管...
谢谢关注...
结构体数组的指针的内容如何从非托管到托管...
部分代码如下:
//Event是结构体struct
IntPtr pEvent = new IntPtr();
int size = Marshal.SizeOf(typeof(Event));
pEvent = Marshal.AllocHGlobal(size * 1000);
uint pReadCount = 0;
if (-1 == M8_GetEventsFromBuf(ui_IP, pEvent, (uint)(size *1000), ref pReadCount))
{
Event[] events = new Event[pReadCount];
for (int k = 0; k < pReadCount; k++)
{
events[k] = new Event();
}
IntPtr ptr = new IntPtr();
ptr = Marshal.AllocHGlobal(size);
for (int i = 0; i < pReadCount; i++)
{
ptr = Marshal.ReadIntPtr(pEvent, i * size);
//问题在这里,为何ptr = 0呢?
events[i] = (Event)Marshal.PtrToStructure(ptr, typeof(Event));
...
...
再次感谢...
------解决方案--------------------pEvent+i*size 有可能要改成 pEvent+i*(int)(size/4)或者pEvent+i*size/4 ,因为是IntPtr,这几种都试试看吧,没做过这种.net的东西,只是靠以前C的经验来猜测
------解决方案--------------------这种方式转来转去,不如unsafe代码更方便
------解决方案--------------------M8_GetEventsFromBuf的C/C++函数声明是什么样子?
主要是pEvent,类型是Event* 还是 Event **?
如果是Event* :
Event[] events = new Event[pReadCount];
IntPtr ptr = pEvent;
for (int i = 0; i < pReadCount; i++)
{
events[i] = (Event)Marshal.PtrToStructure(ptr, ...);