Umanaged C++:
int foo(int ** New_Message_Pointer);
How do I marshall this to C#?
[DllImport("example.dll")]
static extern int foo( ???);
1.2 Declaring Pointers Pointers must be declared before they can be used, just like a normal variable. The syntax of declaring a pointer is to place a * in front of the name. A pointer is associated with a type (such as int and double) too.
Pointers are said to "point to" the variable whose address they store. An interesting property of pointers is that they can be used to access the variable they point to directly. This is done by preceding the pointer name with the dereference operator ( * ). The operator itself can be read as "value pointed to by".
2. You can only add or subtract integers to pointers. When you add (or subtract) an integer (say n) to a pointer, you are not actually adding (or subtracting) n bytes to the pointer value. You are actually adding (or subtracting) n-times the size of the data type of the variable being pointed bytes.
A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.
You can declare function like this:
[DllImport("example.dll")]
static extern int foo(IntPtr New_Message_Pointer)
To call this function and pass pointer to int array for e.g you can use following code:
Int32[] intArray = new Int32[5] { 0, 1, 2, 3, 4, 5 };
// Allocate unmamaged memory
IntPtr pUnmanagedBuffer = (IntPtr)Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(Int32)) * intArray.Length);
// Copy data to unmanaged buffer
Marshal.Copy(intArray, 0, pUnmanagedBuffer, intArray.Length);
// Pin object to create fixed address
GCHandle handle = GCHandle.Alloc(pUnmanagedBuffer, GCHandleType.Pinned);
IntPtr ppUnmanagedBuffer = (IntPtr)handle.AddrOfPinnedObject();
And then pass ppUnmanagedBuffer to your function:
foo(ppUnmanagedBuffer);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With