2016-11-14 37 views
2

我想在一個文件中的nogil函數中創建一個C++字符串,該文件將通過pxd進行輸入。如果我定義,字符串輸出=「」或字符串輸出=字符串(「blah」),這使用python解釋器。有沒有一種方法來定義字符串,這樣編譯器在用Cython CPP文件中寫道:cython用nogil創建字符串

std::string val = "blah"; 

基本上有這樣的:

from libcpp.string cimport string 
cdef string my_func() nogil: 
    cdef: 
     string output = "blah" 
    .... 
    return output 

回答

2
%%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; 

看起來更好。