如何封送列表<int>?

How do i marshal list<int>?

本文关键字:int gt lt 何封送 列表      更新时间:2023-10-16

我在 c++ 中有一个 dll,它返回列表,我想在我的 c# 应用程序中使用它作为列表

[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:

通常,

任何互操作方案都不支持泛型。如果尝试封送泛型类型或值,则 PInvoke 和 COM 互操作都将失败。因此,我希望Marshal.SizeOf在这种情况下未经测试或不受支持,因为它是Marshal特定的函数。

看:封送处理 .NET 泛型类型

可能的情况之一

C++ 端

    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# 端

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