3

我在使用这段代码时遇到了一些问题:

//Creating a new ImageElement Struct
ImageElement oElement = new UM0516.ImageElement();
//Create a pointer and allocate enough room for the struct type
IntPtr pElement = Marshal.AllocHGlobal(Marshal.SizeOf(new UM0516.ImageElement()));
//Copy the contents of the struct into the allocated memory space
Marshal.StructureToPtr(oElement, pElement, true);
//Function that takes a file pointed to by handle, and does some sweet sweet things
//And returns a loaded struct pointed to by pElement
FILES_GetImageElement(handle, el, out pElement);

这是我感到困惑的地方:我将逐步执行代码,在我调用最后一个函数(它应该更改 pElement 指向的内存中的一些位)之后,我看到 oElement 发生了变化!?我认为 Marshal.StructureToPtr 将数据从托管结构“复制”到内存。那么这两个位置实际上是一样的吗?托管结构oElement和pElement指向的分配内存?

4

2 回答 2

3

这篇文章详细解释了它:

格式化的 blittable类在托管和非托管内存中具有固定布局(格式化)和通用数据表示。当这些类型需要编组时,堆中对象的指针会直接传递给被调用者。被调用者可以更改指针所引用的内存位置的内容。

于 2009-04-09T21:32:20.737 回答
0

我认为您可能不需要手动将结构编组为指针。只要结构的托管版本与非托管结构的布局匹配,就让互操作封送拆收器负责封送处理。

您应该能够完全摆脱 pElement 并将 oElement 作为 ref 参数(如果您关心其中的内容)或 out 参数传递。

于 2009-04-09T21:30:15.093 回答