There is some code in Pyjnius that uses a Java string value converted from a Python string value. Unfortunately, the newly converted string is not live anymore, and has been causing me some headaches as the value would sometimes disappear in Java land.
Here is the patch:
--- jnius_conversion.pxi.orig 2014-05-22 08:54:51.000000000 -0700
+++ jnius_conversion.pxi 2014-06-24 18:36:55.000000000 -0700
@@ -50,8 +50,9 @@
j_args[index].l = NULL
elif isinstance(py_arg, basestring) and \
argtype in ('Ljava/lang/String;', 'Ljava/lang/Object;'):
+ py_arg_utf8 = <bytes>py_arg.encode('utf-8')
j_args[index].l = j_env[0].NewStringUTF(
- j_env, <char *><bytes>py_arg.encode('utf-8'))
+ j_env, <char *>py_arg_utf8)
elif isinstance(py_arg, JavaClass):
jc = py_arg
check_assignable_from(j_env, jc, argtype[1:-1])
Note the following from the Cython documentation:
To convert the byte string back into a C char*, use the opposite assignment:
cdef char* other_c_string = py_string
This is a very fast operation after which other_c_string points to the byte string buffer of the Python string itself. It is tied to the life time of the Python string. When the Python string is garbage collected, the pointer becomes invalid. It is therefore important to keep a reference to the Python string as long as the char* is in use. Often enough, this only spans the call to a C function that receives the pointer as parameter. Special care must be taken, however, when the C function stores the pointer for later use. Apart from keeping a Python reference to the string object, no manual memory management is required.
Ron