通过引用将字段传递给非托管代码是否安全?

Tam*_*chi 1 .net c# pinvoke

通过引用将字段传递给非托管的extern方法是否安全?

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*igt 6

的P/Invoke将引脚,通过直接传递参数ref或者out,对呼叫的持续时间.它们将作为指针出现在非托管端.

只要非托管代码不保存指针以供日后使用,您就可以了.如果它将保存指针以供稍后使用,那么您需要使用GCHandle.Alloc(Pinned)它来固定它,直到"稍后"意味着.