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

查看:48
本文介绍了从 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;
}

那么,我做错了什么?

推荐答案

这个函数对我有用,假设结构的大小是固定的:

This function worked for me, assuming that the size of the struct is fixed:

public static void MarshalUnmananagedArray2Struct<T>(IntPtr unmanagedArray, int length, out T[] mangagedArray)
{
    var size = Marshal.SizeOf(typeof(T));
    mangagedArray = new T[length];

    for (int i = 0; i < length; i++)
    {
        IntPtr ins = new IntPtr(unmanagedArray.ToInt64() + i * size);
        mangagedArray[i] = Marshal.PtrToStructure<T>(ins);
    }
 }

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

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