设计网站哪个好用,设计衣服网站,低代码平台设计,自己做的网站显示iis7From: http://hi.baidu.com/jintuguo/item/45639b4e7cda3c9f833ae1bb Python调用C动态链接库 Python调用C库很简单,不经过任何封装打包成so,再使用python的ctypes调用即可。 test.cpp 生成动态库的源文件 #include stdio.h extern C { void…From: http://hi.baidu.com/jintuguo/item/45639b4e7cda3c9f833ae1bb Python调用C动态链接库 Python调用C库很简单,不经过任何封装打包成so,再使用python的ctypes调用即可。 test.cpp 生成动态库的源文件 #include stdio.h extern C { void display() { printf(This is Display Function\n); } } g test.cpp -fPIC -shared -o libtest.so call.py 调用动态库的源文件 import ctypes so ctypes.CDLL(./libtest.so) so.display() 这里需要注意的是:使用g编译生成动态库的代码中的函数 或者 方法时, 需要 使用extern C来进行编译Python调用C(含类,重载)动态链接库但是调用C的so就有点麻烦了,网上找了下大部分都是需要extern C 来辅助也就是说还是只能调用C函数 不能直接调用方法 但是能解析C方法。test.cpp 生成动态库的源文件 #include Akita/Akita.h class TestLib{ public: void display(); void display(int a); }; void TestLib::display() { coutFirst displayendl; } void TestLib::display(int a) { coutSecond displayendl; } extern C { TestLib obj; void display() { obj.display(); } void display_int() { obj.display(2); } } g test.cpp -fPIC -shared -o libtest.so使用这种方法有点麻烦 但是可以解决问题。注意到后面还是会有个extern C 不然构建后的动态链接库没有这些函数的符号表的。call.py 调用动态库的源文件 import ctypes so ctypes.CDLL(./libtest.so) so.display() so.display_int(1) 运行结果如下 ^[root:~/Projects/nugget/kvDB-py]#python call.py First display Second display C/C调用Python模块 test.cpp #include Akita/Akita.h #include Python.h int main() { Py_Initialize(); if (!Py_IsInitialized()) return FALSE; PyRun_SimpleString(import sys); PyRun_SimpleString(sys.path.append(./)); //import Module PyObject* pModule PyImport_ImportModule(hello); if (!pModule) { coutCant import Module!/nendl; return -1; } PyObject* pDict PyModule_GetDict(pModule); if (!pDict) { return -1; } //fetch Function PyObject* pFunHi PyDict_GetItemString(pDict, display); PyObject_CallFunction(pFunHi, s, Crazybaby); Py_DECREF(pFunHi); //Release Py_DECREF(pModule); Py_Finalize(); return 0; } #g test.cpp -I/usr/local/include/python2.7 -ldl -lutil -lpthread -lpython2.7 call.py def display(name): print hi,name --------- C为Python编写扩展模块 Python为C提供脚本接口。 有了两者交互 方便之极。