2

I'm trying to figure out how to return a string value from a C++/CLI method back to unmanaged C++ that calls it. In my current implementation, I have a string stored in a local String ^ variable in a (managed) C++/CLI method that I w/like the method to return back to the unmanaged C++ program that calls it. If using a String ^ variable is not a good choice, what construct/type w/be better? Note, I'm leaving out a part where a C# method returns the string value back to the C++/CLI method as it is not a problem.

I'm using VS2017.

CODE Example - for simplicity, code has been reduced.

Unmanaged C++ -----------------------------

_declspec(dllexport) void GetMyString();

int main()
{
    GetMyString();
}

(managed) C++/CLI -------------------------

__declspec(dllexport) String GetMyString()
{
    String ^ sValue = "Return this string";
    return (sValue);
}

Any help is greatly appreciated. Thanks ahead of time.

pgodar
  • 21
  • 3
  • I think you cannot use `String^` in unmanaged c++. Use `std::string` or `std::wstring`. May be you must convert `String^` to std-string in c++/cli. – Tobias Wollgam Nov 25 '19 at 23:18

2 Answers2

0

You cannot return a String ^ to c++, since it will not recognize it. There is some conversions using the InteropServices though. From microsoft

using namespace System;

void MarshalString ( String ^ s, std::string& os ) {
   using namespace Runtime::InteropServices;
   const char* chars =
      (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}
ChrisMM
  • 8,448
  • 13
  • 29
  • 48
0

I ended up converting a System::String^ to a std::string in a managed C++ method, returning the later to the unmanaged C++ caller.


Managed C++ file excerpts:

#include <msclr\marshal_cppstd.h>

__declspec(dllexport) std::string MyManagedCppFn()
{
    System::String^ managed = "test";
    std::string unmanaged2 = msclr::interop::marshal_as<std::string>(managed);
    return unmanaged2;
}

Unmanaged C++ file excerpts:

_declspec(dllexport) std::string MyMangedCppFn();

std::string jjj = MyMangedCppFn();    // call Managed C++ fn

Credit goes to an answer/edit from tragomaskhalos and Juozas Kontvainis to a stackoverflow question asking how to convert a System::String^ to std::string.

pgodar
  • 21
  • 3