mardi 5 juillet 2016

How to DllImport char*

I have a c++ function like this:

myExport.h

extern "C" { __declspec(dllexport) const int Run(char *input, char *output, int *length); }

myExport.cpp

const int Run(char *input, char *output, int *length) {

    std::ostringstream value;
    value
        << "FOO" << "|"
        << "BAR" << "|";

    auto str = value.str();

    auto i = stdext::checked_array_iterator<char*>(output, str.length());
    std::copy(str.begin(), str.end(), i);
    output[str.length()] = '�';

    return 1;
}

And in C# I have:

myImport.cs

[DllImport("MyExport.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern int Run(
    [MarshalAs(UnmanagedType.LPStr)]string input,
    StringBuilder output,
    ref int length);

public static string Execute(string input)
{
    var length = 1024;
    var output = new StringBuilder(1024);
    var result = Run(input, output, ref length);
    return output.ToString();
}

However, the output buffer is always empty. What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire