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

**URL:** <https://www.ruby-forum.com/t/should-this-work-c-cli-and-ruby-utf-8-strings/71540>\
**Category:** Ruby\
**Created:** [October 9, 2006, 7:02pm UTC](https://www.ruby-forum.com/t/should-this-work-c-cli-and-ruby-utf-8-strings/71540 "2006-10-09T19:02:13Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![sams](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/e79b87/32.png) [@sams](https://www.ruby-forum.com/u/sams)\
**Post date:** [October 9, 2006, 7:02pm UTC](https://www.ruby-forum.com/t/should-this-work-c-cli-and-ruby-utf-8-strings/71540/1 "2006-10-09T19:02:13Z")

</div>

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^ char\_array =  
System::Text::Encoding::UTF8-\>GetBytes(string);  
cli::pin\_ptr 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](http://ADO.NET) through C++/CLI, and is under 400 lines of C++; half of  
it (Helpers.cpp) lifted from John L.'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).
