我如何编组列表<int>?</int>

时间:2012-04-23 22:46:06

标签: c# c++ marshalling

我在c ++中有一个dll,它返回列表,我想在我的c#app中使用它作为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
    //...
}

2 个答案:

答案 0 :(得分:3)

Per Jared Par:

  

任何互操作方案都不支持泛型。如果您尝试生成泛型类型或值,则PInvoke和COM Interop都将失败。因此,我认为Marshal.SizeOf对于这种情况是未经测试或不受支持的,因为它是Marshal特定功能。

请参阅: Marshalling .NET generic types

答案 1 :(得分:2)

可能的情景之一

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