要回答您的编辑:
只是想...有没有办法固定包含结构的父对象,然后获取结构的指针而不是容器对象?
我认同。如果有的话,您应该能够使用托管的结构数组(可能是一个数组)。
这是一个示例代码:
[StructLayout(LayoutKind.Sequential)]
struct SomeStructure
{
public int first;
public int second;
public SomeStructure(int first, int second) { this.first=first; this.second=second; }
}
/// <summary>
/// For this question on Stack Overflow:
/// https://stackoverflow.com/questions/1850488/pinning-an-updateble-struct-before-passing-to-unmanaged-code
/// </summary>
private static void TestModifiableStructure()
{
SomeStructure[] objArray = new SomeStructure[1];
objArray[0] = new SomeStructure(10, 10);
GCHandle hPinned = GCHandle.Alloc(objArray, GCHandleType.Pinned);
//Modify the pinned structure, just to show we can
objArray[0].second = 42;
Console.WriteLine("Before unmanaged incrementing: {0}", objArray[0].second);
PlaceholderForUnmanagedFunction(hPinned.AddrOfPinnedObject());
Console.WriteLine("Before unmanaged incrementing: {0}", objArray[0].second);
//Cleanup
hPinned.Free();
}
//Simulates an unmanaged function that accesses ptr->second
private static void PlaceholderForUnmanagedFunction(IntPtr ptr)
{
int secondInteger = Marshal.ReadInt32(ptr, 4);
secondInteger++;
Marshal.WriteInt32(ptr, 4, secondInteger);
}
及其输出:
Before unmanaged incrementing: 42
Before unmanaged incrementing: 43