C #: convert unmanaged array to a managed list

I am dealing with a set of native functions that return data through dynamically allocated arrays. Functions take a reference pointer as an input, then point it to the resulting array.

For example:

typedef struct result
{
   //..Some Members..//
}

int extern WINAPI getInfo(result**);

After the call, "result" points to an array of results ending with zero *.

I want to create a managed list from this unmanaged array. I can do the following:

struct Result
{
   //..The Same Members..//
}

public static unsafe List<Result> getManagedResultList(Result** unmanagedArray)
{
    List<Result> resultList = new List<Result>();

    while (*unmanagedArray != null)
    {
       resultList.Add(**unmanagedArray);
       ++unmanaged;
    }
    return result;
}

This works, it will be tiring and ugly to redefine for each type of structure that I have to deal with (~ 35). I need a solution that is generic in type of structure in an array. To this end, I tried:

public static unsafe List<T> unmanagedArrToList<T>(T** unmanagedArray)
{ 
    List<T> result = new List<T>();
    while (*unmanagedArray != null)
    {
        result.Add((**unmanagedArray));
        ++unmanagedArray;
    }
    return result;
}

, " , (" T ")".

, , Marshal.Copy() . , Marshal.Copy().

? - ?

+3
2

, ( , # spec , , ). , T** IntPtr*. , , Marshal.Copy , . :

public static unsafe List<T> unmanagedArrToList<T>(IntPtr* p)
{ 
    List<T> result = new List<T>();
    for (; *p != null; ++p)
    {
        T item = (T)Marshal.PtrToStructure(*p, typeof(T));
        result.Add(item);
    }
    return result;
}

, IntPtr* , , .

+2

:

.Copy() .

, Marshal.SizeOf().

, , , . ( , Object ** T **.)

0

Source: https://habr.com/ru/post/1710188/


All Articles