【问题标题】:Can Someone explain the Marshal.StructureToPtr有人可以解释 Marshal.StructureToPtr
【发布时间】:2009-04-09 21:15:35
【问题描述】:

我在处理这段代码时遇到了一些问题:

//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 将数据从托管结构“复制”到内存。那么这两个位置实际上是一样的吗? pElement 指向的托管结构 oElement 和分配的内存?

【问题讨论】:

  • -1 用于在同一篇文章中写“Helps YO”和“Coo Dawg”。

标签: memory struct pointers marshalling


【解决方案1】:

本文在detail中解释:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • Afaik 这需要不安全的指针和 C# 中的 fixed 语句(例如 unsafe int * )以避免垃圾收集器不会移动内存(即内存必须被固定)。
    • 或者使用 System.Runtime.InteropServices.GCHandle 应该这样做(正如 Marshal.StructureToPtr 的文档所说)。
    猜你喜欢
    • 1970-01-01
    • 2012-05-29
    • 2012-05-23
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    相关资源
    最近更新 更多