开发者

P/Invoking a native function that accepts pointers to pairs of strings

I have a Visual Studio 2008 C# .NET 2.0CF application where I need to P/Invoke a native function with the following signature:

/// @brief count - number of pairs
/// @brief pairs - pairs of pointers to strings
void Foo( int count, const char* pairs[][ 2 ] );

In C++, this could be used:

const char* pairs[][2] = { { "Hello", "Bob" }, { "Goodbye", "Diane" } };
Foo( 2, pairs );

How would one write the [DllImport()] signature of s开发者_StackOverflow社区uch a function?

Thanks, PaulH


Like this:

[DllImport("...")]
private static extern void Foo(int count, string[] pairs);

The C# that corresponds to your example is:

var pairs = new[] { "Hello", "Bob", "Goodbye", "Diane" };
Foo(pairs.Length >> 1, pairs);

I tested this with a mock C library and it works as advertised.

libtest.c:

#include <stdio.h>

void Foo( int count, const char* pairs[][ 2 ] ) {
    int i;

    for (i = 0; i < count; i++) {
        printf("%d: %s\n", i, pairs[i][0]);
        printf("%d: %s\n", i, pairs[i][1]);
    }
}

test.cs:

using System;
using System.Runtime.InteropServices;

public static class Foobar {
    public static void Main() {
        var strings = new[] {
            "The", "quick",
            "brown", "fox",
            "jumped", "over",
            "the", "lazy",
            "dog", "LOL"
        };

        Foo(strings.Length >> 1, strings);
    }

    [DllImport("test")]
    private static extern void Foo(int count, string[] pairs);
}

Output:

0: The
0: quick
1: brown
1: fox
2: jumped
2: over
3: the
3: lazy
4: dog
4: LOL
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜