3

我想通过包装来创建一个类型安全的指针结构IntPtr

struct Pointer<T>
{
    private IntPtr ptr;

    // methods marshalling from and to T
}

但我也希望能够将Pointer<T>实例编组为IntPtrs,因此它们需要具有相同的大小和布局。这有保证吗?

如果不是,是不是我加了

[StructLayout(LayoutKind.Sequential, Pack = 1)]

在顶部?

基本上,最后我应该能够编组这个 C 结构

struct Foo {
    int *data;
};

使用这个 C# 结构:

struct Foo
{
    public Pointer<int> data;
}
4

2 回答 2

3

It is already fine as-is, no need to help.

A struct type in C# automatically gets a [StructLayout] attribute. The default is Sequential with a packing of 8. Which is the same kind of packing used by default in unmanaged code. It doesn't matter anyway when you have only one field in the struct.

Just make sure you don't add any fields and don't use automatic properties. You can double-check with Marshal.SizeOf(), it should be 4 in 32-bit mode and 8 in 64-bit mode. Or in other words, equal to IntPtr.Size

于 2013-08-07T12:07:44.683 回答
0

添加 [StructLayout(LayoutKind.Sequential, Pack = 1)] 只会影响结构中变量的对齐方式,不会影响它自身的变量大小。它们仍然是 32 位/64 位。

于 2013-08-07T11:59:26.507 回答