Easiest way to access C module in Python

bartc bc at freeuk.com
Tue Nov 7 06:06:44 EST 2017


On 07/11/2017 02:23, Chris Angelico wrote:
> On Tue, Nov 7, 2017 at 12:52 PM, bartc <bc at freeuk.com> wrote:

>> Cython seems very confusing to me.
>

>
>> Otherwise what /I/ would look for is ways to call C functions inside shared
>> libraries (.dll and .so). That requires that the modules under test be
>> wrapped as a shared library, which may be extra effort (but it will still be
>> using C, so with familiar tools and no crossover with Python at this point).
>>
>> To call shared library C functions from Python I think involves the ctypes
>> module (I've never done it). Googling 'ctypes shared library' gives some
>> promising results.
> 
> The point of Cython is to make this easier. It's worth learning.

My experience is different.

I created a function fred() in a C module, then linked that into a .dll 
(.so on Linux should be similar).

Then I wrote this code, adapted from the first hit I found for 'python 
ctypes example':

  import ctypes

  testlib = ctypes.CDLL('c:/c/c.dll')
  testlib.fred()

And it worked perfectly (on Py2 and Py3). (I understand passing 
arguments is a bit more complicated, but at least you have a working base.)

Then I tried the first example I saw for 'cython examples' which was 
this, first create a .pyx file as suggested, then:

  from distutils.core import setup
  from Cython.Build import cythonize

  setup(ext_modules=cythonize("helloworld.pyx"))

It spend several seconds thinking about it, then I got this enlightening 
error report:

  17.299999999999997
  Traceback (most recent call last):
   File "c:\langs\a.py", line 10, in <module>
     from distutils.core import setup
   File "c:\python36\lib\distutils\core.py", line 16, in <module>
     from distutils.dist import Distribution
   File "c:\python36\lib\distutils\dist.py", line 10, in <module>
     from email import message_from_file
  ImportError: cannot import name 'message_from_file'

That was Py3; on Py2, I had 30 seconds of disk activity, and nearly full 
memory that almost stalled my machine before I aborted it. (Actually I 
mispelled both 'cythonize's in the example; it didn't make any difference).

And I still have no idea how to relate this to calling a native C 
function in an external shared library.

-- 
bartc



More information about the Python-list mailing list