Skip to content

Instantly share code, notes, and snippets.

@justinfx
Last active January 31, 2019 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinfx/8023d341becc8a1092e5beacd7a249eb to your computer and use it in GitHub Desktop.
Save justinfx/8023d341becc8a1092e5beacd7a249eb to your computer and use it in GitHub Desktop.
cython: test converting py2/3 string objects to C++ std::string
#include "libtest.hh"
std::string copy_string(std::string &s) {
std::string s2 = s;
return s2;
}
#ifndef LIBCYTEST_H
#define LIBCYTEST_H
#include <string>
std::string copy_string(std::string &s);
#endif // LIBCYTEST_H
from libcpp.string cimport string
cdef extern from "libtest.hh":
string copy_string(string &s)
# cython: c_string_type=unicode, c_string_encoding=utf8
cimport libtest
def test(s):
return libtest.copy_string(s)
"""
python -c "import test; print (test.test('foo'))"
Python2:
foo
Python3:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "test.pyx", line 6, in test.test
File "stringsource", line 15, in string.from_py.__pyx_convert_string_from_py_std__in_string
TypeError: expected bytes, str found
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment