Search code examples
c#.netpinvoke

Is it safe to pass a field by reference into unmanaged code?


Is it safe to pass a field by reference into an unmanaged extern method?

[StructLayout(LayoutKind.Sequential)]
struct SomeStruct
{
    public int SomeValue;
}

class SomeClass
{
    SomeStruct _someStruct;

    [DllImport("SomeLibrary.dll")]
    static extern void SomeExternMethod(ref SomeStruct someStruct);

    public void SomeMethod()
    {
        // Is this safe or do I have to pin the current instance of SomeClass?
        SomeExternMethod(ref _someStruct);
    }
}

Solution

  • P/Invoke will pin direct arguments which are passed by ref or out, for the duration of the call. They will show up on the unmanaged side as a pointer.

    As long as the unmanaged code doesn't save the pointer for later, you're ok. If it will save the pointer for later, then you need to use GCHandle.Alloc(Pinned) to pin it until whenever "later" means.