I’ve got some unsafe C# code that cannot be changed and that exposes methods like this:
static unsafe void Foo(
byte* a, int aLength,
byte* b, int bLength,
byte* c, int cLength,
byte* d, int dLength,
byte* e, int eLength);
I’m calling these methods like this:
static void Bar(
byte[] a, int aOffset, int aLength,
byte[] b, int bOffset, int bLength,
byte[] c, int cOffset, int cLength,
byte[] d, int dOffset, int dLength,
byte[] e, int eOffset, int eLength)
{
fixed (byte* a_ = &a[aOffset])
fixed (byte* b_ = &b[bOffset])
fixed (byte* c_ = &c[cOffset])
fixed (byte* d_ = &d[dOffset])
fixed (byte* e_ = &e[eOffset])
{
Foo(a_, aLength,
b_, bLength,
c_, cLength,
d_, dLength,
e_, eLength);
}
}
(Argument validation omitted for brevity.)
This works well unless one of the byte arrays has a length of zero. In this case I get an IndexOutOfRangeException.
Index was outside the bounds of the array.
How can I prevent the exception, preferably without writing lots of boilerplate code and without switching from fixed to something else?
The unsafe methods do not read from or write to arguments where the length is zero.
You can’t access any elements in an array that is empty, so replace any of the arrays that are empty with a dummy array that contains an element that you can access: