检测代码是否在 Python / Pybind 上下文中运行
我有一个用 C++ 编写的 Linux 共享库,可以从许多不同的地方(其他库、各种可执行文件等)调用它。
有时,通向我的库的调用链以 Python 开始(例如,Python 导入基于 Pybind 的模块“A”,该模块“A”调用库“B”,该模块调用库“C”,该库“C”调用我的库),有时没有 Python图中(例如,独立命令行可执行文件“D”调用库“E”,该库“E”调用我的库)。我的问题是:
- 我能以某种方式检测图片中是否有Python/Pybind吗? (理想情况下以非 hacky 的方式...例如,我正在考虑获取文本堆栈跟踪并寻找 Pybind 特定的函数名称,但我想避免这样的 hack)
- 我可以在不加载 Python 解释器的情况下执行此操作吗?
- 理想情况下,我可以在不将我的库链接到任何特定于 Python 的东西的情况下执行此操作吗?
I have a Linux shared library written in C++, that's called from many different places (other libraries, various executables, etc).
Sometimes the chain of calls that leads to my library starts in Python (e.g. Python imports Pybind-based module "A" that calls into library "B" that calls into library "C" that calls my library), and sometimes there is no Python in the picture (e.g. standalone command-line executable "D" calls into library "E" that calls into my library). My questions are:
- Can I somehow detect whether there's Python / Pybind in the picture? (Ideally in a non-hacky way... E.g. I was thinking of getting a textual stack trace and looking for Pybind-secific function names, but I'd like to avoid hacks like this)
- Can I do this without loading the Python interpreter?
- Ideally, can I do this without linking my library to anything Python-specific?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用对
dlsym
的调用来查看进程内部是否存在符号Py_Main
:显然,这也是愚蠢的 正在这样做。
You can look inside your process for the existence of the symbol
Py_Main
, using a call todlsym
:Apparently that's also how folly are doing it.