如何通过 Swig 创建 Python 类的别名?
我创建了一个 C++ 库,并成功使用 swig 使其可以通过 python 访问。模板在库中被大量使用,每个模板类型都通过 swig 映射到自己的 python 类,如下所示:
%template(Imageint) Image<int>;
%template(Imagedouble) Image<double>;
但是,我真的很希望有一个由 python 使用的“默认”模板,以便
a = Image("filename")
实例化 Image
a = Imagedouble("filename")
Swig 文档说明:
%template 指令不应该是 用于包装同一个模板 实例化不止一次 范围相同。这将生成一个 错误。这个错误是因为 模板扩展结果为两个 具有相同名称的相同类。 这会生成一个符号表 冲突。除此之外,大概还有更多 有效地仅包装特定的 仅实例化一次,以便 减少代码膨胀的可能性。
所以为了避免符号表冲突,我
%rename(Image) Image<double>;
%template(Imageint) Image<int>;
%template(Imagedouble) Image<double>;
在接口文件中进行了尝试。然而,swig 随后抱怨 Image 被重新定义。
创建别名以使 Image 和 Imagedouble 都引用 C++ Image
的最佳方法是什么?非常感谢您提供的任何帮助。
-乔什
I've created a C++ library and have successfully used swig to make it accessible through python. Templating is used heavily in the library and each template type is mapped to its own python class by swig like so:
%template(Imageint) Image<int>;
%template(Imagedouble) Image<double>;
However, I would really like to have a 'default' template used by python such that
a = Image("filename")
instantiates Image<double>
without having to always type
a = Imagedouble("filename")
Swig documentation states:
The %template directive should not be
used to wrap the same template
instantiation more than once in the
same scope. This will generate an
error. This error is caused because
the template expansion results in two
identical classes with the same name.
This generates a symbol table
conflict. Besides, it probably more
efficient to only wrap a specific
instantiation only once in order to
reduce the potential for code bloat.
So to avoid the symbol table conflict, I tried
%rename(Image) Image<double>;
%template(Imageint) Image<int>;
%template(Imagedouble) Image<double>;
in the interface file. However, swig then complains about Image being redefined.
What is the best way to make an alias such that Image and Imagedouble both refer to C++ Image<double>
? Thank you very much for any help you can provide.
-Josh
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果这对将来的人有帮助,执行上述操作的方法是将以下内容添加到接口文件中:
我没有意识到有一种方法可以在接口文件中编写标准 python 代码。
In case this helps someone in the future, the way to do what is describe above is to add the following to the interface file:
I did not realize there was a way to write standard python code in the interface file.