在 Python 的 SWIG 中包装 boost::shared_ptr 的 std::vector
编辑:解决了,我的错误;我的回答中解释了。
我有这个:
std::vector < boost::shared_ptr < Entity > > entities;
我尝试通过 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>
但是,在 Python 中实体最终成为一个元组:
import MyModule
print type(MyModule.cvar.entities)
# Output: (type 'tuple')
我已经在 Google 上搜索过这个,但找不到任何关于如何包装它的具体示例。一页给出了一个为 C# 包装它的小示例,但它对我的情况没有帮助。
非常感谢任何帮助。
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:
%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:
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. One page gave a small example for wrapping it for C#, but it didn't help in my case.
Any help is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我在将 Python 指针对象序列自动转换为指针对象的
std::vector
时遇到了一些困难。我目前(卡住)使用 Swig 1.3; YMMV,如果您使用的是 Swig 2。诀窍是在 Swig 接口文件(使用%template
)中实例化,不仅是向量,而且不仅仅是对象,还有指针对象:
myObjectPtrT
,Swig 似乎不太了解如何将指向myObjectT
的 Python 指针序列转换为myObjectVectorT
。更新:出于某种原因,我还没有弄清楚,这导致无法从)。
myObjectPtrT
调用myObjectT
上的方法,即使我已经还使用了 SWIG_SHARED_PTR(myObjectT, myObjectI had some difficulty getting a Python sequence of pointer objects to automatically convert into a
std::vector
of pointer objects. I am currently (stuck) using 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:Without the
myObjectPtrT
, Swig doesn't seem to know enough to convert a Python sequence of pointers tomyObjectT
to amyObjectVectorT
.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 amyObjectPtrT
, even though I've also usedSWIG_SHARED_PTR(myObjectT, myObject<T>)
.请参阅 如何公开 std::vector作为使用 SWIG 的 Python 列表? 可能是不错的信息
See How to expose std::vector<int> as a Python list using SWIG? for probably good info
SWIG 似乎将 std::vector 类型的全局变量包装到元组中。解决方案是将实体移入类中,并通过该类的实例访问它。例子:
SWIG seems to wrap global variables of type std::vector into tuples. The solution is to move entities into a class, and access it through an instance of that class. Example: