cython用nogil创建字符串

时间:2016-11-14 19:05:10

标签: c++ cython

我想在一个文件中的nogil函数中创建一个c ++字符串,该文件将通过pxd进行处理。如果我定义,字符串输出=""或者string output = string(" blah"),这使用python解释器。有没有办法定义一个字符串,以便编译器在cython cpp文件中写入:

std::string val = "blah";

基本上有这个:

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

1 个答案:

答案 0 :(得分: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;

看起来更好。

相关问题