1

Given the following C API:

void foo(const char ** stringArray, size_t arrayCount);

I want to create a PInvoke adapter for it in C#. I can make a one-to-one mapping in C# as:

[DllImport("x.dll", ...)]  // char set, etc. omitted
public static extern void foo(string[] stringArray, int arrayCount);

I'd like an implicit second parameter.

// Psuedo-code
[DllImport("x.dll", ...)]
public static extern void foo(string[] stringArray, 
                              [MarshalAs(stringArray.Length)] int arrayCount);

Obviously the [MarshalAs()] part is made-up.

The goal is for the C# calling code to look like this:

string[] list = { "x", "y" };
foo(list);

I can make a simple wrapper around the PInvoke, but I was wondering if that is the best way, or if my PInvoke declaration can directly solve?

1 Answer 1

3

Just create a wrapper function:

private static extern void foo(string[] stringArray, int arrayCount);

public static void foo(string[] stringArray) {
    foo(stringArray, stringArray.Length);
}

This is a far easier and more flexible solution.

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

1 Comment

Don't forget [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)]

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.