[英]Wrapping std::vector of boost::shared_ptr in SWIG for Python
EDIT: Solved, my mistake; 编辑:解决了,我的错误; explained in my answer. 在我的回答中解释。
I have this: 我有这个:
std::vector < boost::shared_ptr < Entity > > entities;
and I try to expose it through SWIG like this: 我尝试通过SWIG公开它,如下所示:
%include "boost_shared_ptr.i"
%include "std_vector.i"
%shared_ptr(Entity)
%include <Entity.h>
namespace std {
%template(EntityVector) vector<boost::shared_ptr<Entity> >;
};
%include <TheFileWithEntities.h>
However, in Python entities ends up being a tuple: 但是,在Python中,实体最终成为一个元组:
import MyModule
print type(MyModule.cvar.entities)
# Output: (type 'tuple')
I've Googled for this, but could not find any concrete examples on how to wrap this. 我已经用Google搜索了,但是找不到任何关于如何包装它的具体例子。 One page gave a small example for wrapping it for C#, but it didn't help in my case. 一个页面给出了一个包装C#的小例子,但在我的情况下它并没有帮助。
Any help is greatly appreciated. 任何帮助是极大的赞赏。
I had some difficulty getting a Python sequence of pointer objects to automatically convert into a std::vector
of pointer objects. 我在获取指针对象的Python序列时遇到了一些困难,无法自动转换为指针对象的std::vector
。 I am currently (stuck) using Swig 1.3; 我目前(卡住)使用Swig 1.3; YMMV if you're using Swig 2. The trick was to instantiate in the Swig interface file (with %template
) not just the vector, and not just the object, but the pointer objects also: YMMV如果你正在使用Swig 2.诀窍是在Swig接口文件(带有%template
)中实例化,而不仅仅是向量,而不仅仅是对象,还有指针对象:
%include "std_vector.i"
%template(myObjectT) namespace::of::myObject<T>;
%template(myObjectPtrT) boost::shared_ptr<namespace::of::myObject<T> >;
%template(myObjectVectorT) std::vector<boost::shared_ptr<namespace::of::myObject<T> > >;
Without the myObjectPtrT
, Swig doesn't seem to know enough to convert a Python sequence of pointers to myObjectT
to a myObjectVectorT
. 如果没有myObjectPtrT
,Swig似乎不太了解将指向myObjectT
的Python指针序列转换为myObjectVectorT
。
UPDATE: For some reason I haven't yet been able to figure out, this leads to not being able to call methods on myObjectT
from a myObjectPtrT
, even though I've also used SWIG_SHARED_PTR(myObjectT, myObject<T>)
. 更新:由于某种原因,我还没有弄明白,这导致无法从myObjectPtrT
调用myObjectT
方法,即使我也使用了SWIG_SHARED_PTR(myObjectT, myObject<T>)
。
See How to expose std::vector<int> as a Python list using SWIG? 请参见如何使用SWIG将std :: vector <int>公开为Python列表? for probably good info 可能是好消息
SWIG seems to wrap global variables of type std::vector into tuples. SWIG似乎将std :: vector类型的全局变量包装成元组。 The solution is to move entities into a class, and access it through an instance of that class. 解决方案是将实体移动到类中,并通过该类的实例访问它。 Example: 例:
class Globals
{
public:
std::vector < boost::shared_ptr < Entity > > entities;
};
extern Globals globals;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.