Skip to content

Instantly share code, notes, and snippets.

@mukundraj
Created October 16, 2014 14:59
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 mukundraj/f4bf45af8ab06d77c866 to your computer and use it in GitHub Desktop.
Save mukundraj/f4bf45af8ab06d77c866 to your computer and use it in GitHub Desktop.
Calling C++ code from Python
import ctypes
_sum = ctypes.CDLL('./sum.so')
_sum.our_function.argtypes = (ctypes.c_int, ctypes.POINTER(ctypes.c_int))
def our_function(numbers):
global _sum
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)
print our_function([1,2,-3,4,-5,6])
# g++ -shared -Wl,-install_name,sum.so -o sum.so -fPIC sum.cpp
# important hint, use extern in Cpp file - http://stackoverflow.com/questions/2900512/ctypes-symbol-not-found-for-dynamic-library-in-osx
# http://jjd-comp.che.wisc.edu/index.php/PythonCtypesTutorial
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment