首先让我说看看我在整个论坛和网络上的许多链接中找到了固定{},Marshal.AllocHGlobal()和GCHandle.Alloc()的使用说明.但是,我还没有找到关于何时使用Marshal类与GCHandle类(使用和不使用fixed {})的简明解释.
我正在使用第三方.NET库,它在"Buffer"类中有一个名为Readline()的方法.该手册显示了以下函数原型:
bool ReadLine(int x1,int y1,int x2,int y2,System.IntPtr bufData,out int numRead);
描述bufData,说明:...内存区域的字节数必须大于或等于行长度乘以BytesPerPixel属性返回的值.
现在,后来在他们的用户手册,做给访问该缓冲区(我已经调整了我的具体的例子一点点)的例子:
// Create an array large enough to hold one line from buffer
int size = 640;
byte[] dataLine = new byte[size * 2]; // 2 bytes per pixel
// Pin the array to avoid Garbage collector moving it
GCHandle dataLineHandle = GCHandle.Alloc(dataLine, GCHandleType.Pinned);
IntPtr dataLineAddress = dataLineHandle.AddrOfPinnedObject();
Run Code Online (Sandbox Code Playgroud)
我可以按照上面的"示例"代码:
// Read one line of buffer data
success = buffer.ReadLine(0, 0, 639, 0, …Run Code Online (Sandbox Code Playgroud)