%%cython -a
#distutils: language = c++
from libcpp.string cimport string
cdef string my_func() nogil:
cdef:
char* c_str = 'blah'
string output = <string>(c_str)
return output
def py_call():
return my_func()
然後調用py_call()
給b'blah'
,即一個字節目的。
編輯:下面是生成的C++代碼:
+08: char* c_str = 'blah'
__pyx_v_c_str = ((char *)"blah");
+09: string output = <string>(c_str)
__pyx_v_output = ((std::string)__pyx_v_c_str);
所以它的字面蒙上char*
到std::string
。
一種替代方法是然後從char*
調用構造函數:
cdef:
char* c_str = 'blah'
string output = string(c_str)
產生
+08: char* c_str = 'blah'
__pyx_v_c_str = ((char *)"blah");
+09: string output = string(c_str, 4)
try {
__pyx_t_1 = std::string(__pyx_v_c_str, 4);
} catch(...) {
#ifdef WITH_THREAD
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();
#endif
__Pyx_CppExn2PyErr();
#ifdef WITH_THREAD
PyGILState_Release(__pyx_gilstate_save);
#endif
__PYX_ERR(0, 9, __pyx_L1_error)
}
__pyx_v_output = __pyx_t_1;
看起來更好。