Should this work? C++/CLI and Ruby UTF-8 Strings

S

Sam Smoot

I need to convert a .NET Unicode String to a UTF-8 byte-array to create
a Ruby String that I can display on a UTF-8 encoded web-page.

I don't know C++ really, but a friend and I have stumbled our way
through most of what we need. I need to figure out this String->UTF-8
stuff though.

Here's the code:

VALUE ToRubyString(String^ string) {
if (string == nullptr) return Qnil;
IntPtr ptr;
try {
char *ret =
(char*)malloc(4+System::Text::Encoding::UTF8->GetByteCount(string));
cli::array<unsigned char>^ char_array =
System::Text::Encoding::UTF8->GetBytes(string);
cli::pin_ptr<unsigned char> char_pin_ptr = &char_array[0];
strcpy(ret, (char*)char_pin_ptr);
return rb_str_new2((char*)(void*)ret);
// ptr =
System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(string);
// return rb_str_new2((char*)(void*)ptr);
} finally {
System::Runtime::InteropServices::Marshal::FreeHGlobal(ptr);
}
}

Can anyone help here? Or any constructive criticisms you can offer?

Just in case you're curious: The project is for an ActiveRecordAdapter
using ADO.NET through C++/CLI, and is under 400 lines of C++; half of
it (Helpers.cpp) lifted from John Lam's RubyClr project. It seems to be
working relatively stably in testing, but the entire pont of the
project is to write something that properly handles the MSSQL nvarchar
(UTF-16LE) to Ruby UTF-8 String conversion (and vice-versa).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top