Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting C global variables to a python extension

Tags:

python

I have to write a python extension to a C module that comes from a third-party package. The module contains the declarations of some methods and also of the following variables at the module level:

int mcnumipar = 13;

struct my_struct {char *name;
                  void *par;
                  enum instr_formal_types type;
                  char *val;};

struct my_struct mcinput[mcnumipar+1] = {
    "E0", &mcipE0,  instr_type_double, "4.94",
    "dE", &mcipdE, instr_type_double, "0.24", 
    "dt", &mcipdt, instr_type_double, "6.4e-6", 
    "coh", &mcipcoh, instr_type_string, "Rb_liq_coh.sqw", 
    "inc", &mcipinc, instr_type_string, "Rb_liq_inc.sqw"
};

I succeeded in exporting the C-methods to my python extension using the PyMethodDef mechanism as explained in the Python/C API documentation. Unfortunately, I failed for the global variables.

Is there a way to export those variables (mcnumipar & mcinput) into my python extension ?

thanks a lot

Eric

like image 237
Eurydice Avatar asked Aug 19 '26 12:08

Eurydice


1 Answers

Certainly. Possibly the easiest way would be to create Python objects for those variables with Py_BuildValue(), and then add them into your module object (the one you created with Py_InitModule()) using PyObject_SetAttrString().

If the contents of those global variables may change over time, and you want your Python code to be able to see the latest values, then you may be better off exposing extra methods which return the current values.

As a third option, you could use ctypes fairly easily to inspect or even change the current values of those variables. It would be a bit strange to build a true Python-C module for part of an API, and expose the rest through ctypes, but it might end up fitting your needs.

like image 200
the paul Avatar answered Aug 22 '26 13:08

the paul