简体   繁体   中英

How to convert the IntPtr to an array?

How to convert the IntPtr to an array. Actually I called the function from unmanaged dll. It returns IntPtr . Now I need to convert it to an array. Please any one give an idea.Code snippet is below.

Unmanaged function declared

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

Calling the function

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

Now I need to convert PPtr to an array(array is demo[] ).where demo is defined by

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

Try this:

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

UPDATE :

Solution 2 of this page is what you need.

It depends of what type of data you are pointing to, the next code get an array of strings from an IntPtr:

nstring is the number of elements you expect to get.

You can modify the code to satisfy your needs, but this can give you an idea of how to retrive data from an IntPtr in an unmaganed block code.

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;
}

cheers, Kevin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM