How to directly access the memory using an intPtr

B

Beorne

I have imported a corporate image handling COM object in my C#
project.
To access in a fast way the memory of the image there is a method that
returns a pointer to the memory (in byte) of the underlying image.
This method can be used to read as well to rewrite the pixel values.
In the interface .idl file the method is declared as:

[helpstring("Get a pointer to the pixels of a plane")]
HRESULT GetPlane([out,size_is(,*dim)] BYTE ** pPlane,
[out,unique] long *dim);

C# imports the method as:
void GetPlane(intPtr pPlane, out int dim)

I haven't found a way to directly access (read and write) the memory
pointed by intPtw without the need of copying to managed memory.

An example of error:

int planeSize;
byte b;
int v;
unsafe
{
IntPtr pPlane = new IntPtr((void*)&b); // here I tried with pPlane =
new IntPtr.Zero but gave me NullReferenceException
img.GetPlane(pPlane, out planeSize);
byte* pByte = (byte*)pPlane.ToPointer();
for (int i = 0; i < planeSize; i++)
v = greylevels[*(pByte + i)]++; // access violation exception
}

Is it possible to do it? How could I do?
Thanks
 
N

Nicholas Paldino [.NET/C# MVP]

Beorne,

You are going to need to pass the address of a pointer to the GetPlane
method, like so:

// The size of the plane.
int planeSize = 0;

// This will be populated with the pointer to your array.
IntPtr array = IntPtr.Zero;

// Unsafe code.
unsafe
{
// Get the pointer to the array variable.
IntPtr pointer = new IntPtr((void*) &array);

// Make the call.
img.GetPlane(pointer, out planeSize);

// At this point, array should have the first memory location
// of the item in the array.
byte* pByte = (byte*) array.ToPointer();

// Manipulate the array here.
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top