Eugene Osovetsky
Eugene Osovetsky

Reputation: 6541

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:

Upvotes: 1

Views: 190

Answers (1)

unddoch
unddoch

Reputation: 6004

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.

Upvotes: 1

Related Questions