0

I'm trying to allocate a Java char array from Jython which will be populated by a Java library. I want to do the equivalent to from Jython:

char[] charBuffer = new char[charCount];

I've read the documentation for the array and jarray modules (I think they're the same) but I'm not entirely sure which type code I want to use. The two document's seem slightly contradictory, but the newer array module seems more correct. According to the Java documentation, a char is a "16-bit Unicode character" (2 bytes).

So if I check the following type codes:

>>> array.array('c').itemsize # C char, Python character
1
>>> array.array('b').itemsize # C signed char, Python int
1
>>> array.array('B').itemsize # C unsigned char, Python int
2
>>> array.array('u').itemsize # C Py_UNICODE, Python unicode character
4
>>> array.array('h').itemsize # C signed short, Python int
2
>>> array.array('H').itemsize # C unsigned short Python int
4

It seems odd to me that the size of B and H are twice the size of their signed counterparts b and h. Can I safely and reliably use the 16-bit B (unsigned char) or h (signed short int) for a Java char? Or, if using the array module for this is completely wrong for this, please let me know.

1 Answer 1

1

The short answer is: use 'c'

Under the hood, jython is doing the work of converting data types for you.

You can verify with some tests. There is a class java.nio.CharBuffer with a method wrap() that takes a char[] array. Observe that jython array type 'c' works, while everything else fails:

>>> import array
>>> from java.nio import CharBuffer

>>> array.array('c', 'Hello World')
array('c', 'Hello World')
>>> CharBuffer.wrap( array.array('c', 'Hello World') )
Hello World

>>> array.array('b','Hello World')
array('b', [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100])
>>> CharBuffer.wrap( array.array('b', 'Hello World') )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: wrap(): 1st arg can't be coerced to char[], java.lang.CharSequence

>>> array.array('u', u'Hello World') 
array('u', u'Hello World')
>>> CharBuffer.wrap( array.array('u', u'Hello World') )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: wrap(): 1st arg can't be coerced to char[], java.lang.CharSequence
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.