boost.python将char*的参数转换为python以调用c++中的python函数

The argument of char* converted to python to call a python function in C++ by boost.python

本文关键字:python 调用 c++ 中的 函数 参数 char boost 转换      更新时间:2023-10-16

我通过boost.python调用c++中的python函数。并将char*参数传递给python函数。但是有一个错误。TypeError:找不到c++类型:char. to_python(按值)转换器

代码如下: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)

使用const char*,特别是在使用字符串字面值时:

char* bad = "Foo"; // wrong!
bad[0] = 'f'; // undefined behavior!

正确的:

const char* s = "Foo"; // correct
obj(s); // automatically converted to python string

也可以使用:

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定义了const char*, std::stringchar的字符串转换器,以及Python3的std::wstring。为了选择合适的转换器,boost尝试通过专门的模板(为内置类型定义)匹配类型,如果没有合适的模板,则默认使用转换器注册表查找。由于char*const char*不匹配,因此没有注册char*的转换器,转换失败

如果你有一个合适的char*,在传递给python之前将其转换为const char*:

char* p = new char[4];
memcpy(p,"Foo",4); // include terminating ''
obj( const_cast<const char*>(p) );
delete [] p;