Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array of strings from C++ to C#

I've already written this piece of code which works fine:
C++ code

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

C# code

[DllImport("ClassLibrary1")]
private static extern IntPtr giefStrPlx(string x);

void Start()
{

    IntPtr stringPtr = giefStrPlx("Huntsman");
    string huntsman = Marshal.PtrToStringAnsi(echoedStringPtr);
}

After this huntsman contains "Huntsman".


My problem is the step of doing something similar for an array of strings. I wrote the following function

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

I then tried to write the following piece of code in 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);
    }
}

Which does not work. So now I'm a bit lost on how to accomplish this.

like image 581
Bjorninn Avatar asked Sep 25 '15 15:09

Bjorninn


1 Answers

Here are the two helper functions I have from CLR to std::string and from std::string to 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());
}

for using a List of strings you will need to use List<String^>^ mind the capital String. for a list of std::string use std::vector<std::string>

like image 172
Gilad Avatar answered Sep 21 '22 10:09

Gilad