Pinning char[] on P/Invoke call

后端 未结 1 1230
终归单人心
终归单人心 2021-01-22 02:40

I have object pool of char buffers and passing this buffer on P/Invoke call. Do i need pinning buffer before call or not?

First approach:

[DllImport(\"Na         


        
1条回答
  •  闹比i
    闹比i (楼主)
    2021-01-22 02:57

    No, there is auto-pinning for reference types passed to PInvoke.

    From https://msdn.microsoft.com/en-us/magazine/cc163910.aspx#S3:

    When the runtime marshaler sees that your code is passing to native code a reference to a managed reference object, it automatically pins the object.

    so first approach is ok.

    Only:

    SomeMeth(buffer, 4095);
    

    I do think it is wrong to sprinkle constants around the code...

    SomeMeth(buffer, buffer.Length);
    

    or

    SomeMeth(buffer, buffer.Length - 1);
    

    would be probably better.

    0 讨论(0)
提交回复
热议问题