Created
April 10, 2013 05:40
-
-
Save nnemkin/5352088 to your computer and use it in GitHub Desktop.
Warning: untested code.
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
/* Extension's __file__ attribute is not initialized until after the init | |
function returns. To set submodules' __file__ at init time we will | |
have to retrieve it from the OS. */ | |
#if defined(_WIN32) | |
#include <Windows.h> | |
static PyObject *get_current_file() { | |
HMODULE hModule; | |
union { | |
CHAR nameA[MAX_PATH]; | |
WCHAR nameW[MAX_PATH]; | |
} buffer; | |
DWORD length; | |
/* NB: requires WinXP or later */ | |
GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, | |
(LPCTSTR)&get_current_file, | |
&hModule); | |
#if PY_VERSION_HEX < 0x03000000 | |
/* XXX: make sure it fails for paths not encodable with CP_ACP */ | |
length = GetModuleFileNameA(hModule, buffer.nameA, MAX_PATH); | |
if (length) | |
return PyString_FromStringAndSize(buffer.nameA, length); | |
#endif | |
length = GetModuleFileNameW(hModule, buffer.nameW, MAX_PATH); | |
if (length) | |
return PyUnicode_FromUnicode(buffer.nameW, length); | |
Py_RETURN_NONE; | |
} | |
#elif defined(LINUX) || defined(FREEBSD) || defined(DARWIN) || defined(__GNU__) || defined(__GLIBC__) | |
#include <dlfcn.h> | |
static PyObject *get_current_file() { | |
Dl_info info; | |
if (dladdr(&get_current_file, &info) && info.dli_fname) { | |
#if PY_VERSION_HEX < 0x03000000 | |
return PyString_FromString(info.dli_fname) | |
#else | |
return PyUnicode_DecodeFSDefault(info.dli_fname) | |
#endif | |
} | |
Py_RETURN_NONE; | |
} | |
#else | |
static PyObject *get_current_file() { Py_RETURN_NONE; } | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment