Click to See Complete Forum and Search --> : How to get Sub array?
sharong
January 2nd, 2005, 07:46 AM
I’m using a one dimensional array:
byte[] bArray = new byte[100];
And I’m writing a function that return a subset of this array:
void GetSubArray(int offset, int size, ref byte[] subArray);
As you can see, the user asks for the bArray offset and size to put in the given subArray.
How do I do that without copying the values? I want that the sub array will referee to the same memory/values as the bArray (same value)??
darwen
January 2nd, 2005, 06:50 PM
Apologies, but no. You can't do this without dropping into an unsafe context and using fixed which won't help you.
The point about passing about offsets & sizes of arrays is that you can address sections of a single array which is passed around your functions without needing to copy it.
The Garbage Collector will take care of all references and not delete the array until it's unused.
So I recommend you do it the .NET way and just pass back the relevant start offset and length of the subsection of the array which you want to address.
If you do need to copy byte arrays, by the way, then the Buffer.BlockCopy is the most efficient way that I've found of doing it.
Darwen.
sharong
January 3rd, 2005, 02:08 AM
Thanks for your replay.
I don’t fully understand what you mean to do it the .NET way. How is it possible?
Can you post some code showing what you mean?
Please note that I’m writing a component that will export this kind of interface, this interface function should return a reference to sub array inside my component without copying.
I willing to do it in unsafe code, but I haven’t succeeded yet as the interface must stay in the .NET style.
darwen
January 3rd, 2005, 07:16 AM
The .NET way is to return an offset and a size from your method.
That's all I meant.
That's why most methods which take arrays also have overloaded members which have offset and size parameters.
Darwen.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.