将字符串数组从c++传递到c#

本文关键字:c++ 字符串 数组 | 更新日期: 2023-09-27 18:14:36

我已经写了这段代码,运行良好:
c++代码

extern "C"
{
    const MYLIBRARY_EXPORT char* giefStrPlx(char* addon)
    {
        return addon;
    }
}

c#代码

[DllImport("ClassLibrary1")]
private static extern IntPtr giefStrPlx(string x);
void Start()
{
    IntPtr stringPtr = giefStrPlx("Huntsman");
    string huntsman = Marshal.PtrToStringAnsi(echoedStringPtr);
}

之后huntsman包含"Huntsman"


我的问题是对字符串数组做类似事情的步骤。我编写了以下函数

extern "C"
{
    const MYLIBRARY_EXPORT bool fillStrArray(char** lizt, int* length)
    {
        char* one = "one";
        char* two = "two";
        char* three = "three";
        lizt[0] = one;
        lizt[1] = two;
        lizt[2] = three;
        *length = 3;
    }
}

然后我试着用c#

写下面这段代码
[DllImport("ClassLibrary1")]
private static extern bool fillStrArray(ref IntPtr array, ref int length);
void Start()
{
    IntPtr charArray = IntPtr.Zero;
    int charArraySize = 0;
    fillStrArray(ref charArray, ref charArraySize);
    IntPtr[] results = new IntPtr[charArraySize];
    Marshal.Copy(charArray, results, 0, charArraySize);
    foreach (IntPtr ptr in results)
    {
        string str = Marshal.PtrToStringAnsi(ptr);
    }
}

不起作用。现在我有点不知道怎么实现这个了

将字符串数组从c++传递到c#

下面是我从CLR到std::string和从std::string到string的两个辅助函数

std::string CLROperations::ClrStringToStdString(String^ str)
{
    if (String::IsNullOrEmpty(str))
        return "";
    std::string outStr;
    IntPtr ansiStr = System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(str); 
    outStr = (const char*)ansiStr.ToPointer(); 
    System::Runtime::InteropServices::Marshal::FreeHGlobal(ansiStr); 
    return outStr;
}
String ^ CLROperations::StdStringToClr(std::string str)
{
    return gcnew String(str.c_str());
}

用于使用字符串列表,您将需要使用List<String^>^注意大写字符串。对于std::string列表使用std::vector<std::string>