This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
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: 24183
    
  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.
 
 
subject: Why isn't this char to jchar working?