Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import ctypes
- import os
- from subprocess import Popen
- def compile_cpp(srcfile, src):
- with open(srcfile,'w') as fout:
- fout.write(src)
- sofile = './lib'+srcfile.replace('.cpp','.so')
- cmd = 'g++ -fPIC -shared -o{} {}'.format(sofile,srcfile)
- Popen(cmd,shell=True).wait()
- os.remove(srcfile)
- return sofile
- libfile = 'fn.cpp'
- libsrc = '''\
- #include <cstdlib>
- void(*_abort)() = std::abort;
- extern "C" {
- void test() { _abort(); }
- void install_abort(void(*f)()) { _abort = f; }
- }
- '''
- libso = compile_cpp(libfile,libsrc)
- print(libso)
- lib = ctypes.cdll.LoadLibrary(libso)
- # pure python function we want to
- # replace lib._abort() with
- def abort():
- print('in python abort')
- # convert Py func to C func
- c_abort = ctypes.CFUNCTYPE(None)(abort)
- # connect Py func to lib._abort()
- lib.install_abort(c_abort)
- # call lib._abort() from within C++
- lib.test()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement