Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access memory address in c#

I am interfacing with an ActiveX component that gives me a memory address and the number of bytes.

How can I write a C# program that will access the bytes starting at a given memory address? Is there a way to do it natively, or am I going to have to interface to C++? Does the ActiveX component and my program share the same memory/address space?

like image 794
chocojosh Avatar asked Jun 09 '09 20:06

chocojosh


2 Answers

You can use Marshal.Copy to copy the data from native memory into an managed array. This way you can then use the data in managed code without using unsafe code.

like image 129
Ben Schwehn Avatar answered Oct 06 '22 00:10

Ben Schwehn


I highly suggest you use an IntPtr and Marshal.Copy. Here is some code to get you started. memAddr is the memory address you are given, and bufSize is the size.

IntPtr bufPtr = new IntPtr(memAddr);
byte[] data = new byte[bufSize];
Marshal.Copy(bufPtr, data, 0, bufSize);

This doesn't require you to use unsafe code which requires the the /unsafe compiler option and is not verifiable by the CLR.

If you need an array of something other than bytes, just change the second line. Marshal.Copy has a bunch of overloads.

like image 42
Bryce Kahle Avatar answered Oct 06 '22 01:10

Bryce Kahle