如何在 Boost python 中包装 init/cleanup 函数
我最近发现了 boost-python 的存在,并对其明显的简单性感到惊讶。我想尝试一下,并开始包装现有的 C++ 库。
虽然包装基本库 API 调用非常简单(没什么特别的,只是常规函数调用和非常常见的参数),但我不知道如何正确包装初始化/清理函数:
就目前情况而言,我的 C++ 库要求调用者首先在程序启动时调用 mylib::initialize()
,并在程序结束前调用 mylib::cleanup()
(实际上还有一个初始化对象负责照顾的,但这可能是无关紧要的)。
我应该如何使用 boost python 包装它?
强制 Python 用户调用 mymodule.initialize() 和 mymodule.cleanup() 似乎不太 Pythonic。有没有办法以自动的方式做到这一点?理想情况下,对 initialize()
的调用将在导入模块时透明地完成,并且对 cleanup()
的调用也会在 python 脚本结束时完成。
有什么办法可以做到这一点吗?如果不是,最优雅的解决方案是什么?
谢谢。
I recently discovered the existence of boost-python and was astonished by it's apparent simplicity. I wanted to give it a try and started to wrap an existing C++ library.
While wrapping the basic library API calls is quite simple (nothing special, just regular function calls and very common parameters), I don't know how to properly wrap the initialization/cleanup functions:
As it stands, my C++ library requires the caller to first call mylib::initialize()
when the program starts, and to call mylib::cleanup()
before it ends (actually there is also an initializer object that takes care of that, but it is probably irrelevant).
How should I wrap this using boost python ?
Forcing a Python user to call mymodule.initialize()
and mymodule.cleanup()
seems not very pythonic. Is there any way to that in an automatic fashion ? Ideally, the call to initialize()
would be done transparently when the module is imported and the call to cleanup()
also done when the python script ends.
Is there any way to do that ? If not, what is the most elegant solution ?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试创建一个防护对象并将其分配给模块的隐藏属性。
You could try to do a guard object and assign it to a hidden attribute of your module.