python能夠利用SO的方式去調用C++中的函數,可是須要一種調試方案來進行python和C++的聯合調試,效果是直接在c++代碼中打斷點,而後python在進行c++so調用的時候,直接進入到斷點處:html
testlib.cpppython
#include <python2.7_d/Python.h> using namespace std; PyObject * CFuncEntry(PyObject * self, PyObject *args) { PyObject * datalist = NULL; PyArg_ParseTuple(args, "O", &datalist); int rst = 0; for(int i=0; i < PyList_Size(datalist); ++i){ int val = PyInt_AsLong(PyList_GetItem(datalist, i)); rst += val; } return Py_BuildValue("i", rst); } PyMODINIT_FUNC initCFuncEntry(void) { static PyMethodDef methods[] = { {"CFuncEntry", (PyCFunction)CFuncEntry, METH_VARARGS, "test lib"}, {NULL, NULL, 0, NULL} }; Py_InitModule("CFuncEntry", methods); }
call_cpp.pyc++
#!/usr/bin/python # -*- encoding utf-8 -*- import CFuncEntry if __name__ == "__main__": numberlist = [1,2,3,4,5,6,7] rst = CFuncEntry.CFuncEntry(numberlist) print rst
setup.pypython2.7
from distutils.core import setup, Extension module1 = Extension('CFuncEntry', define_macros = [('MAJOR_VERSION', '1'), ('MINOR_VERSION', '0'), ('Py_DEBUG', 1)], include_dirs = ['/usr/local/include'], library_dirs = ['/usr/local/lib'], sources = ['testlib.cpp']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', author = 'Martin v. Loewis', author_email = 'martin@v.loewis.de', url = 'https://docs.python.org/extending/building', long_description = ''' This is really just a demo package. ''', ext_modules = [module1])
將setup.py和testlib.cpp放到同一個目錄下,執行python setup.py install函數
能夠看到CFuncEntry.so已經生成,這時執行gdb –args python-dbg call_cpp.py能夠進入到gdb調試模式:ui
可能的問題:url
1. python-dbg有可能沒有安裝,須要執行sudo apt-get install python-dbg進行安裝;spa
2. 直接使用g++ -o CFuncEntry.so testlib.cpp -g -shared -fpic -DEBUG -lpython2.7_d 的方式生成的so會出現以下錯誤:.net
undefined symbol: Py_InitModule4_643d
3. 直接用g++進行編譯,生成so,須要加上Py_DEBUG參數:g++ -o CFuncEntry.so testlib.cpp -g -shared -fpic -DEBUG -lpython2.7_d -DPy_DEBUG
參考資料:
1. http://hustoknow.blogspot.com/2013/06/why-your-python-program-cant-start-when.html
2. https://blog.csdn.net/mydear_11000/article/details/52252363