我正在使用 native 函数并且在 C# 中编码(marshal)结构时遇到小问题。我有指向另一个结构中的结构的指针 - 例如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 结构的指针。我需要传递一个(父结构的)“引用指针”作为 API 函数的参数。
单个引用没有问题(“ref PARENT”作为导入的dll函数的参数)但是如何传递“ref ref”?是否可以不使用不安全代码(使用 C 指针)?
问候 亚瑟
最佳答案
如果您不想使用不安全的代码,那么您需要将 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;
}
我认为使用不安全的代码/指针会更简单、更清晰。
关于c# - C# 中的编码(marshal)处理 - 将指针传递给结构 ("double ref"的引用?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11241030/