gpt4 book ai didi

c++ - 使用 Boost.Python 公开带有 unsigned char 和参数的方法

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

我有闭源 C++ 库,它提供的头文件的代码等效于:

class CSomething
{
public:
void getParams( unsigned char & u8OutParamOne,
unsigned char & u8OutParamTwo ) const;
private:
unsigned char u8OutParamOne_,
unsigned char u8OutParamTwo_,
};

我试图将它暴露给 Python,我的包装器代码是这样的:

BOOST_PYTHON_MODULE(MySomething)
{
class_<CSomething>("CSomething", init<>())
.def("getParams", &CSomething::getParams,(args("one", "two")))

}

现在我正尝试在 Python 中使用它,但失败得很惨:

one, two = 0, 0
CSomething.getParams(one, two)

结果是:

ArgumentError: Python argument types in
CSomething.getParams(CSomething, int, int)
did not match C++ signature:
getParams(CSomething {lvalue}, unsigned char {lvalue} one, unsigned char {lvalue} two)

我需要在 Boost.Python 包装器代码或 Python 代码中更改什么才能使其工作?我如何添加一些 Boost.Python 魔法来自动将 PyInt 转换为 unsigned char ,反之亦然?

最佳答案

Boost.Python 提示缺少 lvalue 参数,这个概念在 Python 中不存在:

def f(x):
x = 1

y = 2
f(y)
print(y) # Prints 2

f 函数的x 参数不是类 C++ 的引用。在 C++ 中,输出不同:

void f(int &x) {
x = 1;
}

void main() {
int y = 2;
f(y);
cout << y << endl; // Prints 1.
}

这里有几个选择:

a) 包装 CSomething.getParams 函数以返回新参数值的元组:

one, two = 0, 0
one, two = CSomething.getParams(one, two)
print(one, two)

b) 包装 CSomething.getParams 函数以接受类实例作为参数:

class GPParameter:
def __init__(self, one, two):
self.one = one
self.two = two

p = GPParameter(0, 0)
CSomething.getParams(p)
print(p.one, p.two)

关于c++ - 使用 Boost.Python 公开带有 unsigned char 和参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12916877/

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