繁体   English   中英

char *的参数通过boost.python转换为python以在C ++中调用python函数

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

我通过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);
}

蟒蛇

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

如果您有合适的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM