Boost::在python中的类的对象上填充指针的C++向量

Boost::filling a C++ vector of pointer on object of a class in python

本文关键字:指针 填充 C++ 向量 python Boost 对象      更新时间:2023-10-16

这是我的问题。我应该让python代码能够在一类C++代码的对象上填充指针的C++向量。我正在使用Boost::Python。它看起来如下:

C++代码:

class A_Base {}
class A_derived_1 {}
...
class A_derived_N {}
class B {
...
setAderivediList(vector<A *> &_AderivedList){}
}

我需要在Python中做什么:

B.setAderivediList(_AderivedList)

我不能修改C++代码中的方法,我只能在#ifdef-python_interface之间添加其他对象,以免影响其他开发人员的工作。起初,我试图根据我在互联网上找到的内容编写一个转换器,但我没能使它适用于我的代码。然后我尝试在类B中添加一个_AderivedList和一个填充向量的setter。虽然它是用C++编译的,但在Python中不起作用。

新的B类:

class B {
...
setAderivediList(vector<A *> &_AderivedList){}
#ifdef myPython_code
public:
  vector<A *> * _AderivedListPy;
  setAListPy(A * &my_Aderived){       //Actually, I tried without the reference as well
  this->_AderivedListPy->push_back(my_Aderived);
};
#endif
}

在python中,它变成了:

myB = mydll.B()
Ai = mydll.A_derived_i()
myB.setAListPy(Ai) #stopping here
myB.setAderivediList(myB._AderivedListPy)

如果我使用引用,它会在myB.setAListPy(Ai)处抛出一条"python参数类型与C++签名不匹配"的错误消息,如果没有引用,它将在同一行停止,不会抛出任何错误消息。有什么线索可以告诉我如何改进这一点或其他方法吗?提前谢谢。

实际上,我找到了解决问题的方法。通过直接在setAListPy中填充向量(包括调用setAdrivediList)。我只是将一个int my_A_dederived传递给setAListPy(实际上,还有所有A_derived类构造函数所需的其他arg),并在my_A_deDerived上使用if条件。