Advertisement
Guest User

Untitled

a guest
May 2nd, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. import ctypes
  2. import os
  3. from subprocess import Popen
  4.  
  5. def compile_cpp(srcfile, src):
  6. with open(srcfile,'w') as fout:
  7. fout.write(src)
  8. sofile = './lib'+srcfile.replace('.cpp','.so')
  9. cmd = 'g++ -fPIC -shared -o{} {}'.format(sofile,srcfile)
  10. Popen(cmd,shell=True).wait()
  11. os.remove(srcfile)
  12. return sofile
  13.  
  14. libfile = 'fn.cpp'
  15. libsrc = '''\
  16. #include <cstdlib>
  17.  
  18. void(*_abort)() = std::abort;
  19.  
  20. extern "C" {
  21. void test() { _abort(); }
  22. void install_abort(void(*f)()) { _abort = f; }
  23. }
  24. '''
  25. libso = compile_cpp(libfile,libsrc)
  26. print(libso)
  27. lib = ctypes.cdll.LoadLibrary(libso)
  28.  
  29. # pure python function we want to
  30. # replace lib._abort() with
  31. def abort():
  32. print('in python abort')
  33.  
  34. # convert Py func to C func
  35. c_abort = ctypes.CFUNCTYPE(None)(abort)
  36.  
  37. # connect Py func to lib._abort()
  38. lib.install_abort(c_abort)
  39.  
  40. # call lib._abort() from within C++
  41. lib.test()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement