std::string marshalling
-
I am having difficulty handling a vector that is returned from unmanaged code and then converting it to an ArrayList of String. I get the following error: cannot convert parameter 1 from 'std::string' to 'System::Object __gc * How do I Marshal this? #ifndef __STAT_H__ #define __STAT_H__ #include #include // Unmanaged file class CStatus { public: std::vector statuses; CStatus() {} }; #endif // EOF // in Managed file ArrayList statuses = new ArrayList(); CStatus stat; int iReturn = SubmitJob( stat); for (unsigned int ivector = 0; ivector < stat.statuses.size(); ivector++) { statuses->Add((stat.statuses[ivector])); // ERROR occurs } Thanks for all advice.
-
I am having difficulty handling a vector that is returned from unmanaged code and then converting it to an ArrayList of String. I get the following error: cannot convert parameter 1 from 'std::string' to 'System::Object __gc * How do I Marshal this? #ifndef __STAT_H__ #define __STAT_H__ #include #include // Unmanaged file class CStatus { public: std::vector statuses; CStatus() {} }; #endif // EOF // in Managed file ArrayList statuses = new ArrayList(); CStatus stat; int iReturn = SubmitJob( stat); for (unsigned int ivector = 0; ivector < stat.statuses.size(); ivector++) { statuses->Add((stat.statuses[ivector])); // ERROR occurs } Thanks for all advice.
You only have to marshal your strings to CLR Strings, since all CLR reference types (including String) are based on Object. Then you can Add() your Strings to an ArrayList. If your std::strings are strictly lower ASCII (and I do mean 7-bit ASCII, not MBCS/ANSI), the following method will work:
using namespace System; using namespace System::Collections; using namespace System::Text; using namespace std; vector vec; string s = "a std::string"; vec.push_back(s); ASCIIEncoding *enc = new ASCIIEncoding(); String *sCopy = new String(vec[0].c_str(), 0, vec[0].size(), enc); ArrayList *al = new ArrayList(); al->Add(sCopy);
For anything beyond English, you will need to use either Marshal::PtrToStringAnsi() or MultiByteToWideChar(). I could explain that if it's what you need instead. Cheers