gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:01:13 26 4
gpt4 key购买 nike

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

代码如下: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::pythonconst 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 '\0'
obj( const_cast<const char*>(p) );
delete [] p;

关于python - char* 的参数转换为 python 以通过 boost.python 在 C++ 中调用 python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14029351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com