简体   繁体   中英

How do i marshal list<int>?

I have a dll in c++, it returns list, I want to use it in my c# app as List

[DllImport("TaskLib.dll", SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern List<int> GetProcessesID();

public static List<int> GetID()
{
    List<int> processes = GetProcessesID();//It is impossible to pack a "return value": The basic types can not be packed
    //...
}

Per Jared Par:

Generics as a rule are not supported in any interop scenario. Both PInvoke and COM Interop will fail if you attempt to Marshal a generic type or value. Hence I would expect Marshal.SizeOf to be untested or unsupported for this scenario as it is a Marshal specific function.

See: Marshalling .NET generic types

one of possible scenarios

c++ side

    struct ArrayStruct
    {
        int myarray[2048];
        int length;
    };

    extern "C" __declspec(dllexport) void GetArray(ArrayStruct* a)
    {
        a->length = 10;
        for(int i=0; i<a->length; i++)
            a->myarray[i] = i;
    }

c# side

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct ArrayStruct
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2048)]
        public int[] myarray;
        public int length;
    }

    [DllImport("TaskLib.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern void GetArray(ref ArrayStruct a);

    public void foo()
    {
        ArrayStruct a = new ArrayStruct();
        GetArray(ref a);
    }

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