3

I want to ask if there is some difference between

public int Method1([In, Out] byte[] buffer);

and

public int Method2(byte[] buffer);

I came across http://referencesource.microsoft.com/#mscorlib/system/io/stream.cs,739 and wonder why [In, Out] is there?

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
  • 2
    This code is very, very old and almost surely written before the pinvoke marshaller was done. Which took quite a while, they spent enormous resources on optimizing it. Decent odds that [Out] was necessary when the pinvoke marshaller couldn't yet handle blittable types. Or the programmer just included it because it is never wrong to be explicit about it. You'd have to find the Microsoft programmer that worked on this 17+ years ago to get a completely reliable answer. They are very hard to find. – Hans Passant Sep 08 '16 at 15:08

1 Answers1

-1

Yes. There are differences.

  • public int Method2(byte[] buffer); uses implicit In:

    Indicates that data should be marshaled from the caller to the callee, but not back to the caller.

  • public int Method2(out byte[] buffer); uses Out:

    Indicates that data should be marshaled from callee back to caller.

  • public int Method2(ref byte[] buffer); uses [In, Out].
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
  • 2
    No, they are not equivalent. Using '[In, Out]' does not replace using 'ref'. – Marek Fekete Sep 08 '16 at 15:02
  • @reproduktor could you please explain? – Ondrej Sep 13 '16 at 09:10
  • According to [msdn](https://msdn.microsoft.com/en-us/library/77e6taeh(v=vs.100).aspx) `ref` translates to `[in/out]`. – Ondrej Sep 13 '16 at 09:29
  • @Ondrej, that was just a minor comment related to (apparently edited out in the meantime) statement that `[In, Out]` _is equivalent_ to `ref`. While `ref` implies `[In, Out]`, it does not work the other way round, so to be able to call `Method1(ref arr);` you need to use `ref`. These two are equivalent though: `public int Method1([In, Out] ref byte[] buffer)` and `public int Method1(ref byte[] buffer)`. – Marek Fekete Sep 13 '16 at 12:28