I am trying to wrap a class which returns a string.
class SS {
public:
SS(const std::string& s) : data_(s.data()), size_(s.size()) {}
// Return a pointer to the beginning of the referenced data
const char* data() const { return data_; }
const char* data_;
size_t size_;
};
class PySS: public SS {
public:
PySS(const std::string &str): SS(str) {
std::cout << "cons " << str << std::endl; #key1
std::cout << "data " << SS::data() << std::endl; # key1
}
std::string data() {
std::cout << "call data " << SS::data() << std::endl; # p��
return std::string(SS::data());
}
};
void init_slice(py::module & m) {
py::class_<PySS>(m, "SS")
.def(py::init<const std::string&>())
.def("data", &PySS::data);
}
When calling from python,
s = SS('key1')
print (s.data())
it throws unicode error
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xae in position 1: invalid start byte
I print the string in the constructor, and it shows the identical result. But in the other function it shows some uninterpreted string.
any idea?
[Edit]
Here is the minimal example to reproduce the similar issue.
class SS {
public:
SS(const std::string& s) : data_(s.data()) {}
// Return a pointer to the beginning of the referenced data
const char* data() const { return data_; }
const std::string ToString() const {
std::cout << std::string(data_) << std::endl;
return std::string(data_);
}
const char* data_;
};
void init_slice(py::module & m) {
py::class_<SS>(m, "Slice")
.def(py::init<const std::string&>())
.def("data", &SS::ToString);
}