'Detect whether code is running in a Python / Pybind context

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?


Solution 1:[1]

You can look inside your process for the existence of the symbol Py_Main, using a call to dlsym:

#include <dlfcn.h>

bool is_inside_python() {
  return dlsym(RTLD_DEFAULT, "Py_Main") != nullptr;
}

Apparently that's also how folly are doing it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1