November 15th, 2006, 08:42 AM
C# memory allocation
Im attempting to convert a small section of C++ code into C#.
A third party component method expects an address to be passed pointing to an area of allocated memory.
The component then stores data starting from this address.
Is it possible using C#?
November 15th, 2006, 11:32 AM
yes. look into System.Runtime.InteropServices.Marshal and how to use p/invoke.
November 15th, 2006, 12:13 PM
Hi thanks ill take a look.
I have started to get somewhere however:
I pass lSize (the memory address as an integer) to the third party control and it successfull places the size in bytes of the data in this variable.
int lSize = new int();
lSize = (int)&lSize;
The next step is to store the actual data. This will be a bitmap.
I am unsure how to apply to same approach however. I think i need to declare and initalize something, store the address of this in an integer, then pass this integer address to the third party control.
November 15th, 2006, 06:05 PM
Since memory can be represent in many ways lets represent yours with a byte array.
Here is a code sample i created for you.
//You first have to make C# aware of the methods you are going to call.
static extern int GetLength();
// lets say your method is void FillMemory(void* ptr)
static extern void FillMemory(IntPtr ptr);
static void Test()
//you call your method to get how large this chunk of memory needs to be.
int length = GetLength();
//you create a byte array of that size.
Byte buffer = new Byte[length];
//Then you pin that array.
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
// and get a IntPtr to it.
IntPtr bufferPtr = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, index);
//You pass that pointer to the C++ method.
//then unpin the array
// deal with the data in the array.
Comments on this post
November 16th, 2006, 12:35 PM
Thanks for all the help and taking the time to do the example.
Ill give it a try.