Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn System::String^ into std::string?

So i work in clr, creating .net dll in visual c++.

I tru such code:

 static bool InitFile(System::String^ fileName, System::String^ container)
{
    return enc.InitFile(std::string(fileName), std::string(container));
}

having encoder that normaly resives std::string. but here the compiler (visual studio) gives me C2664 error if I strip out arguments from std::string and C2440 which is in general the same. VS tells me that it just can not to convert System::String^ into std::string.

So I am sad... what shall I do to turn System::String^ into std::string?

Update:

Now with your help I have such code

#include <msclr\marshal.h>
#include <stdlib.h>
#include <string.h>
using namespace msclr::interop;
namespace NSSTW
{
  public ref class CFEW
  {
 public:
     CFEW() {}

     static System::String^ echo(System::String^ stringToReturn)
    {
        return stringToReturn;  
    }

     static bool InitFile(System::String^ fileName, System::String^ container)
    {   
        std::string sys_fileName = marshal_as<std::string>(fileName);;
        std::string sys_container = marshal_as<std::string>(container);;
        return enc.InitFile(sys_fileName, sys_container);
    }
...

but when I try to compile it gives me C4996

error C4996: 'msclr::interop::error_reporting_helper<_To_Type,_From_Type>::marshal_as': This conversion is not supported by the library or the header file needed for this conversion is not included. Please refer to the documentation on 'How to: Extend the Marshaling Library' for adding your own marshaling method.

what to do?

like image 770
Rella Avatar asked Aug 21 '10 22:08

Rella


1 Answers

If you're using VS2008 or newer, you can do this very simply with the automatic marshaling added to C++. For example, you can convert from System::String^ to std::string via marshal_as:

System::String^ clrString = "CLR string";
std::string stdString = marshal_as<std::string>(clrString);

This is the same marshaling used for P/Invoke calls.

like image 160
Chris Schmich Avatar answered Oct 22 '22 20:10

Chris Schmich