You 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.
Marked As Answer bysimonwolfThursday, July 31, 2008 9:05 AM
Marked As Answer bysimonwolfThursday, July 31, 2008 9:05 AM
You 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[100]; byte[] aryTwo = new byte[aryOne.Length]; int count = aryOne.Length; fixed (byte* a1 = &aryOne[0]) { fixed (byte* a2 = &aryTwo[0]) { byte* p1 = a1; byte* p2 = a2; for (int i = 0; i < count; i++) { *arrb = *pt; p1++; p2++; } } }
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.
Marked As Answer bysimonwolfThursday, July 31, 2008 9:05 AM
Marked As Answer bysimonwolfThursday, July 31, 2008 9:05 AM
Microsoft is conducting an online survey to understand your opinion of the Msdn Web site. If you choose to participate, the online survey will be presented to you when you leave the Msdn Web site.