Correct way to convert array<unsigned char>^ to std::string - c++-cli

I wanted to know what is the correct way to convert a managed array<unsigned char>^ to an unmanaged std::string. What I do right now is this:
array<unsigned char>^ const content = GetArray();
auto enc = System::Text::Encoding::ASCII;
auto const source = enc->GetString(content);
std::string s = msclr::interop::marshal_as<std::string>(source);
Is there a way to marshal the content in one step to a std::string without converting to a String^?
I tried:
array<unsigned char>^ const content = GetArray();
std::string s = msclr::interop::marshal_as<std::string>(content);
but this gave me following errors:
Error C4996 'msclr::interop::error_reporting_helper<_To_Type,cli::array<unsigned char,1> ^,false>::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.
Error C2065 '_This_conversion_is_not_supported': undeclared identifier

If the array is of plain bytes, then it's already ASCII encoded (or whatever narrow characters you're using). Converting to a managed UTF-16 String^ is an unnecessary detour.
Just construct a narrow-characters string from the byte array. Pass a pointer to the first byte and the length.
array<unsigned char>^ const content = GetArray();
pin_ptr<unsigned char> contentPtr = &content[0];
std::string s(contentPtr, content->Length);
I'm not at a compiler right now, there may be trivial syntax errors.

Related

C/C++ DLL: Converting a const uint8_t to a String

I haven't seen C++ code in more than 10 years and now I'm in the need of developing a very small DLL to use the Ping class (System::Net::NetworkInformation) to make a ping to some remoteAddress.
The argument where I'm receiving the remoteAddress is a FREObject which then needs to be transformed into a const uint8_t *. The previous is mandatory and I can't change anything from it. The remoteAddress has to be received as a FREObject and later be transformed in a const uint8_t *.
The problem I'm having is that I have to pass a String^ to the Ping class and not a const uint8_t * and I have no clue of how to convert my const uint8_t * to a String^. Do you have any ideas?
Next is part of my code:
// argv[ARG_IP_ADDRESS_ARGUMENT holds the remoteAddress value.
uint32_t nativeCharArrayLength = 0;
const uint8_t * nativeCharArray = NULL;
FREResult status = FREGetObjectAsUTF8(argv[ARG_IP_ADDRESS_ARGUMENT], &nativeCharArrayLength, &nativeCharArray);
Basically the FREGetObjectAsUTF8 function fills the nativeCharArray array with the value of argv[ARG_IP_ADDRESS_ARGUMENT] and returns the array's length in nativeCharArrayLength. Also, the string uses UTF-8 encoding terminates with the null character.
My next problem would be to convert a String^ back to a const uint8_t *. If you can help with this as well I would really appreciate it.
As I said before, non of this is changeable and I have no idea of how to change nativeCharArray to a String^. Any advice will help.
PS: Also, the purpose of this DLL is to use it as an ANE (Air Native Extension) for my Adobe Air app.
You'll need UTF8Encoding to convert the bytes to characters. It has methods that take pointers, you'll want to take advantage of that. You first need to count the number of characters in the converted string, then allocate an array to store the converted characters, then you can turn it into System::String. Like this:
auto converter = gcnew System::Text::UTF8Encoding;
auto chars = converter->GetCharCount((Byte*)nativeCharArray, nativeCharArrayLength-1);
auto buffer = gcnew array<Char>(chars);
pin_ptr<Char> pbuffer = &buffer[0];
converter->GetChars((Byte*)nativeCharArray, nativeCharArrayLength-1, pbuffer, chars);
String^ result = gcnew String(buffer);
Note that the -1 on nativeCharArrayLength compensates for the zero terminator being included in the value.

Convert System::String to std::string in UTF8, which later converted to char* as c_str

I have a System::String^ variable in C++ code. This variable should be converted to std::string which is later converted to const char* via c_str.
// original string
System::String^ path = ...;
// convert to std::string
msclr::interop::marshal_context context;
std::string filename(context.marshal_as<std::string>(path));
// call API function that internally connects to sqlite3 using sqlite3_open as
// sqlite3_open(filename.c_str())
// https://www.sqlite.org/c3ref/open.html -
// const char *filename, /* Database filename (UTF-8) */
doCalculation(filename)
It works well with the ASCII paths, but fails if the path contains non-latin characters.
So Somehow I need to convert marshalled std::string from current implementation (ASCII?) to UTF8.
I've tried
std::wstring dbPath(context.marshal_as<std::wstring>(path));
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> convert;
std::string dbPathU8 = convert.to_bytes(dbPath);
but it does not work.
What you want to do is use the .Net methods to convert directly to UTF-8.
The available methods in the Encoding class aren't exactly what you're looking for (direct from managed String to unmanaged string or byte array), so we'll need an intermediary and some manual copying.
String^ path = ...;
// First, convert to a managed array of the bytes you want.
array<Byte>^ bytes = Encoding::UTF8->GetBytes(path);
// Then, copy those bytes from the managed byte array to an unmanaged string.
std::string str;
str.resize(bytes->Length);
Marshal::Copy(bytes, 0, IntPtr(str.data()), bytes->Length);
// OR, copy directly to the char* you want eventually.
char* chars = new char[bytes->Length + 1]; // or malloc(), or whatever.
Marshal::Copy(bytes, 0, IntPtr(chars), bytes->Length);
chars[bytes->Length] = '\0'; // null terminate.
// don't forget to free the buffer when you're done with it!
There are several GetBytes variants available, but the parameters to them seem to either be both managed, or both unmanaged. (String^ and array^, or char* and byte*, but not String^ and byte*.) Therefore, we have the Encoding class create a managed byte array, then we use the Marshal::Copy method to copy those bytes either to the unmanaged string object, or directly to a char*.

How to convert a handle string to a std::string

I am trying to convert a handle string to a normal string. I though the method I was using was working, but when I look in the debugger it appears that half of my string has been chopped off on the line that creates the chars variable. Any idea why and what the proper way to convert a handle string to a normal string woudl be?
std::string convert(String^ s) {
const char* chars = (const char*)(System::Runtime::InteropServices::Marshal::
StringToHGlobalAnsi(s)).ToPointer();
string myNewString = std::string(chars);
return myNewString;
}
It's probably the debugger that's cutting off the display of the string. You didn't mention how long a string you're using, but the debugger can't display infinite length, so it has to cut it off at some point.
To verify this, try printing myNewString to the console, or to the debugger via Debug::WriteLine or OutputDebugString.
However, there is a significant issue in your code: After allocating memory with StringToHGlobalAnsi, you must free it using FreeHGlobal.
If you want to continue using StringToHGlobalAnsi, I'd fix it up like this:
std::string convert(String^ s) {
IntPtr ptr = Marshal::StringToHGlobalAnsi(s);
string myNewString = std::string((const char*)ptr.ToPointer());
Marshal::FreeHGlobal(ptr);
return myNewString;
}
However, it's probably easier to use the marshal_as methods. This will take care of everything for you.
std::string output = marshal_as<std::string>(managedString);

C++/CLI, I have a Byte[] and I need a char* to the first and last elements

I've been handed a Byte[] that contains a file. I need to pass this to another method that is expecting two parameters, a char* to the beginning of the file and a char* to the end of the file.
I'm assuming I need to pin the array first so it doesn't get collected. I don't imagine I can then just cast the first and last elements, right?
Old question, but I just found out that you can create a pin_ptr<unsigned char> from such an array and then reinterpret_cast the result.
pin_ptr<unsigned char> pinned = &buffer[0];
unsigned char* unsignedBufferPtr = pinned;
char* bufferPtr = reinterpret_cast<char*>(unsignedBufferPtr);
You can then use a reinterpret_cast on the result

How to convert System::IntPtr to char*

can any body tell How to convert System::IntPtr to char* in managed c++
this is my main function
int main(void)
{
String* strMessage = "Hello world";
CManagedClass* pCManagedClass = new CManagedClass();//working
pCManagedClass->ShowMessage(strMessage);//working
****above said error here***
char* szMessage = (char*)Marshal::StringToHGlobalAnsi(strMessage);
CUnmanagedClass cUnmanagedClass; cUnmanagedClass.ShowMessageBox(szMessage);
Marshal::FreeHGlobal((int)szMessage);
return 0;
}
thanks in advance
I'm not a huge C++/CLI programmer, but the following should work just fine.
IntPtr p = GetTheIntPtr();
char* pChar = reinterpret_cast<char*>(p.ToPointer());
The IntPtr class has a method called ToPointer which returns the address as a void* type. That will be convertible to char* in C++/CLI.
EDIT
Verified this works on VS2008 and VS2015
Instead of
char* szMessage = (char*)Marshal::StringToHGlobalAnsi(strMessage).ToPointer();
Marshal::FreeHGlobal((int)szMessage);
Use
marshal_context conversions.
const char* szMessage = conversions.marshal_as<const char*>(strMessage);
It cleans itself up, the magic of C++ RAII.
Attention!
I want to add something to JaredPar answer.I don't know where your IntPtr is coming from but you should also use pin_ptr in order to prevent the garbage collector from messing up your memory. I did lot of CLR/Native inter op in the past and using pin_ptr is one of those things that I learnt to do in the hard way.
read the following:
click me