For developing a C++ dynamically-linked library (i.e. shared object) which may interface with C programs, what is the best practice to save program state across exported function calls?
I as a not-experienced C++ programmer can think of the following methods:
- Compilation unit level
static
variables. - Instantiate a
struct
at heap which holds the state and passing back and forth its address in each API call (somewhat like JNI).
The problem with the first approach is that my state variables need some data to be initialized and these data are provided by calling init
API (one of exported functions). On the other side, when using module's level static
variables, those data aren't available yet when those variables are getting initialized.
Also my problem with the second method is that each API function should be supplied with that pointer and this is a bit cumbersome.
Note that there is another option that static
variables are pointers to those state variables and are assigned in that init
function (actually state variables are instantiated in init
and their address are saved in those static variables). This option is fine, but I would like to not use pointers where possible.