Created
September 5, 2025 07:13
-
-
Save aont/8b5bca3f59086d28db590f2d882777ed to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // g++ $(python3-config --embed --libs --ldflags --cflags ) main.cpp | |
| #include <Python.h> | |
| #include <string> | |
| int main(void) { | |
| PyStatus st; | |
| PyConfig cfg; | |
| PyConfig_InitPythonConfig(&cfg); // normal mode using env vars | |
| const char *ve = getenv("VIRTUAL_ENV"); | |
| if (ve && *ve) { | |
| char exe[4096]; | |
| snprintf(exe, sizeof(exe), "%s" | |
| #ifdef _WIN32 | |
| "\\Scripts\\python.exe" | |
| #else | |
| "/bin/python3" | |
| #endif | |
| , ve); | |
| wchar_t *wexe = Py_DecodeLocale(exe, NULL); | |
| if (!wexe) return 1; | |
| PyConfig_SetString(&cfg, &cfg.program_name, wexe); | |
| PyConfig_SetString(&cfg, &cfg.executable, wexe); | |
| PyMem_RawFree(wexe); | |
| cfg.site_import = 1; | |
| } | |
| st = Py_InitializeFromConfig(&cfg); | |
| PyConfig_Clear(&cfg); | |
| if (PyStatus_Exception(st)) { | |
| Py_ExitStatusException(st); | |
| } | |
| // begin user code | |
| const char *py_code = | |
| "def get_pi():\n" | |
| " import math\n" | |
| " return math.pi\n"; | |
| if (PyRun_SimpleString(py_code) != 0) { | |
| fprintf(stderr, "Failed to run embedded python code\n"); | |
| if (PyErr_Occurred()) PyErr_Print(); | |
| Py_Finalize(); | |
| return 1; | |
| } | |
| PyObject *main_mod = PyImport_AddModule("__main__"); // borrowed reference | |
| if (!main_mod) { | |
| fprintf(stderr, "Cannot get __main__ module\n"); | |
| if (PyErr_Occurred()) PyErr_Print(); | |
| Py_Finalize(); | |
| return 1; | |
| } | |
| PyObject *func = PyObject_GetAttrString(main_mod, "get_pi"); | |
| if (!func || !PyCallable_Check(func)) { | |
| fprintf(stderr, "get_pi is not found or not callable\n"); | |
| if (PyErr_Occurred()) PyErr_Print(); | |
| Py_XDECREF(func); | |
| Py_Finalize(); | |
| return 1; | |
| } | |
| PyObject *result = PyObject_CallObject(func, NULL); | |
| Py_DECREF(func); | |
| if (!result) { | |
| fprintf(stderr, "call to get_pi() failed\n"); | |
| if (PyErr_Occurred()) PyErr_Print(); | |
| Py_Finalize(); | |
| return 1; | |
| } | |
| double pi_val = PyFloat_AsDouble(result); | |
| if (PyErr_Occurred()) { | |
| fprintf(stderr, "Failed to convert result to double\n"); | |
| PyErr_Print(); | |
| Py_DECREF(result); | |
| Py_Finalize(); | |
| return 1; | |
| } | |
| printf("pi = %.15g\n", pi_val); | |
| Py_DECREF(result); | |
| // end user code | |
| Py_Finalize(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment