Created
October 22, 2013 11:56
-
-
Save elyezer/7099291 to your computer and use it in GitHub Desktop.
Create and use a shared library using Python's ctypes module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Compile a shared library | |
gcc -shared -o libmean.so.1 mean.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "mean.h" | |
double mean(double a, double b) { | |
return (a+b)/2; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Returns the mean of passed parameters | |
double mean(double, double); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> 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