-4

I have a piece of code that I developed in an academic context for which I would like to build a nice frontend. My approach to coding has been very academic to this point (read: I made stuff up as I went and didn't worry about other users), but that is no longer a luxury I have, so I want to plan this out carefully before I start anything, and I am unfamiliar with best practices so I am hoping for advice.

My code so far consists of a standalone piece of C software that is compiled to an executable and run via the command line. It is highly optimized, runs like lightning, runs clean through valgrind, and is thoroughly tested by >20 users over 4 years of daily use, but it isn't very use friendly and doesn't do any input validation so it's easy to break it if you don't know how to use it.

In order to incorporate this into a python GUI, I have a few options, and I would like opinions or alternatives from those more experienced than I.

  1. Write the python GUI as a completely separate entity, use it to build the necessary config files and validate the input. Make a system call to the compiled C executable when appropriate.

Pros: easy, simple, won't require much refactoring. The C library is very stable, and not having to change it at all to use it is worth consideration.

Cons: Almost certainly the wrong way to do things. Not sure why, exactly, but please talk me out of this one.

  1. Repackage the C code into a library from which I build cython modules. Use these modules within the python GUI.

Pros: Using cython as intended, basically to glue together fast and optimized modules of C code. Unit testing can happen entirely on the python side (right?) and do all of the input validation on the python side as well, completely hiding the C backend from the user. Can turn it into a more object-oriented structure than the C code presently allows.

Cons: I am new to cython, there will be a learning curve. It will also require refactoring of the C code (in a nutshell, the usual main() function that handles control flow would be moved to the Python side, which comes with the potential for bug introduction and added complexity.

  1. Some third thing I have not thought of yet.

Any advice or alternatives to the above are welcome.

1

You can use Python's ctypes library. Not sure your specific use-case but the general workflow is like this:

from ctypes import *

so_file = 'path/to/shared_object/file.so'

c_functions = CDLL(so_file)
# you can now call functions from that file

c_functions.some_func_you_made_in_c()

# you can even pass parameters 
c_functions.square(2)
# returns 4 assuming the relevant .c file
# had a function called square that took
# an int as a parameter

hope this helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.