2016-11-14 8 views
2

Я хотел бы создать строку C++ в функции nogil в файле, который будет cimported через pxd. Если я определяю, строка output = "" или строка output = string ("blah"), это использует интерпретатор python. Есть ли способ определить строку, так что компилятор записывает в файл Cython CPP:cython create string with 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', т.е. байт объект.

EDIT: Вот сгенерированный 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; 

, который выглядит лучше.

 Смежные вопросы

  • Нет связанных вопросов^_^