Question

My question is going to use examples from Python, but it seems like this could be a general question.

I've been using load-time dynamic linking, but for various reasons (it's recommended in the link below) I'd like to dynamically load the Python library:

HINSTANCE hModPython = LoadLibrary(_T("Python27.dll"));

I'm able to load Py_Initialize and other functions from the DLL, but it's a dirty process:

int (*pPy_Initialize)(void);
pPy_Initialize = (int (*)(void))GetProcAddress(hModPython, "Py_Initialize");
pPy_Initialize();

In this conversation it's said that:

Macros can make using these pointers transparent to any C code that calls routines in Python’s C API.

My question is really how to do what this writer suggests when I'm going to be importing a wide variety of functions, with various signatures. It would be nice to use the signatures that are already in Python.h (including that header somehow).

Was it helpful?

Solution

I would do like the system linker does: construct a symbol table containing all the function names. Then just initialise the pointers in that table. Function names can either be fixed string constants, or they might be read from the DLL itself (i.e. Win32 API to enumerate dll export functions?).

Significant drawback of that table approach, though, is impossibility to use it with existing code, which calls the functions by name (pPy_Initialize();) -- you'd have to use the pointer in the table, perhaps indexed via enum (pPy[Initialize]();).

Different signatures can be handled by using different tables (a table per signature). Signatures can also be stored along with the names in some symbolic form, and then you'd wrap it in some accessor magic which could parse and check it -- but that could quickly become too complex, like inventing yet another programming language.

IMHO, the only significant advantage of all that weird machinery over macros is that you might be able to load arbitrary DLLs with it. Other than that, I wouldn't go that route.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top