Thursday, July 31, 2008 2:04 AM
As we known, using fixed, we can get the address of array. as following.
byte arrb= new byte;
fixed(byte* pb = &arrb)
And my question is how can I convert the pointer to array..
byte arrb2 = (byte)pb; //this will cause compiling error.
Sorry for my English skill.I try my best to make the question clear.
Thursday, July 31, 2008 6:07 AMYou can't use a simple cast because the CLR doesn't know whether your pointer points to the first element of a managed array, and simply assuming that it does would violate CLR type safety.
You'd have to create a new array of the desired type and size, and then copy the data from the pointer location into the array. There don't seem to be any predefined methods for this job but it's just a simple loop, of course.
Thursday, July 31, 2008 8:19 AMYou can't get a pointer like that to an array (besides like gchandle). In your fixed statement you are telling the clr to pin the array ie keep it in the same spot in memory, and you are using the address of operator to just get the first element of the array not the entire thing. Like Chris said you need to loop through the array and copy what you need. Below is an example.
byte aryOne= new byte;
byte aryTwo = new byte[aryOne.Length];
int count = aryOne.Length;
fixed (byte* a1 = &aryOne)
fixed (byte* a2 = &aryTwo)
byte* p1 = a1;
byte* p2 = a2;
for (int i = 0; i < count; i++)
*arrb = *pt;
Is there a reason you need to do this with unsafe code. Your best bet is to use the Clone method on the array or the CopyTo method. If you want a fast way to copy primitives types you should use the System.Buffer.BlockCopy which interally does a memcpy.