3

我正在使用本机函数,并且在 c# 中编组结构存在小问题。我在另一个结构中有指向结构的指针 - 例如 C# 声明:

    [StructLayout(LayoutKind.Sequential, Pack=1, CharSet = CharSet.Auto)]
    public struct PARENT
    {
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string Name;
        [MarshalAs(UnmanagedType.Struct, SizeConst=8)]
        public CHILD pChild;
    }

    [StructLayout(LayoutKind.Sequential, Pack=1, CharSet = CharSet.Auto)]
    public struct CHILD
    {
        public UInt32 val1;
        public UInt32 val2;
    }

在 PARENT 结构中,我应该有一个指向 CHILD 结构的指针。我需要传递一个“指向引用的指针”(PARENT 结构)作为 API 函数的参数。

单引用(“ref PARENT”作为导入的 dll 函数的参数)没有问题,但是如何传递“ref ref”?是否可以不使用不安全代码(使用 C 指针)?

问候亚瑟

4

2 回答 2

1

如果您不想使用不安全的代码,则需要将 Child 定义为 IntPtr 并添加一个属性,该属性可以访问 Child IntPtr 中的值。

    [StructLayout(LayoutKind.Sequential, Pack=1, CharSet = CharSet.Auto)]
public struct PARENT
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
    public string Name;
    public IntPtr pChild;
    public CHILD Child{
      get {
       return (CHILD)Marshal.PtrToStructure(pChild, typeof(CHILD));
      }
    }
}

[StructLayout(LayoutKind.Sequential, Pack=1, CharSet = CharSet.Auto)]
public struct CHILD
{
    public UInt32 val1;
    public UInt32 val2;
}

我认为使用不安全的代码/指针会更容易、更干净。

于 2012-06-28T08:52:08.560 回答
0

这是安全和不安全的结合,我认为这里是合理的。

fixed (void* pt = new byte[Marshal.SizeOf(myStructInstance)])
{
    var intPtr = new IntPtr(pt);
    Marshal.StructureToPtr(myStructInstance, intPtr, true);

    // now "pt" is a pointer to your struct instance
    // and "intPtr" is the same, but wrapped with managed code
}
于 2012-06-28T08:53:08.793 回答