Pinning an updateble struct before passing to unmanaged code?

后端 未结 6 2229
一个人的身影
一个人的身影 2021-02-04 11:11

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

In other words, after i passing the struct pointer to the unman

6条回答
  •  醉酒成梦
    2021-02-04 11:48

    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.

    From MSDN:

    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.

提交回复
热议问题