2015-09-25 122 views
4

我已经写这段代码的正常工作:
C++代码传递一个字符串数组从C++到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包含“亨斯迈”。


我的问题是对字符串数组做类似的操作。我写了下面的功能

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); 
    } 
} 

不工作。所以现在我对如何完成这一点有点失落。

+0

你的C代码要求你传递一个指向内存的指针,它可以写入字符串指针。 IntPtr.Zero不可写。你也不知道你需要分配多少内存。使用IntPtr charArray = Marshal.AllocHGlobal(crossMyFingers)其中crossMyFingers是一个很大的数字,对于此代码至少需要3 * IntPtr.Size,但应该较大以减少堆损坏的几率。你可以设置* length *参数来帮助它避免这种腐败。 –

+0

感谢您的指针。即使改变,我仍然有问题。我试图在Unity中使用它,并且插件崩溃,这使得调试更加困难。 而不是将指针传递给数组我只是返回一个指针,与第一个示例中的不同。 – Bjorninn

回答

2

这里有两个辅助功能,我从CLR必须的std :: string和的std :: string串CLR

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>

+0

我很抱歉,但我不明白这是如何帮助我解决我遇到的问题。 – Bjorninn

+0

请勿使用IntPtr和char *。改为使用std :: string – Gilad

相关问题