Easiest way to access C module in Python

bartc bc at freeuk.com
Mon Nov 6 20:52:37 EST 2017


On 07/11/2017 00:58, Chris Angelico wrote:
> On Tue, Nov 7, 2017 at 10:43 AM, John Pote <johnpote at jptechnical.co.uk> wrote:
>> Hi all,
>> I have successfully used Python to perform unit and integration tests in the
>> past and I'd like to do the same for some C modules I'm working with at
>> work. There seem to be a number of ways of doing this but being busy at work
>> and home I looking for the approach with the least learning curve.
>>
>> I don't want to add the C modules into the CPython build itself as I've
>> never done this and at work it's a real pain getting admin rights to do
>> this, and when you do it lasts just 24 hours. The C modules are likely to
>> change frequently as bugs are found and features added.
> 
> Fortunately, you don't have to modify CPython to do this :)
> 
>> The other option I'm considering is to use sockets and write a C wrapper
>> round the C modules I want to test. This has the advantage for me that I
>> know about sockets from Python & C points of view and I get complete control
>> of the C compile process. This may be important as the C modules come from
>> an embedded project and I don't want to change them in any way.
>>
>> Are there any other approachs to this problem?
>> I'll be using Python 3.5 (work) and 3.6 (home).
>> Feedback appriciated.
> 
> This. The best way to do this is to create a wrapper... but the best
> way to create that wrapper is with Cython. (Not to be confused with
> CPython.) Check out http://cython.org/ to see what it takes to carry
> information into and out of the C module. You'd compile the Cython
> wrapper and then import that from Python directly.

Cython seems very confusing to me.

The simplest way for Python to run C is for Python to just run the 
executable created using C. If that is possible.

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.


-- 
bartc



More information about the Python-list mailing list