Note that there are some explanatory texts on larger screens.

plurals
  1. POCython - convert wide string (wchar_t *) to Python 3 unicode object
    text
    copied!<p>I'm wrapping a C library to Pyhon 3 using Cython and i'm looking for a way of converting wchar_t string to python object which i want to return from a function. There's an answer in <a href="https://stackoverflow.com/questions/12778832/how-to-wrap-a-c-function-whose-parameter-is-wchar-t-pointer-with-cython">this question</a>, but it involves encoding the string as multibyte str, and decoding it back to unicode. I hope for more straightforward solution. I tried using <a href="http://docs.python.org/3.3/c-api/unicode.html#PyUnicode_FromWideChar" rel="nofollow noreferrer">PyUnicode_FromWideChar</a> from Python C API, but i'm getting a segfault. Here's my .pyx code:</p> <pre><code>from cpython.ref cimport PyObject from libc.stddef cimport wchar_t cdef extern from "Python.h": PyObject* PyUnicode_FromWideChar(wchar_t *w, Py_ssize_t size) cdef extern from "../../src/my_c_lib.h": wchar_t * myObjToStr(wchar_t * result, size_t size, myObj * obj) cdef class MyClass: cdef myObj * ptr ... def to_str(self): cdef wchar_t buf[64] cdef wchar_t * result = myObjToStr(buf, 64, self.ptr) if result is NULL: raise Exception("Error converting object to string.") cdef PyObject * pystr = PyUnicode_FromWideChar(result, 64) return &lt;object&gt;pystr </code></pre> <p><code>result</code> is actually the pointer to <code>buf</code>. What's wrong with this? Is there another way without encoding/decoding?</p> <p>Edit: I found that <code>PyUnicode_FromWideChar()</code> returns NULL, but why? I checked, that <code>result</code> is a valid wchar_t * string.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload