views:

1073

answers:

4

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?

+1  A: 

I think you are looking for the IntPtr type. This type (when used within an unsafe block) will allow you to use the memory handle from the ActiveX component.

Andrew Hare
+8  A: 

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.

Ben Schwehn
This is probably a much more elegant way than using unsafe code. My program now works with unsafe code; but, I will revisit it later to see if I can replace it with Marshal.Copy
chocojosh
A: 

C# can use pointers. Just use the 'unsafe' keyword in front of your class, block, method, or member variable (not local variables). If a class is marked unsafe all member variables are unsafe as well.

unsafe class Foo
{

}

unsafe int FooMethod
{

}

Then you can use pointers with * and & just like C.

I don't know about ActiveX Components in the same address space.

Chet
I ended up using this solution after I posted the question._axetRecord1.SourceBufferMemoryPointer stores the location of the beginning of the memory buffer.The following code does work:[code]short* memPtr;memPtr = (short*)_axetRecord1.SourceBufferMemoryPointer;[/code]
chocojosh
You have to pin the instance if you're going to pass it to native code though!
Paul Betts
+3  A: 

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.

Bryce Kahle
Thanks for the code sample; this is what I ended up using.
chocojosh