I am try开发者_如何学JAVAing to make a C extension for Ruby that includes a method returning a string, which will sometimes have character values that need to be in an unsigned char
. In http://github.com/shyouhei/ruby/blob/trunk/README.EXT, all of the functions listed for turning C strings into Ruby strings take signed chars. So I couldn't do this:
unsigned char bytes[] = {0xf0, 0xf1, 0xf2};
return rb_str_new(bytes, 3);
How could I make a method that returns these types of strings? In other words, how would I make a C extension with a method returning "\xff"
?
I figured out that ruby will treat negative chars as their unsigned equivalent when using rb_str_new
. So, you can just cast the array of bytes to a char *
.
unsigned char bytes[] = {0xf0, 0xf1, 0xf2};
return rb_str_new((char *)bytes, 3);
精彩评论