【问题标题】:How to convert the IntPtr to an array?如何将 IntPtr 转换为数组?
【发布时间】:2015-08-06 11:09:57
【问题描述】:

如何将IntPtr 转换为数组。实际上,我从非托管 dll 中调用了该函数。它返回IntPtr。现在我需要将其转换为数组。请任何人给出一个想法。代码sn-p如下。

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;

【问题讨论】:

标签: c#


【解决方案1】:

试试这个:

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

更新:

thispage 的解决方案 2 正是您所需要的。

【讨论】:

  • 感谢您的回答。但现在我得到了数组结构。如何将其转换为数组 demo[] 数组。
  • 请参考我的回答中提供的链接。
【解决方案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;
}

干杯, 凯文

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-29
    • 2012-03-19
    • 1970-01-01
    • 2013-07-22
    • 2017-09-09
    • 2013-08-12
    • 2010-09-07
    • 2016-12-07
    相关资源
    最近更新 更多