0

I'm writing some sort of Python C extension. It uses my own *.so library and headers from another project (let's say they're in /usr/local/lib/otherproject.so and /usr/local/include/otherproject.h).

I don't know which strategy to follow. I came up with two:

As a pure Python extension

Write a Python C extension just as described in the official docs. The problem here is that I don't know how to link with my own library and headers; to compile, I write a setup.py file and run python3.4 setup.py build. I don't know if I can include some option to the former command, or if I can write something in setup.py to include my headers and binaries (if so, I will also have to worry about making this distributable?).

With ctypes

Write a C library (with my other project's build system). Include Python by passing '/usr/include/python2.7' to find headers and the python2.7 binary. Then use ctypes to wrap around that library and get the functions, types, objects, etc. The inconvenience here is that I need to manually wrap around every single function/type/variable from ctypes; I don't think I can use PyModule_AddObject since I'm not creating the module in C but in the Python wrapper (with ctypes).


Also, I tried the second approach, but I could not successfully get my custom PyTypeObject from ctypes. If the second approach sounds good to any more expert brain here on SO, I would post the code to get any help =).

tynn
  • 38,113
  • 8
  • 108
  • 143
jleeothon
  • 2,907
  • 4
  • 19
  • 35

1 Answers1

1

The second approach also yields problems with distribution. And if you create a Python object in C you should do it in the context of a module. For scenarios where distribution is problematic, you could link this module statically instead.

For your issue with linking you'll find more information about Library options in the documentation. Since your library resides in a directory which should be in the standard library search path, you'd only need to define your library with the libraries option of the Extension class:

mymodule_ext = Extension('mymodule', ['mymodule.c'], libraries=['otherproject'])

If you're not using the standard lib* prefix you'd need to use libraries=[':otherproject.so'] instead.

tynn
  • 38,113
  • 8
  • 108
  • 143
  • Thanks! I did follow the first approach from above and yes, discovered ``libraries``, ``library_dirs``, and ``include_dirs``, which help me build like a Python extension and link with my other stuff. – jleeothon Dec 23 '15 at 17:59