boost.python将char*的参数转换为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);
}
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::string
和char
的字符串转换器,以及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;
相关文章:
- 从python调用openMP共享库时,未定义opnMP函数
- 使用JsonCpp将数据返回到带有pybind11的python会在python调用中产生Symbol not foun
- 为什么我无法打开/读取从 Python 调用的 C 扩展名中的 txt 文件?
- 从 Python 调用 c++ 文件
- 如何为从 Python 调用C++启动 GDB?
- 从python调用C++函数,使用cython,使用cythonize
- 为什么在 2019 年我们仍然不能使用 ctypes 从 Python 调用C++?
- 如何使用 python 调用 c++ 函数
- 从 Python 调用 Windows DLL 函数时出错
- 如何从 Python 调用 MPI .so 文件
- 我如何有boost.python调用一个函数来处理对象
- 从Python调用的C++dll
- 通过嵌入式 Python 调用C++代码
- 从 Python 调用 cpp 函数时出现分段错误
- 从Python调用C++64位共享库
- 使用ctypes从Python调用C++方法不起作用
- Boost python,在嵌入时从python调用c ++函数
- 从 Python 调用 C++ opencv 函数(发送一个 cv :: mat 到 C++ 使用 opencv 的 d
- 从 Python 调用自定义C++ dll
- 如何使用Python调用C++代码