I am reading file data in using a file stream. I am reading this data into a Byte array. I would like to access this data in terms of UInt32s. In c++ i would simply typecast the buffer, but in c# this does not seem to be the solution. How can I access this array in terms of UInt32s without copying the data into a UInt32 array with Buffer.BlockCopy(); this method would be far too slow for my needs.
// compile with /unsafe
private unsafe void doSomethingWithUint32s(byte[] bytes) {
int nCurPos = 0;
fixed (uint *pnUint = bytes)
{
// use old-fashioned pointer manipulation here.
while (bytes.Length - nCurPost >= 4)
{
// do your thing regarding pnUint.
pnUint += sizeof(uint); // same as += 4;
nCurPos += 4;
}
}
}
mm pointers in c#, interesting ;)
You could also intialize a System.IO.MemoryStream containing the bytes and read it from there.
BTW, won't that code complain here:
fixed(uint* pnUint = bytes)
that bytes is not a pointer to a uint?
I seem to recall having that problem; the next thing I tried was:
fixed(uint* p = (uint*)bytes)
and it complained that you cannot have a typecast insided a fixed() statement, so I ended up doing:
fixed(byte* bTmp = bytes)
{
uint* p = (uint*)bTmp;
}
Or maybe I'm crazy :P
well thanks guys, i wasnt even aware you could do pointers in c# lol. This helps alot!
Quote from: c0ol on September 22, 2004, 05:04 PM
well thanks guys, i wasnt even aware you could do pointers in c# lol. This helps alot!
This isn't always desireable, though. Your images will be marked "unsafe" / "unverified", so if you are planning to make something that runs in, say, browsers (e.g. like a Java applet) then you would probably not want to use pointers (as "untrusted" code cannot do "unsafe" things, IIRC).
That's a good point K, heh, sorry I put that up while at work w/o a compiler available. ;)
Also, you could just use BitConvert.ToUInt32(bytes, i); and increment i by four every iteration. ;)