.NET Framework 封送处理结构

示例

简单的结构

C ++签名:

typedef struct _PERSON
{
    int age;
    char name[32];
} PERSON, *LP_PERSON;

void GetSpouse(PERSON person, LP_PERSON spouse);

C#定义

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct PERSON
{
    public int age;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
    public string name;
}

[DllImport("family.dll", CharSet = CharSet.Auto)]
public static extern bool GetSpouse(PERSON person, ref PERSON spouse);

具有未知大小数组字段的结构。传入

C ++签名

typedef struct
{
    int length;
    int *data;
} VECTOR;

void SetVector(VECTOR &vector);

从托管代码传递到非托管代码时,此

所述data阵列应该被定义为的IntPtr和存储器应该与显式地分配(和释放与后记):Marshal.AllocHGlobal()Marshal.FreeHGlobal()

[StructLayout(LayoutKind.Sequential)]
public struct VECTOR : IDisposable
{
    int length;
    IntPtr dataBuf;

    public int[] data
    {
        set
        {
            FreeDataBuf();
            if (value != null &&value.Length> 0)
            {
                dataBuf = Marshal.AllocHGlobal(value.Length * Marshal.SizeOf(value[0]));
                Marshal.Copy(value, 0, dataBuf, value.Length);
                length = value.Length;
            }
        }
    }
    void FreeDataBuf()
    {
        if (dataBuf != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(dataBuf);
            dataBuf = IntPtr.Zero;
        }
    }
    public void Dispose()
    {
        FreeDataBuf();
    }
}

[DllImport("vectors.dll")]
public static extern void SetVector([In]ref VECTOR vector);

具有未知大小数组字段的结构。接收

C ++签名:

typedef struct
{
    char *name;
} USER;

bool GetCurrentUser(USER *user);

当此类数据从非托管代码中传递出去并由非托管函数分配内存时,托管调用者应将其接收到一个IntPrt变量中,并将缓冲区转换为托管数组。对于字符串,有一个方便的方法:Marshal.PtrToStringAnsi()

[StructLayout(LayoutKind.Sequential)]
public struct USER
{
    IntPtr nameBuffer;
    public string name { get { return Marshal.PtrToStringAnsi(nameBuffer); } }
}

[DllImport("users.dll")]
public static extern bool GetCurrentUser(out USER user);