-
-
Save mukundraj/f4bf45af8ab06d77c866 to your computer and use it in GitHub Desktop.
Calling C++ code from Python
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 | |
_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