如何将IntPtr转换为数组?

时间:2015-08-06 11:09:57

标签: c#

如何将IntPtr转换为数组。实际上我从非托管DLL调用了该函数。它返回IntPtr。现在我需要将其转换为数组。请任何人提出一个想法。代码片段在下面。

Unmanaged function declared

[DllImport("NLib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern unsafe IntPtr N_AllocPt1dArray(NL_INDEX n, ref stacks S); 

调用函数

void Function1()
{
     IntPtr PPtr=N_AllocPt1dArray(n, ref S);
}

现在我需要将PPtr转换为数组(数组为demo[])。其中demo由

定义
public unsafe struct demo 
{            
    public int x ;
    public int y ;
    public int z ;
}demo DEMO;

2 个答案:

答案 0 :(得分:0)

试试这个:

array[0] = (demo)System.Runtime.InteropServices.Marshal.PtrToStructure(PPtr , typeof(demo));

更新:

this page的解决方案2就是您所需要的。

答案 1 :(得分:-2)

这取决于您所指向的数据类型,下一个代码从IntPtr获取字符串数组:

nstring是您希望获得的元素数。

您可以修改代码以满足您的需求,但这可以使您了解如何以未经修饰的块代码从IntPtr检索数据。

private string[] ConvertIntPtrToStringArray(IntPtr p, int nstring)
{
    //Marshal.ptr
    string[] s = new string[nstring];
    char[] word;
    int i, j, size;

    unsafe
    {   
        byte** str = (byte**)p.ToPointer();

        i = 0;
        while (i < nstring)
        {
            j = 0;
            while (str[i][j] != 0)
                j++;
            size = j;
            word = new char[size];
            j = 0;
            while (str[i][j] != 0)
            {
                word[j] = (char)str[i][j];
                j++;
            }
            s[i] = new string(word);

            i++;
        }
    }

    return s;
}

欢呼声, 凯文