tags:

views:

1535

answers:

3

I've got a function which fills an array of type sbyte[], and I need to pass this array to another function which accepts a parameter or type byte[].

Can I convert it nicely and quickly, without copying all the data or using unsafe magic?

+10  A: 

You will have to copy the data (only reference-type arrays are covariant) - but we can try to do it efficiently; Buffer.BlockCopy seems to work:

    sbyte[] signed = { -2, -1, 0, 1, 2 };
    byte[] unsigned = new byte[signed.Length];
    Buffer.BlockCopy(signed, 0, unsigned, 0, signed.Length);

If it was a reference-type, you can just cast the reference without duplicating the array:

    Foo[] arr = { new Foo(), new Foo() };
    IFoo[] iarr = (IFoo[])arr;
    Console.WriteLine(ReferenceEquals(arr, iarr)); // true
Marc Gravell
Yup... but read the last sentence of the question. ;)
Vilx-
Edited to include note on covariance
Marc Gravell
+1  A: 

If you are using .NET 3.5+, you can use the following:

byte[] dest = Array.ConvertAll(sbyteArray, (a) => (byte)a);

Which is, I guess effectively copying all the data.

Note this function is also in .NET 2.0, but you'd have to use an anonymous method instead.

Clinton
Ugh. I'd rather use Buffer.BlockCopy() then. That at least blindly copies a bunch of bytes. This one has a function call for each of them. Performance nightmare.
Vilx-
Well, it all depends on how much you're copying, but yeah, The block copy makes more sense.In the end, if you want type safety, the only way is to copy. If you want to convert (re-cast) the array, the unsafe is the only way to go.
Clinton
A: 

You may look at hacks in next thread: C# unsafe value type array to byte array conversions.

Arvo
...and again - read the question. I know this solution.
Vilx-
I did read the question :) One proposed solution there didn't use unsafe keyword, although used magic -[StructLayout(LayoutKind.Explicit)] and further. But yes, I've used Buffer.BlockCopy() so far; it seems reasonably fast.
Arvo
Whoa, I missed the StructLayout trick. Neat! Heh, might even work in my case, since the array size is pretty constant. :)
Vilx-