簡體   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