# Ruby 'C' Extensions and Unicode

**URL:** <https://rubytalk.org/t/ruby-c-extensions-and-unicode/57341>\
**Category:** ruby-talk\
**Created:** [9 February 2010 12:15 UTC](https://rubytalk.org/t/ruby-c-extensions-and-unicode/57341 "2010-02-09T12:15:06Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![Praveen](https://avatars.discourse-cdn.com/v4/letter/p/3ec8ea/32.png) [@Praveen](https://rubytalk.org/u/Praveen)\
**Post date:** [9 February 2010 12:15 UTC](https://rubytalk.org/t/ruby-c-extensions-and-unicode/57341/1 "2010-02-09T12:15:06Z")

</div>

Hi,

I am working on enhancing the IBM\_DB Ruby driver (database driver for  
DB2 and Informix) by providing unicode support.

I tried googling with no luck to find any documents or links which  
talk about the Ruby C extension API's that can be used to unleash the  
unicode support of Ruby-1.9 to

1) Convert Ruby string (unicode) object received in the extension API  
into wchar (like rb\_str2cstr, in ruby-1.8)

2) Convert wchar\* to a Ruby Object (like rb\_str\_new2, in ruby-1.8).

3) Convert string objects between different formats (UCS-2, UCS-4).

Could some body put light on the answers for the above queries.

Along with the above things could you also tell me if Ruby by default  
is compiled to use UCS-2 or UCS-4 or other format strings and how will  
I be able to tap this info, of which format is being used,  
programmatically in the extension.

Thanks

Praveen

---

<div class="post-metadata">

**Author:** ![KUBO\_Takehiro](https://avatars.discourse-cdn.com/v4/letter/k/3be4f8/32.png) [@KUBO\_Takehiro](https://rubytalk.org/u/KUBO_Takehiro)\
**Post date:** [9 February 2010 13:06 UTC](https://rubytalk.org/t/ruby-c-extensions-and-unicode/57341/2 "2010-02-09T13:06:05Z")

</div>

> Hi,
> 
> I am working on enhancing the IBM\_DB Ruby driver (database driver for  
> DB2 and Informix) by providing unicode support.
> 
> I tried googling with no luck to find any documents or links which  
> talk about the Ruby C extension API's that can be used to unleash the  
> unicode support of Ruby-1.9 to

Look at ruby-1.9.1-pxxx/include/ruby/encoding.h and ruby-1.9.1-pxxx/string.c.

> 1) Convert Ruby string (unicode) object received in the extension API  
> into wchar (like rb\_str2cstr, in ruby-1.8)

No generic way because wchar's encoding is platform-dependent.  
As far as I know, it is UCS-2 in Windows, UCS-4 in Linux, locale-dependent  
value in Solaris.

If it is UCS-2,  
&nbsp;&nbsp;rb\_encoding \*ucs2\_enc = rb\_enc\_find("UCS-2");  
&nbsp;&nbsp;VALUE ucs2\_string = rb\_str\_export\_to\_enc(string, ucs2\_enc);  
&nbsp;&nbsp;const char \*ucs2\_cstr = StringValueCStr(ucs2\_string);

> 2) Convert wchar\* to a Ruby Object (like rb\_str\_new2, in ruby-1.8).

If the wchar's encoding is UCS-2,  
&nbsp;&nbsp;rb\_encoding \*ucs2\_enc = rb\_enc\_find("UCS-2");  
&nbsp;&nbsp;VALUE ucs2\_string = rb\_external\_str\_new\_with\_enc(cstr, len, usc2\_enc);

> 3) Convert string objects between different formats (UCS-2, UCS-4).

&nbsp;&nbsp;rb\_encoding \*ucs2\_enc = rb\_enc\_find("UCS-2");  
&nbsp;&nbsp;rb\_encoding \*ucs4\_enc = rb\_enc\_find("UCS-4");  
&nbsp;&nbsp;VALUE ucs4\_string = rb\_str\_conv\_enc(ucs2\_string, ucs2\_enc, ucs4\_enc);

> **···**
>
> On Tue, Feb 9, 2010 at 9:15 PM, Praveen \<praveendevarao@gmail.com\> wrote:

---

<div class="post-metadata">

**Author:** ![KUBO\_Takehiro](https://avatars.discourse-cdn.com/v4/letter/k/3be4f8/32.png) [@KUBO\_Takehiro](https://rubytalk.org/u/KUBO_Takehiro)\
**Post date:** [9 February 2010 13:14 UTC](https://rubytalk.org/t/ruby-c-extensions-and-unicode/57341/3 "2010-02-09T13:14:21Z")

</div>

Sorry, UCS-2 and UCS-4 are not defined in ruby 1.9.1.  
Use UTF-16LE, UTF-16BE, UTF-32LE or UTF-32BE instead.

> **···**
>
> On Tue, Feb 9, 2010 at 10:06 PM, KUBO Takehiro \<kubo@jiubao.org\> wrote:
> 
> > rb\_encoding \*ucs2\_enc = rb\_enc\_find("UCS-2");  
> > rb\_encoding \*ucs4\_enc = rb\_enc\_find("UCS-4");

---

<div class="post-metadata">

**Author:** ![Praveen](https://avatars.discourse-cdn.com/v4/letter/p/3ec8ea/32.png) [@Praveen](https://rubytalk.org/u/Praveen)\
**Post date:** [9 February 2010 16:40 UTC](https://rubytalk.org/t/ruby-c-extensions-and-unicode/57341/4 "2010-02-09T16:40:25Z")

</div>

Hi Kubo,

Thanks for the information.

I will give a try and get back to you on how I progress [with doubts/  
Success ].

Thanks

Praveen

---

<div class="post-metadata">

**Author:** ![Praveen](https://avatars.discourse-cdn.com/v4/letter/p/3ec8ea/32.png) [@Praveen](https://rubytalk.org/u/Praveen)\
**Post date:** [16 February 2010 09:17 UTC](https://rubytalk.org/t/ruby-c-extensions-and-unicode/57341/5 "2010-02-16T09:17:59Z")

</div>

Hi Kubo,

I tried proceeding with the above mentioned APIs. However I am seeing  
some interesting stuffs. Not sure if I am using the right constructs.

Below is the Ruby script I am using:

> **···**
>
> ======================================  
> #encoding: utf-8
> 
> puts "Results in C extension"  
> puts "----------------------"  
> require 'ibm\_db'  
> str = "insert into woods (name) values ('GÜHRING文')"
> 
> conn = IBM\_DB.connect 'DRIVER={IBM DB2 ODBC  
> DRIVER};DATABASE=devdb;HOSTNAME=9.124.159.74;PORT=50000;PROTOCOL=TCPIP;UID=db2admin;PWD=db2admin;','',''  
> stmt = IBM\_DB.exec conn, str  
> IBM\_DB.close conn
> 
> print "----------------------\n\n"
> 
> puts "Results in Ruby script"  
> puts "----------------------"
> 
> # puts "str.length is :#{str.length}" puts "str.bytesize: #{str.bytesize}" puts "\*\*Forcing encoding\*\*" str1 = str.force\_encoding("UTF-16LE") puts "str.length is :#{str1.length}" puts "str.bytesize: #{str1.bytesize}"
> 
> In the script above, IBM\_DB is the C extension module. However the  
> database call has got nothing to do with the unicode API usage. I have  
> just resused the module for trying the unicode support.
> 
> The snippet in C extension that uses the unicode functions is as  
> below:
> 
> ======================================  
> VALUE ibm\_db\_exec(int argc, VALUE \*argv, VALUE self){  
> &nbsp;&nbsp;rb\_scan\_args(argc, argv, "21", &connection, &stmt, &options);  
> &nbsp;&nbsp;if (!NIL\_P(stmt)) {  
> &nbsp;&nbsp;&nbsp;&nbsp;rb\_encoding \*enc\_received;  
> &nbsp;&nbsp;&nbsp;&nbsp;rb\_encoding \*ucs2\_enc = rb\_enc\_find("UTF-16LE");  
> &nbsp;&nbsp;&nbsp;&nbsp;rb\_encoding \*ucs4\_enc = rb\_enc\_find("UTF-32LE");
> 
> &nbsp;&nbsp;&nbsp;&nbsp;enc\_received = rb\_enc\_from\_index(ENCODING\_GET(stmt));
> 
> &nbsp;&nbsp;&nbsp;&nbsp;printf("\nString in received format: %s\n",RSTRING\_PTR(stmt));  
> &nbsp;&nbsp;&nbsp;&nbsp;printf("\nrb\_str\_length is: %d\n",rb\_str\_length(stmt));  
> &nbsp;&nbsp;&nbsp;&nbsp;printf("\nRSTRING\_LEN is: %d\n",RSTRING\_LEN(stmt));  
> &nbsp;&nbsp;&nbsp;&nbsp;printf("\nEncoding format received: %s\n",enc\_received-\>name);
> 
> &nbsp;&nbsp;&nbsp;&nbsp;stmt\_ucs2 = rb\_str\_export\_to\_enc(stmt,ucs2\_enc);
> 
> &nbsp;&nbsp;&nbsp;&nbsp;printf("\nString in utf16 format: %s\n",RSTRING\_PTR(stmt\_ucs2));  
> &nbsp;&nbsp;&nbsp;&nbsp;printf("\nrb\_str\_length is: %d\n",rb\_str\_length(stmt\_ucs2));  
> &nbsp;&nbsp;&nbsp;&nbsp;printf("\nRSTRING\_LEN is: %d\n",RSTRING\_LEN(stmt\_ucs2));  
> &nbsp;&nbsp;&nbsp;&nbsp;printf("\nEncoding after conversion: %s\n",ucs2\_enc-\>name);  
> &nbsp;&nbsp;}  
> }
> 
> ======================================
> 
> The above ruby script run produces the following output:
> 
> ======================================
> 
> Results in C extension  
> ----------------------
> 
> String in received format: insert into woods (name) values  
> ('GÃHRINGæ')
> 
> rb\_str\_length is: 89
> 
> RSTRING\_LEN is: 47
> 
> Encoding format received: UTF-8
> 
> String in utf16 format: i #Expected because used printf
> 
> rb\_str\_length is: 89
> 
> RSTRING\_LEN is: 88
> 
> Encoding after conversion: UTF-16LE  
> ----------------------
> 
> Results in Ruby script  
> ----------------------  
> str.length is :44  
> str.bytesize: 47  
> \*\*Forcing encoding\*\*  
> str.length is :24  
> str.bytesize: 47
> 
> ======================================
> 
> I am not sure why is there a difference in the string length in the  
> original string [44] (UTF-8 format) and string after changing the  
> encoding [24] (to UTF-16LE). The same is the case in case of output in  
> the C extension, the bytesize and the length are same (+1 or -1) and  
> the length is different in different encoding formats.
> 
> Could you tell me what is that I am doing wrong?
> 
> Along with this, in C extension is there any API that I can call to  
> check if the given string is in a particular encoding or should I use  
> rb\_enc\_from\_index and from there read the struct member name and  
> determine in the extension that I write?
> 
> Thanks
> 
> Praveen

---

<div class="post-metadata">

**Author:** ![Praveen](https://avatars.discourse-cdn.com/v4/letter/p/3ec8ea/32.png) [@Praveen](https://rubytalk.org/u/Praveen)\
**Post date:** [16 February 2010 12:55 UTC](https://rubytalk.org/t/ruby-c-extensions-and-unicode/57341/6 "2010-02-16T12:55:07Z")

</div>

Forgot to mention. I am on ruby version

ruby 1.9.1p0 (2009-01-30 revision 21907) [x86\_64-linux].

Let me know if you require any info

Thanks

Praveen

---

<div class="post-metadata">

**Author:** ![Heesob\_Park](https://avatars.discourse-cdn.com/v4/letter/h/3bc359/32.png) [@Heesob\_Park](https://rubytalk.org/u/Heesob_Park)\
**Post date:** [16 February 2010 14:49 UTC](https://rubytalk.org/t/ruby-c-extensions-and-unicode/57341/7 "2010-02-16T14:49:47Z")

</div>

Hi,

> Hi Kubo,
> 
> I tried proceeding with the above mentioned APIs. However I am seeing  
> some interesting stuffs. Not sure if I am using the right constructs.
> 
> Below is the Ruby script I am using:
> 
> ======================================  
> #encoding: utf-8
> 
> puts "Results in C extension"  
> puts "----------------------"  
> require 'ibm\_db'  
> str = "insert into woods (name) values ('GÜHRING文')"
> 
> conn = IBM\_DB.connect 'DRIVER={IBM DB2 ODBC  
> DRIVER};DATABASE=devdb;HOSTNAME=9.124.159.74;PORT=50000;PROTOCOL=TCPIP;UID=db2admin;PWD=db2admin;','',''  
> stmt = IBM\_DB.exec conn, str  
> IBM\_DB.close conn
> 
> print "----------------------\n\n"
> 
> puts "Results in Ruby script"  
> puts "----------------------"
> 
> # puts "str.length is :#{str.length}" puts "str.bytesize: #{str.bytesize}" puts "\*\*Forcing encoding\*\*" str1 = str.force\_encoding("UTF-16LE") puts "str.length is :#{str1.length}" puts "str.bytesize: #{str1.bytesize}"
> 
> In the script above, IBM\_DB is the C extension module. However the  
> database call has got nothing to do with the unicode API usage. I have  
> just resused the module for trying the unicode support.
> 
> The snippet in C extension that uses the unicode functions is as  
> below:
> 
> ======================================  
> VALUE ibm\_db\_exec(int argc, VALUE \*argv, VALUE self){  
> rb\_scan\_args(argc, argv, "21", &connection, &stmt, &options);  
> if (!NIL\_P(stmt)) {  
> rb\_encoding \*enc\_received;  
> rb\_encoding \*ucs2\_enc = rb\_enc\_find("UTF-16LE");  
> rb\_encoding \*ucs4\_enc = rb\_enc\_find("UTF-32LE");
> 
> enc\_received = rb\_enc\_from\_index(ENCODING\_GET(stmt));
> 
> printf("\nString in received format: %s\n",RSTRING\_PTR(stmt));  
> printf("\nrb\_str\_length is: %d\n",rb\_str\_length(stmt));  
> printf("\nRSTRING\_LEN is: %d\n",RSTRING\_LEN(stmt));  
> printf("\nEncoding format received: %s\n",enc\_received-\>name);
> 
> stmt\_ucs2 = rb\_str\_export\_to\_enc(stmt,ucs2\_enc);
> 
> printf("\nString in utf16 format: %s\n",RSTRING\_PTR(stmt\_ucs2));  
> printf("\nrb\_str\_length is: %d\n",rb\_str\_length(stmt\_ucs2));  
> printf("\nRSTRING\_LEN is: %d\n",RSTRING\_LEN(stmt\_ucs2));  
> printf("\nEncoding after conversion: %s\n",ucs2\_enc-\>name);  
> }  
> }
> 
> ======================================
> 
> The above ruby script run produces the following output:
> 
> ======================================
> 
> Results in C extension  
> ----------------------
> 
> String in received format: insert into woods (name) values  
> ('GÃHRINGæ')
> 
> rb\_str\_length is: 89
> 
> RSTRING\_LEN is: 47
> 
> Encoding format received: UTF-8
> 
> String in utf16 format: i #Expected because used printf
> 
> rb\_str\_length is: 89
> 
> RSTRING\_LEN is: 88
> 
> Encoding after conversion: UTF-16LE  
> ----------------------
> 
> Results in Ruby script  
> ----------------------  
> str.length is :44  
> str.bytesize: 47  
> \*\*Forcing encoding\*\*  
> str.length is :24  
> str.bytesize: 47
> 
> ======================================
> 
> I am not sure why is there a difference in the string length in the  
> original string [44] (UTF-8 format) and string after changing the  
> encoding [24] (to UTF-16LE). The same is the case in case of output in  
> the C extension, the bytesize and the length are same (+1 or -1) and  
> the length is different in different encoding formats.

89 is not an integer but a VALUE. VALUE of 89 means 44 of integer.

> Could you tell me what is that I am doing wrong?

You should use String#encode instead of String#force\_encode like this:

puts "\*\*Converting encoding\*\*"  
str1 = str.encode("UTF-16LE")  
puts "str.length is :#{str1.length}"  
puts "str.bytesize: #{str1.bytesize}"

> Along with this, in C extension is there any API that I can call to  
> check if the given string is in a particular encoding or should I use  
> rb\_enc\_from\_index and from there read the struct member name and  
> determine in the extension that I write?

Using rb\_enc\_get is more simple then rb\_enc\_from\_index like this:  
&nbsp;&nbsp;&nbsp;&nbsp;enc\_received = rb\_enc\_get(stmt);

And, rb\_str\_length returns not an integer but a VALUE. So you should  
use NUM2INT like this:  
&nbsp;&nbsp;&nbsp;&nbsp;printf("\nrb\_str\_length is: %d\n",NUM2INT(rb\_str\_length(stmt)));

Regards,

Park Heesob

> **···**
>
> 2010/2/16 Praveen \<praveendevarao@gmail.com\>:

---

<div class="post-metadata">

**Author:** ![Lui\_Core](https://avatars.discourse-cdn.com/v4/letter/l/90ced4/32.png) [@Lui\_Core](https://rubytalk.org/u/Lui_Core)\
**Post date:** [16 February 2010 14:11 UTC](https://rubytalk.org/t/ruby-c-extensions-and-unicode/57341/8 "2010-02-16T14:11:58Z")

</div>

I'm not familiar with the enc\_ APIs.

But I think the easiest way is to use

&nbsp;&nbsp;rb\_funcall(some\_str, rb\_intern("encode") ...

Praveen wrote:

> **···**
>
> > Forgot to mention. I am on ruby version
> > 
> > ruby 1.9.1p0 (2009-01-30 revision 21907) [x86\_64-linux].
> > 
> > Let me know if you require any info
> > 
> > Thanks
> > 
> > Praveen
> 
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Praveen](https://avatars.discourse-cdn.com/v4/letter/p/3ec8ea/32.png) [@Praveen](https://rubytalk.org/u/Praveen)\
**Post date:** [22 February 2010 16:30 UTC](https://rubytalk.org/t/ruby-c-extensions-and-unicode/57341/9 "2010-02-22T16:30:07Z")

</div>

Thanks All for your help!!

Will Keep posted on how it goes.

Thanks

Praveen

---

<div class="post-metadata">

**Author:** ![Praveen](https://avatars.discourse-cdn.com/v4/letter/p/3ec8ea/32.png) [@Praveen](https://rubytalk.org/u/Praveen)\
**Post date:** [20 March 2010 12:40 UTC](https://rubytalk.org/t/ruby-c-extensions-and-unicode/57341/10 "2010-03-20T12:40:47Z")

</div>

Hi,

I wanted to know if there is any function in the C extension  
(Ruby-1.9) that can be used to convert the encoding of the string to  
the encoding format specified by the user (in his environment or by  
setting #encoding: at the beginning of .rb file).

I did find 2 function namely rb\_str\_export and rb\_str\_export\_locale.  
Not sure which one will convert the strings rightly to the format  
which the user is set.

Could somebody guide.

Thanks

Praveen

---

<div class="post-metadata">

**Author:** ![Brian\_Candler](https://avatars.discourse-cdn.com/v4/letter/b/5f9b8f/32.png) [@Brian\_Candler](https://rubytalk.org/u/Brian_Candler)\
**Post date:** [22 March 2010 13:41 UTC](https://rubytalk.org/t/ruby-c-extensions-and-unicode/57341/11 "2010-03-22T13:41:09Z")

</div>

Praveen wrote:

> I wanted to know if there is any function in the C extension  
> (Ruby-1.9) that can be used to convert the encoding of the string to  
> the encoding format specified by the user (in his environment or by  
> setting #encoding: at the beginning of .rb file).

Those are two different things.

The encoding guessed from the environment is Encoding.default\_external  
(or Encoding.find("external")). So you can do:

&nbsp;&nbsp;str2 = str1.encode("external")

The encoding specified in the #encoding line is called the source  
encoding, and it's the encoding which string literals like "abc"  
(usually) get automatically.

Maybe it would be helpful first to review the concepts in 'pure ruby',  
then map them to C. There are some details at:

> <https://github.com/candlerb/string19/blob/master/string19.rb>

[Gray Soft / Not Found](http://blog.grayproductions.net/articles/ruby_19s_string) (plus see other  
articles linked from the table of contents)

Warning: it's a large and complex topic.

> I did find 2 function namely rb\_str\_export and rb\_str\_export\_locale.  
> Not sure which one will convert the strings rightly to the format  
> which the user is set.

I suggest you start by calling the ruby-level functions, like  
String#encode. If there is a particular need to call the underlying C  
functions directly then you can look at the ruby source code for  
String#encode and see what it calls.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).
