[英]The argument of char* converted to python to call a python function in C++ by boost.python
I call a python function in c++ by boost.python. 我通过boost.python在c ++中调用python函数。 And pass a argument of char* to the python function.But there was a error.
并将char *参数传递给python函数,但是出现错误。 TypeError: NO to_python (by-value) converter found for c++ type: char.
TypeError:找不到C ++类型为char的to_python(按值)转换器。
The following is code: C++ 以下是代码: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)
Use const char*
, especially when using string literals: 使用
const char*
,尤其是在使用字符串文字时:
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. boost::python
为const char*
, std::string
和char
以及std::wstring
为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. 为了选择合适的转换器,boost尝试通过专用模板(为内置类型定义)匹配类型,如果没有合适的选项,默认情况下默认使用转换器注册表查找。 Since
char*
does not match const char*
, an no converter for char*
is registered, the conversion fails. 由于
char*
与const char*
不匹配,因此未注册char*
转换器,因此转换失败。
If you have a proper char*
, cast it to a const char*
before passing it to python: 如果您有合适的
char*
,请将其转换为const char*
然后再传递给python:
char* p = new char[4];
memcpy(p,"Foo",4); // include terminating '\0'
obj( const_cast<const char*>(p) );
delete [] p;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.