1

Good Day, I've been writing a simple program using the Windows API, it's written in C++/CLI. The problem I've encountered is, I'm loading a library (.dll) and then calling its functions. one of the functions returns char*. So I add the returned value to my textbox

output->Text = System::Runtime::InteropServices::Marshal::PtrToStringAnsi
                   (IntPtr(Function()));

Now, as you can see this is encoded in ANSI, the char* returned is, I presume, also ANSI (or Windows-1252, w/e you guys call it :>). The original data, which the function in LIBRARY gets is encoded in UTF-8, variable-length byte field, terminated by 0x00. There are a lot of non-Latin characters in my program, so this is troubling. I've also tried this

USES_CONVERSION;
wchar_t* pUnicodeString = 0;
pUnicodeString = A2W( Function());

output->Text = System::Runtime::InteropServices::Marshal::PtrToStringUni
                   (IntPtr(pUnicodeString));

using atlconv.h. It still prints malformed/wrong characters. So my question would be, can I convert it to something like UTF-8 so I would be able to see correct output, or does the char* loose the necessary information required to do so? Maybe changing the .dll source code would help, but it's quite old and written in C, so i don't want to mess with it :/ I hope the information I provided was sufficient, if you need anything more, just ask.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Zylius
  • 33
  • 1
  • 4

1 Answers1

1

As I know there is no standard way to handle UTF-8. Try to google appropriate converters, e.g. http://www.nuclex.org/articles/cxx/10-marshaling-strings-in-cxx-cli , Convert from C++/CLI pointer to native C++ pointer .

Also, your second code snippet doesn't use pUnicodeString, it doesn't look right.

Community
  • 1
  • 1
kan
  • 28,279
  • 7
  • 71
  • 101
  • I'm sorry, i misstyped the second code, it should be output->Text = System::Runtime::InteropServices::Marshal::PtrToStringUni(IntPtr(pUnicodeString)); The fact doesn't change though, it's not working :( (I've fixed the original post.) – Zylius Oct 25 '11 at 15:05
  • Have you tried `System::Text::Encoding::UTF8->GetString(bytes)` from the link above? – kan Oct 25 '11 at 15:11
  • How would I use System::Text::Encoding::UTF8->GetString(bytes) with char*? – Zylius Oct 25 '11 at 15:42
  • Have you opened the link?! // Copy the C++ string contents into a managed array of bytes array ^bytes = gcnew array(byteCount); { pin_ptr pinnedBytes = &bytes[0]; memcpy(pinnedBytes, cxxString.c_str(), byteCount); } – kan Oct 25 '11 at 15:46
  • Thank you guys, it's working lovely, sorry for not noticing it kan :), thank you. – Zylius Oct 25 '11 at 16:08