2

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.