Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I marshal a pointer to a pointer to an int?

Umanaged C++:

int  foo(int **    New_Message_Pointer);

How do I marshall this to C#?

[DllImport("example.dll")]
static extern int foo( ???);
like image 867
user2134127 Avatar asked Jul 12 '13 16:07

user2134127


People also ask

How will you declare a pointer to a pointer to an integer?

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.

How do you point a pointer to a variable?

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".

Can you add a pointer and integer?

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.

Can you point to a pointer in C++?

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.


1 Answers

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);
like image 165
SergeyIL Avatar answered Oct 06 '22 00:10

SergeyIL