本文目錄一覽:
如何在python中調用C語言代碼
先把C語言代碼做成DLL文件,再用python加載此DLL文件來訪問C語言功能代碼
如何讓python調用C和C++代碼
二、Python調用C/C++1、Python調用C動態鏈接庫Python調用C庫比較簡單,不經過任何封裝打包成so,再使用python的ctypes調用即可。(1)C語言文件:pycall.c[html]viewplaincopy/***gcc-olibpycall.so-shared-fPICpycall.c*/#include#includeintfoo(inta,intb){printf(“youinput%dand%d\n”,a,b);returna+b;}(2)gcc編譯生成動態庫libpycall.so:gcc-olibpycall.so-shared-fPICpycall.c。使用g++編譯生成C動態庫的代碼中的函數或者方法時,需要使用extern”C”來進行編譯。(3)Python調用動態庫的文件:pycall.py[html]viewplaincopyimportctypesll=ctypes.cdll.LoadLibrarylib=ll(“./libpycall.so”)lib.foo(1,3)print’***finish***’(4)運行結果:2、Python調用C++(類)動態鏈接庫需要extern”C”來輔助,也就是說還是只能調用C函數,不能直接調用方法,但是能解析C++方法。不是用extern”C”,構建後的動態鏈接庫沒有這些函數的符號表。(1)C++類文件:pycallclass.cpp[html]viewplaincopy#includeusingnamespacestd;classTestLib{public:voiddisplay();voiddisplay(inta);};voidTestLib::display(){cout#include#includeintfac(intn){if(n2)return(1);/*0!==1!==1*/return(n)*fac(n-1);/*n!==n*(n-1)!*/}char*reverse(char*s){registerchart,/*tmp*/*p=s,/*fwd*/*q=(s+(strlen(s)-1));/*bwd*/while(p
python 怎麼調用c語言接口
ctypes: 可直接調用c語言動態鏈接庫。
使用步驟:
1 編譯好自己的動態連接庫
2 利用ctypes載入動態連接庫
3 用ctype調用C函數接口時,需要將python變量類型做轉換後才能作為函數參數,轉換原則見下圖:
4 Python若想獲取ctypes調用的C函數返回值,需要先指定返回值類型。我們將在接下來的完整Sample中看到如何使用。
#Step 1: test.c#include stdio.h
int add(int a, int b)
{
return a + b;
}#Step 2: 編譯動態鏈接庫 ( 如何編譯動態鏈接庫在本文不詳解,網上資料一大堆。)gcc -fPIC -shared test.c -o libtest.so
#Step 3: test.py
from ctypes import *mylib = CDLL(“libtest.so”) 或者 cdll.LoadLibrary(“libtest.so”) add = mylib.add
add.argtypes = [c_int, c_int] # 參數類型,兩個int(c_int是ctypes類型,見上表)
add.restype = c_int # 返回值類型,int (c_int 是ctypes類型,見上表)
sum = add(3, 6)
原創文章,作者:UPTA,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/139054.html