钢钉传递给非托管code之前,updateble结构?

问题描述:

我使用一些旧的API,并需要通过一个结构,以非托管code运行异步的指针。

I using some old API and need to pass the a pointer of a struct to unmanaged code that runs asynchronous.

在换句话说,之后我立刻传递结构指针非托管code,非托管的code将指针和回报。非托管code可以访问该结构的背景下,在另一个线程。 我有过一个运行在另一个线程也不线程本身的非托管code没有控制权。

In other words, after i passing the struct pointer to the unmanaged code, the unmanaged code copies the pointer and returns immediately. The unmanaged code can access that struct in background, in another thread. I have no control over the unmanaged code that runs in another thread nor the thread itself.

固定{}语句不能用于固定,因为它不是设计用于异步非托管钉扎

The fixed { } statement can't be used for pinning because it not designed for async unmanaged pinning.

的GCHandle可以固定只能引用,因此结构必须被装箱使用的GCHandle。我试了一下,和它的作品。它的主要问题是,你不能从更新管理code 结构体的。要更新结构,首先我们需要拆箱它,然后更新,然后重新框,但......哎呀......再次盒子?!?这意味着在内存中的previous指针依然指向旧的非达最新的结构,而新结构有另一个指针,这意味着我需要通过新指针的非托管code ......不适用我的情况。

GCHandle can pin only references, so the struct must be boxed to use GCHandle. I tried it, and it works. The main problem with it, is that you can't update the struct from managed code. To update a struct, first of all we need to unbox it, then update, then box again, but... oops ... box again?!? this means the previous pointer in the memory still point to the old non-up-to-date struct, and the new struct have another pointer, and this means that i need to pass new pointer to the unmanaged code... inapplicable in my case.

我如何可以固定一个结构在内存中没有固定{}语句,这样我可以更新它的从管理code 不改变它的指针?

How can i pin a struct in the memory without fixed { } statement, and so that i can update it from managed code without change it's pointer?

感谢。

编辑:

只是想......是有办法针包含结构中的父对象,然后得到的结构,而不是容器对象的指针?

Just thought... is there a way to pin the parent object that contains the struct, and then get the pointer of the struct rather than the container object?

是不安全code选项?

Is unsafe code an option?

// allocate unmanaged memory
Foo* foo = (Foo*)Marshal.AllocHGlobal(sizeof(Foo));

// initialize struct
foo->bar = 0;

// invoke unmanaged function which remembers foo
UnsafeNativeMethods.Bar(foo);
Console.WriteLine(foo->bar);

// update struct
foo->bar = 10;

// invoke unmanaged function which uses remembered foo
UnsafeNativeMethods.Qux();
Console.WriteLine(foo->bar);

// free unmanaged memory
Marshal.FreeHGlobal((IntPtr)foo);

这编译并不会抛出异常,但我没有一个非托管函数在手边,以测试它是否正常工作。

This compiles and doesn't throw an exception, but I don't have an unmanaged function at hand to test if it works.

MSDN

当的AllocHGlobal调用LocalAlloc,它通过一个LMEM_FIXED标志,这会导致分配的内存被锁定在适当位置。此外,分配的内存不是零填充。

When AllocHGlobal calls LocalAlloc, it passes a LMEM_FIXED flag, which causes the allocated memory to be locked in place. Also, the allocated memory is not zero-filled.