Prototyping with Python code before compiling

前端 未结 7 1366
囚心锁ツ
囚心锁ツ 2021-01-30 17:56

I have been mulling over writing a peak-fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I ma

7条回答
  •  被撕碎了的回忆
    2021-01-30 18:38

    In my experience, there are two easy ways to call into C code from Python code. There are other approaches, all of which are more annoying and/or verbose.

    The first and easiest is to compile a bunch of C code as a separate shared library and then call functions in that library using ctypes. Unfortunately, passing anything other than basic data types is non-trivial.

    The second easiest way is to write a Python module in C and then call functions in that module. You can pass anything you want to these C functions without having to jump through any hoops. And it's easy to call Python functions or methods from these C functions, as described here: https://docs.python.org/extending/extending.html#calling-python-functions-from-c

    I don't have enough experience with SWIG to offer intelligent commentary. And while it is possible to do things like pass custom Python objects to C functions through ctypes, or to define new Python classes in C, these things are annoying and verbose and I recommend taking one of the two approaches described above.

提交回复
热议问题