How to convert C ++ / CLI string to const char *

I have a C ++ / CLI DLL that I plan to use as an adapter between my C # DLL and C ++ native clients. I need to pass strings in both directions. The adapter is compiled with VS2013, but it needs to support clients built on VS2008, so I use const char * in the API. But what I have does not work, even if both of them are built by VS2013.

Elsewhere, I found advice for using msclr \ marshal.h, so I created:

using namespace msclr::interop;
System::String^ ToCliString(const char* s)
{
    System::String ^result = marshal_as<System::String^>(s);
    return result;
}    
const char* ToCppString(System::String^ s)
{
    msclr::interop::marshal_context context;
    const char* result = context.marshal_as<const char*>(s);
    return result;
}

To test them, I created a round-trip conversion method in my C ++ / CLI DLL:

const char* Foo(const char *cstar)
{
    System::String^ cli = ::ToCliString(cstar);

    if (cli == "abc")
    {
        MessageBox::Show("const char* -> CLI: OK");
    }

    const char* cstar2 = ::ToCppString(cli);

    if (std::strcmp(cstar2, "abc") == 0)
    {
        MessageBox::Show("CLI -> const char*: OK");
    }
    else if (std::strcmp(cstar2, "") == 0)
    {
        MessageBox::Show("ToCppString returned empty string");
    }
    else
    {
        MessageBox::Show("ToCppString returned something else");
    }

    return cstar2;
}

++ Foo ( "abc" ), , " - ", (รพรพรฎรพรฎรพรฎรพรฎรพรฎรพรพรพรพรพรพรพรพรพรพรพรพรพรพรพรพรพรพรพรพรพรพรพ > vรšยง). , , .

UPDATE

, .

zneaks std::string PaulMcKenzie char * const char *. .

void ToCppString(System::String^ input, char* output)
{
    std::string temp= marshal_as<std::string>(input);
    strcpy(output, temp.c_str());
}

void Foo(const char* input, char* output)
{
    System::String^ cli = ::ToCliString(input);
    ::ToCppString(cli, output);
}
+4
2

, marshal_context char, , :

System:: String const char *. .

marshal_as<std::string>, marshal_context.

+1

, , V++ 2008 express (marshal.h ), V++ 2008 pro . , - VS2010.

0

Source: https://habr.com/ru/post/1624355/


All Articles