Reading file contents to unmanaged memory block (IntPtr) from C#

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

In my project I need to use VirtualAlloc (kernel32) to allocate memory to
ensure that data is 4K aligned. I need to fill the data block with file
contents. I notice that there are no 'Read' operations to memory pointed to
be an IntPtr (I checked FileStream & BinaryReader). Can I do this from
C#/.NET?

I'm currently mapping C-functions to achieve this, and I'm not too fond of
doing that. Can someone help me with this?

Thanks
 
One thing you can do is; use BinaryReader.Read to read the data into a
byte[], when done use Marshal.Copy to copy the byte[] to the native heap
pointed to by your IntPtr.

Willy.
 
Tom,

You can use the static ReadByte, ReadInt16, ReadInt32, ReadInt64 and
ReadIntPtr methods in order to read blocks of bytes from a location in
memory.

I also believe you can use the static Copy method to copy unmanaged
memory into an array of bytes.

Hope this helps.
 
Tom,

I would use unsafe code for this. Basically, I would allocate a byte
array. Then, I would enter an unsafe block and populate the byte array with
calls to CreateFile (to open) and ReadFile, etc, etc. Then, when you exit
the unsafe block, you should have the contents in a byte array. You can
always reverse the process to flush the contents back.
 
Tom,

If you need to read file data effeciently into native heap memory, you
shouldn't be using C# for this.
If you don't need the data to cross the native/managed heap boundary, you
should use native C++. If you want your data to cross this boundary you
should use MC++.

Willy.


TT (Tom Tempelaere) said:
Hi Willy,

The problem is efficiency if I would do it like that. The data is read
into
memory to start a DMA operation (hence the use of VirtualAlloc). I can't
read
the file contents to a managed array and then copy it to unmanaged memory,
that would be too unefficient.

Currently, I'm using fopen,fread,fclose,... from MSVCRT.dll to pull it
off.
It works but as I said, I'm not too fond of it.

Thank you,
Tom T.



Willy Denoyette said:
One thing you can do is; use BinaryReader.Read to read the data into a
byte[], when done use Marshal.Copy to copy the byte[] to the native heap
pointed to by your IntPtr.

Willy.

"TT (Tom Tempelaere)" <_|\|_0$P@|/\|titi____AThotmail.com|/\|@P$0_|\|_>
wrote in message
Hi,

In my project I need to use VirtualAlloc (kernel32) to allocate memory
to
ensure that data is 4K aligned. I need to fill the data block with file
contents. I notice that there are no 'Read' operations to memory
pointed
to
be an IntPtr (I checked FileStream & BinaryReader). Can I do this from
C#/.NET?

I'm currently mapping C-functions to achieve this, and I'm not too fond
of
doing that. Can someone help me with this?

Thanks
 
Back
Top