Vivek
Vivek

Reputation: 21

Passing pointer to a pointer to a struct as a function parameter in C#

How do I pass a pointer to a pointer to a struct as a function parameter in C#?

I am trying to use a function from a DLL which has one of its arguments as a double pointer. For e.g.,

struct mystruct
{
   int a;
   char b;
};

[DllImport("mydll.dll")]
private static extern int func_name(int a, char b, mystruct** c);

I guess the correct way to use a pointer like int *a is ref int a. Is there anything similar for int **a?

Upvotes: 2

Views: 408

Answers (2)

Cody Gray
Cody Gray

Reputation: 244812

The CLR equivalent for a pointer to a pointer is ref IntPtr.

An IntPtr is a pointer to an integer, and when you pass it by ref, it's transferred by reference, making it a pointer to a pointer.

You may also need to use the Marshal.PtrToStructure method to convert the pointer to your structure object.

See the section entitled "Manual marshalling" near the bottom of this article for more information.

Upvotes: 2

weismat
weismat

Reputation: 7411

I would work differently.
Any pointer should be used as

System.IntPtr

and I would then use

Marshal.PtrToStructure

for the actual conversion of the pointer to actual structure. Otherwise I would also consider to copy field by field with offsets, which is sometimes easier to debug.

Upvotes: 0

Related Questions