1

You have a python module written with SWIG (http://swig.org/), named "swigMod1", and a global C variable in the .i extension file called "int A1=0;". Typing "import swigMod1" and "swigMod1.cvar.A1" under the python environment, imports the new extension and allows you to read and modify A1 during the execution time.

If you are running two swig modules, a syntax like "swigMod1.cvar.A1=swigMod2.cvar.A2" copies the variable A1 (in the first module) into A2 (in the second module).

This is a very useful functionality in my project, and I'd like to preserve it in the next considered case.

You have now another extension named "cMod", this time written via the classical C API (https://docs.python.org/2.7/extending/extending.html#). There is again a C global variable in the source code ("int B=1;"), and you want to access it like in the example before, but typing "cMod.cvar.B" doesn't work because it is only a SWIG feature.

Is it possible to obtain anyway results like "cMod.cvar.B" and "swigModule.cvar.A1=cMod.cvar.B" ?

Please note how I declared integers only for simplicity but in practice I face other types and I'd like to find a general solution. I also omitted the proper checking for avoiding undesired effects.

4
  • Long time ago I looked for a general solution, and have not found one. I remember that it was a pain to use both python and C with structures, and we also had to pass variables to functions by value and not by pointer (yikes!). That being said, it was 10+years since I tried that, and there could be newer libraries, and improved SWIG that can do that. Good luck, and I am looking forward to see if you have found the solution. Have you seen this one answer: stackoverflow.com/questions/35585457/… Commented Jan 18, 2018 at 16:45
  • 2
    It's probably simpler to make a statically allocated cvar Python object and move your global variables to C-level struct fields in that object, then provide Python-level access through the tp_members interface. Commented Jan 18, 2018 at 17:32
  • @user2357112 your idea sounds really promising. Do you mind elaborating? I started learning Python really recently and I do not know how to turn your advice into practice. Commented Jan 18, 2018 at 17:57
  • I wrote up part of an answer and then got bored (and I can't test it anyway), so here's what I wrote in a pastebin. It's (part of) an example of what such code might look like. The globals struct is where globals would go, and unless I screwed something up, it should be a valid Python object that exposes its struct fields as Python attributes, so inserting it into your module dict should provide Python-level access to those fields. Commented Jan 20, 2018 at 22:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.