Python, C: How to access methods written in C through Python?

135 Views Asked by At

I wrote some functions in C and I want to access them through my Python script. In my research I found the ctypes and struct libraries and the following tutorial explaining how to access shared objects and dlls (http://python.net/crew/theller/ctypes/tutorial.html#loading-dynamic-link-libraries). However, I could not find a simple solution how to import, use or access my C methods in the same folder.

Can you recommend me a way how to access my C methods through Python?

2

There are 2 best solutions below

0
El Marce On BEST ANSWER

You must compile your c methods into a library.

On windows, you must first you must place your .dlls in a place Python can find them. Later you call the ctypes library like this

from ctypes import *

On linux you must use the LoadLibrary method of the dll loaders should be used, or you should load the library by creating an instance of CDLL by calling the constructor:

cdll.LoadLibrary("libc.so.6")
libc = CDLL("libc.so.6")

Depending on the calling convention you use one of the cdll, windll, stdcall or olecall. For example, if you have a stdcall calling convention function do it like this:

from ctypes import *
a = cdll.yourModule.MyIntFunction(9)

You can call these functions like any other Python callable. ctypes tries to protect you from calling functions with the wrong number of arguments or the wrong calling convention. Unfortunately this only works on Windows.

ctypes define a number of primitive c compatibles types find the complete reference in here: http://python.net/crew/theller/ctypes/tutorial.html#id4

1
Riccardo Cagnasso On

Take a look at this tutorial, seems pretty straightforward to me.

Basically you write your C functions using Python.h, compile it as dynamic lib and this become a python module.