Skip to content

Instantly share code, notes, and snippets.

@elyezer
Created October 22, 2013 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save elyezer/7099291 to your computer and use it in GitHub Desktop.
Save elyezer/7099291 to your computer and use it in GitHub Desktop.
Create and use a shared library using Python's ctypes module
# Compile a shared library
gcc -shared -o libmean.so.1 mean.c
#include "mean.h"
double mean(double a, double b) {
return (a+b)/2;
}
// Returns the mean of passed parameters
double mean(double, double);
>>> import ctypes
>>> libmean = ctypes.CDLL("libmean.so.1") # loads the shared library
>>> libmean.mean.restype = ctypes.c_double # define mean function return type
>>> libmean.mean(ctypes.c_double(10), ctypes.c_double(3)) # call mean function needs cast arg types
6.5
>>> libmean.mean.argtypes = [ctypes.c_double, ctypes.c_double] # define arguments types
>>> libmean.mean(10, 3) # call mean function does not need cast arg types
6.5
>>> type(libmean.mean(10, 5)) # returned value is converted to python types
<type 'float'>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment