指针参数传递给Boost.Python

5 投票
1 回答
2152 浏览
提问于 2025-04-15 20:02

怎么才能让一个带指针参数的函数在Boost Python中正常工作呢?我在文档里看到有很多关于返回值的可能性,但我不知道怎么处理参数。

void Tesuto::testp(std::string* s)
{
    if (!s)
        cout << " NULL s" << endl;
    else
        cout << s << endl;
}

>>> t.testp(None)
 NULL s
>>>       
>>> s='test'
>>> t.testp(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
    Tesuto.testp(Tesuto, str)
did not match C++ signature:
    testp(Tesuto {lvalue}, std::string*)
>>>                        

1 个回答

4

根据我查找的信息,Python 默认是不支持指针参数类型的。如果你真的想要实现这个功能,可能需要手动修改 Python 解释器,但这听起来像是生产环境中的代码,所以这样做可能不太现实。

补充说明:你可以添加一个包装函数,像这样:

 
std::string * pointer (std::string& p)
{
    return &p
}

然后用以下方式调用你的代码:


>>> s = 'hello'
>>> t.testp (pointer (s))
hello
>>>

撰写回答