从C ++将const char * const *(在struct内部)封送至C#

时间:2018-08-12 22:17:19

标签: c# c++ marshalling

我正在尝试将const char * char *从dll封送至C#。我目前可以成功地返回包含const char * char *和两个int变量的结构。完整的int变量(Count和Score)完好无损,但是const char * char *单词被视为垃圾。

这是结构定义(在标题中):

struct __declspec(dllexport) Results {
    const char* const* Words;
    unsigned Count;
    unsigned Score;
    void* UserData;
}; 

extern "C"
{
    __declspec(dllexport) Results TestResults();
}

这是我的C#:

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct Results
    {
        [MarshalAs(UnmanagedType.ByValArray, ArraySubType = 
        UnmanagedType.LPStr)]
        public IntPtr[] Words;
        public int Count;
        public int Score;
    };

    [DllImport("Test.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr TestResults();

最后,我在Main()中的测试:

    Results LocalResults = Marshal.PtrToStructure<Results>(TestResults());

    Console.WriteLine(LocalResults.Count.ToString());
    Console.WriteLine(LocalResults.Score.ToString());

    for (int i = 0; i < 4; i++)
    {

        Console.WriteLine(Marshal.PtrToStringAnsi(LocalResults.Words[i]));
    }

(编辑)

也许我从c ++提供的数据有问题:

__declspec(dllexport) Results TestResults() {

    Results r;

    const char* array[5];
    for (int i = 0; i < 5; i++) {
        array[i] = _dict[i].c_str();
    }
    const char** p = array;
    r.Words = p;

    r.Count = 3;
    r.Score = 4;

    return r;
}

0 个答案:

没有答案