Problem with casting string to/from char*is that in utf8, some characters are actually two-byte sized.
That's why glib has a specialized API for dealing with utf8, like the function g_utf8_find_next_char. On Wed, Dec 29, 2010 at 5:59 PM, Anatol Pomozov <[email protected]> wrote: > On Wed, Dec 29, 2010 at 3:51 PM, Anatol Pomozov > <[email protected]> wrote: >> Hi >> >> On Thu, Dec 23, 2010 at 12:37 AM, Anatol Pomozov >> <[email protected]> wrote: >>> Hi, >>> >>> I manipulate with strings in my application such as storing/reading >>> to/from binary files. And I need to convert a string to/from array of >>> bytes. What is the best way of doing it in Vala? >>> >>> Looking into string class http://valadoc.org/glib-2.0/string.html I >>> see a method called string#to_utf8() that converts string to array of >>> chars. But I cannot find any other methods. >>> >>> So I have 2 questions: >>> - How to convert a string to array of chars in encoding different >>> from UTF8. Something like this one >>> http://download.oracle.com/javase/6/docs/api/java/lang/String.html#getBytes(java.nio.charset.Charset) >>> - How to convert array of chars/uint8 back to string? Like this one >>> http://download.oracle.com/javase/6/docs/api/java/lang/String.html#String(byte[], >>> java.nio.charset.Charset) >> >> I think I found a way to convert string to bytes in Vala. Actually it >> is as simple as casting string to char* and back. Under the hood >> strings in vala is just a pointer to char. >> >> Here is an example that shows it: >> >> string hello = "abcd"; >> char* ch = (char*) hello; >> stdout.printf("%c\n", ch[1]); // Second char, that is 'b' > > It actually produces an interesting effect. You *can* change content > of a string (that are claimed as immutable) > > string hello = "abcd"; > char* ch = (char*) hello; > ch[0] = 'z'; > stdout.printf(hello); // Prints 'zbcd' > > PS Casting string to/from char* is an interesting technique and worth > mention about it in the tutorial. > _______________________________________________ > vala-list mailing list > [email protected] > http://mail.gnome.org/mailman/listinfo/vala-list > _______________________________________________ vala-list mailing list [email protected] http://mail.gnome.org/mailman/listinfo/vala-list
