3
public : array<Byte>^ Foo(array<Byte>^ data)

gets dynamic size managed array

but how can I get fixed size managed byte array?

I wanna force C# user to send me 8 byte array; and get 8 bytes back

style:

public : Byte[8] Foo(Byte[8] data)

EDIT:

can any1 explain why its impossbile in safe context?

Nahum
  • 6,959
  • 12
  • 48
  • 69
  • 1
    re your edit: "safe" C# simply doesn't have a concept of "an array with checked / verified length" - if you have a method that takes a `byte[]`, that could be `null`, 0-length, or length 213341. A one line check is very easy to add... `fixed` buffers have known / defined lengths, but they **aren't arrays**. – Marc Gravell Dec 10 '12 at 09:42

3 Answers3

7

C# does not allow you to do that. You'll simply have to validate the array's length and maybe throw an exception if the length is not 8.

Also, the type of your function can't be Byte[8]; you'll have to change that to Byte[].

Neko
  • 3,550
  • 7
  • 28
  • 34
6

You can use a fixed size buffer inside a struct. You'll need it to be in an unsafe block though.

unsafe struct fixedLengthByteArrayWrapper
{
    public fixed byte byteArray[8];
}

On the C++ side you'll need to use inline_array to represent this type.

As Marc correctly says, fixed size buffers are no fun to work with. You'll probably find it more convenient to do runtime length checking.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • `fixed` buffers are a bit of a pain to work with, though - and not applicable to all platforms / deployments. – Marc Gravell Dec 10 '12 at 09:38
  • I don't see why. seems easier to fix array size than create a dynamic array and handle exception, not to mention it isn't staticly checkable. – Nahum Dec 10 '12 at 09:43
  • 2
    @NahumLitvin the point is; `fixed` buffers ***are not arrays***; you can't treat them like arrays, even though the syntax can be similar. Every time you touch a `fixed` buffer you need **both** `unsafe` *and* a `fixed` statement (which does an implicit pin, IIRC). `fixed` buffers can be incredibly useful in a few scenarios, but personally I'd leave them as implementation details, not part of the API – Marc Gravell Dec 10 '12 at 09:47
6

If you want to force exactly 8 bytes... consider sending a long or ulong instead. Old-school, but it works. It also has the advantage of not needing an object (a byte[] is an object) - it is a pure value-type (a primitive, in this case)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900