问题
I call a python function in c++ by boost.python. And pass a argument of char* to the python function.But there was a error. TypeError: NO to_python (by-value) converter found for c++ type: char.
The following is code: C++
#include <boost/python.hpp>
#include <boost/module.hpp>
#include <boost/def.hpp>
using namespace boost::python;
void foo(object obj) {
char *aa="1234abcd";
obj(aa);
}
BOOST_PYTHON_MODULE(ctopy)
{
def("foo",foo);
}
python
import ctopy
def test(data)
print data
t1=ctopy.foo(test)
回答1:
Use const char*
, especially when using string literals:
char* bad = "Foo"; // wrong!
bad[0] = 'f'; // undefined behavior!
Correct:
const char* s = "Foo"; // correct
obj(s); // automatically converted to python string
Alternatively you can use:
std::string s = "Bar"; // ok: std::string
obj(s); // automatically converted to python string
obj("Baz"); // ok: it's actually a const char*
char c = 'X'; // ok, single character
obj(c); // automatically converted to python string
signed char d = 42; // careful!
obj(d); // converted to integer (same for unsigned char)
boost::python
defines string converters for const char*
, std::string
and char
as well as std::wstring
for Python3.
To select a proper converter, boost is trying to match the type through specialized templates (defined for built-in types) which defaults to a converter registry lookup if nothing fits. Since char*
does not match const char*
, an no converter for char*
is registered,
the conversion fails.
If you have a proper char*
, cast it to a const char*
before passing it to python:
char* p = new char[4];
memcpy(p,"Foo",4); // include terminating '\0'
obj( const_cast<const char*>(p) );
delete [] p;
来源:https://stackoverflow.com/questions/14029351/the-argument-of-char-converted-to-python-to-call-a-python-function-in-c-by-bo