5

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;
Rytis I
  • 1,105
  • 8
  • 19
  • 1
    possible duplicate of [Getting Array of struct from IntPtr](http://stackoverflow.com/questions/6747112/getting-array-of-struct-from-intptr) – tafa Aug 06 '15 at 11:16

2 Answers2

-1

Try this:

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

UPDATE :

Solution 2 of this page is what you need.

Mehmed
  • 132
  • 4
  • 15
-2

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

Kevin Diaz
  • 21
  • 2