Created
October 3, 2017 11:29
-
-
Save breuderink/10534918a1c769f8cdb1e81e331c5872 to your computer and use it in GitHub Desktop.
Calling C from Python
This file contains hidden or 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
libsum.so: sum.c | |
cc -shared -o libsum.so sum.c |
This file contains hidden or 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
int our_function(int num_numbers, int *numbers) { | |
int sum = 0; | |
for (int i = 0; i < num_numbers; i++) { | |
sum += numbers[i]; | |
} | |
return sum; | |
} |
This file contains hidden or 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 | |
_sum = ctypes.CDLL('libsum.so') | |
_sum.our_function.argtypes = (ctypes.c_int, ctypes.POINTER(ctypes.c_int)) | |
def our_function(numbers): | |
num_numbers = len(numbers) | |
array_type = ctypes.c_int * num_numbers | |
result = _sum.our_function(ctypes.c_int(num_numbers), array_type(*numbers)) | |
return int(result) | |
if __name__ == '__main__': | |
print(our_function([1, 2, 3, -10])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on https://pgi-jcns.fz-juelich.de/portal/pages/using-c-from-python.html.