Meaningless Drivel is fun!*
The moose likes Other JSE/JEE APIs and the fly likes Why isn't this char to jchar working? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Other JSE/JEE APIs
Bookmark "Why isn Watch "Why isn New topic
Author

Why isn't this char to jchar working?

Dan Bizman
Ranch Hand

Joined: Feb 25, 2003
Posts: 387
This really is an array/vector of chars, not a string (i.e. not a char* string).



It returns garble to Java instead of the characters put into the vector. What am I doing wrong?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi,

jchar is a 16-bit type, like Java char. By (effectively) copying an array of char into an array of jchar, you're packing two chars into one jchar for half the array, then ignoring the other half. You'd have to have an array of wchar_t to copy in this way.

I don't know what the best way to do this correctly is; I've never thought about this case before. You could do a loop of course and set one element at a time; you could allocate a twice-as-large buffer in C, "scatter" the chars into it, then use the above code. You could even create a Java String from your chars, ask *it* for the char array, and return that.


[Jess in Action][AskingGoodQuestions]
Dan Bizman
Ranch Hand

Joined: Feb 25, 2003
Posts: 387
Originally posted by Ernest Friedman-Hill:
Hi,

jchar is a 16-bit type, like Java char. By (effectively) copying an array of char into an array of jchar, you're packing two chars into one jchar for half the array, then ignoring the other half. You'd have to have an array of wchar_t to copy in this way.

I don't know what the best way to do this correctly is; I've never thought about this case before. You could do a loop of course and set one element at a time; you could allocate a twice-as-large buffer in C, "scatter" the chars into it, then use the above code. You could even create a Java String from your chars, ask *it* for the char array, and return that.


Thanks. Yeah, I ended up going with the last: creating a jstring and then getting it's characters as an array from the JNIEnv.
 
jQuery in Action, 2nd edition
 
subject: Why isn't this char to jchar working?