如何注释C#结构字段以编组为指针或嵌套在PInvoke中?

问题描述 投票:1回答:1

在C ++中,具有以下结构

extern "C" {
    struct A_C {
        UINT32 number;
    }

    struct B_C {
        A_C nested;
        A_C* pointer;
    }
}

以下C#结构的正确属性注释是什么

struct ACs {
    UInt32 number;
}

struct BCs {
    ACs nested;
    ACs pointer;
}

以便BCs.nested将映射到B_C.nested,而BCs.pointer将映射到B_C.pointer

可以通过实现ICustomMarshaler来实现,但是有没有其他程序代码的解决方案吗?

c# c++ struct pinvoke
1个回答
0
投票

如果我理解您的意思。在c ++中

#pragma pack(1)

#define DLL_EXPORT extern "C" __declspec(dllexport)

    extern "C" {
        struct A_C {
            unsigned int number;
        };

        struct B_C {
            A_C nested;
            A_C* pointer;
        };
    }

    DLL_EXPORT B_C GetStruct(int &size) {
        A_C nested;
        nested.number = 10;
        B_C bc;
        bc.nested = nested;
        size = 10;
        bc.pointer = new A_C[size];
        A_C* ac_ptr = bc.pointer;
        for (int i = 0;i < size;i++)
            ac_ptr++->number = i;
        return bc;
    }

    DLL_EXPORT void DeletPointer(void* ptr) {
        delete[] ptr;
    }

在C#中:

[DllImport("<your.dll>", EntryPoint = "GetStruct", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern BCs GetStruct(out int size);

[DllImport("<your.dll>", EntryPoint = "DeletPointer", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern void DeletPointer(void* ptr);

[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode, Size = 4)]
struct ACs {
  [FieldOffset(0)]
  uint number;
}

[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode, Size = 8)]
struct BCs {

   [FieldOffset(0)]
   ACs nested;

   [FieldOffset(4)]
   Acs* pointer;
}

public unsafe static int Main(string[] args)
{
    BCs bcs = GetStruct(out int size);
    string str = string.Empty;
    for (int i = 0; i < size; i++)
         str += bcs.pointer[i].number.ToString() + "\r\n";
    DeletPointer(bcs.pointer);
    System.Console.Write(str);
}
© www.soinside.com 2019 - 2024. All rights reserved.