gpt4 book ai didi

memory - 有人可以解释 Marshal.StructureToPtr

转载 作者:行者123 更新时间:2023-12-01 23:22:00 24 4
gpt4 key购买 nike

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

//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 指向的分配内存?

最佳答案

本文在 detail 中对此进行了解释:

Formatted blittable classes have fixed layout (formatted) and common data representation in both managed and unmanaged memory. When these types require marshaling, a pointer to the object in the heap is passed to the callee directly. The callee can change the contents of the memory location being referenced by the pointer.

关于memory - 有人可以解释 Marshal.StructureToPtr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/735959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com