简体   繁体   中英

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. And pass a argument of char* to the python function.But there was a error. TypeError: NO to_python (by-value) converter found for c++ type: char.

The following is code: 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:

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. 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. Since char* does not match const char* , an no converter for char* is registered, the conversion fails.

If you have a proper char* , cast it to a const char* before passing it to python:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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