获取结构数组从IntPtr的 [英] Getting Array of struct from IntPtr

查看:81
本文介绍了获取结构数组从IntPtr的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些结构类似这样

struct MyStruct
{
    public int field1;
    public int field2;
    public int field3;
}

和我有指向此结构的数组。
所以,我需要从这个指针数组获得。
我试着用Marshal.PtrToStructure,但我有内存读取错误。
这是我的梅索德:

and I have pointer to array of this struct. So, I need to get array from this pointer. I'm tried to using Marshal.PtrToStructure, but i had memory reading error. This is my methode:

public MyStruct[] GetArrayOfStruct(IntPtr pointerToStruct, int length)
{
    var sizeInBytes = Marshal.SizeOf(typeof(TCnt));
    MyStruct[] output = new MyStruct[length];

    for (int i = 0; i < length; i++)
    {
        IntPtr p = new IntPtr((pointerToStruct.ToInt32() + i * sizeInBytes));

        output[i] = (MyStruct)System.Runtime.InteropServices.Marshal.PtrToStructure(p, typeof(MyStruct));
    }

    return output;
}

那么,究竟我做错了?

So, what am i doing wrong ?

推荐答案

两个问题。您可以在Marshal.SizeOf()调用中使用TCNT代替MYSTRUCT。您IntPtr的算术不能在64位机器上工作,你必须使用IntPtr.ToInt64()或转换为(长)。

Two problems. You use TCnt instead of MyStruct in the Marshal.SizeOf() call. Your IntPtr arithmetic cannot work on a 64-bit machine, you must use IntPtr.ToInt64() or cast to (long).

刚开错IntPtr的或长度肯定是太当然的可能性。使用调试+的Windows +内存+内存1,并把pointerToStruct在地址框中基本验证。

Just getting the wrong IntPtr or length is certainly a possibility too of course. Use Debug + Windows + Memory + Memory 1 and put "pointerToStruct" in the Address box for basic verification.

这篇关于获取结构数组从IntPtr的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆