使用unsigned char& amp;使用Boost.Python的参数

时间:2012-10-16 14:24:03

标签: c++ python boost-python

我是一个闭源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,反之亦然?

1 个答案:

答案 0 :(得分:1)

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

def f(x):
  x = 1

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

x函数的f参数不是类似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)