Skip to content

Instantly share code, notes, and snippets.

@breuderink
Created October 3, 2017 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save breuderink/10534918a1c769f8cdb1e81e331c5872 to your computer and use it in GitHub Desktop.
Save breuderink/10534918a1c769f8cdb1e81e331c5872 to your computer and use it in GitHub Desktop.
Calling C from Python
libsum.so: sum.c
cc -shared -o libsum.so sum.c
int our_function(int num_numbers, int *numbers) {
int sum = 0;
for (int i = 0; i < num_numbers; i++) {
sum += numbers[i];
}
return sum;
}
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]))
@breuderink
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment