-
當(dāng)前位置:首頁 > 創(chuàng)意學(xué)院 > 營銷推廣 > 專題列表 > 正文
python調(diào)用ctypes(python調(diào)用ctypes接收指針)
大家好!今天讓創(chuàng)意嶺的小編來大家介紹下關(guān)于python調(diào)用ctypes的問題,以下是小編對此問題的歸納整理,讓我們一起來看看吧。
開始之前先推薦一個非常厲害的Ai人工智能工具,一鍵生成原創(chuàng)文章、方案、文案、工作計劃、工作報告、論文、代碼、作文、做題和對話答疑等等
只需要輸入關(guān)鍵詞,就能返回你想要的內(nèi)容,有小程序、在線網(wǎng)頁版、PC客戶端和批量生成器
問友Ai官網(wǎng):https://ai.de1919.com。
本文目錄:
如何讓python調(diào)用C和C++代碼
二、Python調(diào)用C/C++1、Python調(diào)用C動態(tài)鏈接庫Python調(diào)用C庫比較簡單,不經(jīng)過任何封裝打包成so,再使用python的ctypes調(diào)用即可。(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編譯生成動態(tài)庫libpycall.so:gcc-olibpycall.so-shared-fPICpycall.c。使用g++編譯生成C動態(tài)庫的代碼中的函數(shù)或者方法時,需要使用extern"C"來進(jìn)行編譯。(3)Python調(diào)用動態(tài)庫的文件:pycall.py[html]viewplaincopyimportctypesll=ctypes.cdll.LoadLibrarylib=ll("./libpycall.so")lib.foo(1,3)print'***finish***'(4)運行結(jié)果:2、Python調(diào)用C++(類)動態(tài)鏈接庫需要extern"C"來輔助,也就是說還是只能調(diào)用C函數(shù),不能直接調(diào)用方法,但是能解析C++方法。不是用extern"C",構(gòu)建后的動態(tài)鏈接庫沒有這些函數(shù)的符號表。(1)C++類文件:pycallclass.cpp[html]viewplaincopy#includeusingnamespacestd;classTestLib{public:voiddisplay();voiddisplay(inta);};voidTestLib::display(){cout#include#includeintfac(intn){if(n<2)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(pPython使用Ctypes調(diào)用lib,怎么使用指針類型參數(shù)接收輸出參數(shù)
本文演示了在python中調(diào)用C語言生成的動態(tài)庫,返回結(jié)構(gòu)體指針,并進(jìn)行輸出!test.c(動態(tài)庫源代碼)
// 編譯生成動態(tài)庫: gcc -g -fPIC -shared -o libtest.so test.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct StructPointerTest
{
char name[20];
int age;
}StructPointerTest, *StructPointer;
StructPointer test() // 返回結(jié)構(gòu)體指針
{
StructPointer p = (StructPointer)malloc(sizeof(StructPointerTest));
strcpy(p->name, "Joe");
p->age = 20;
return p;
}
編譯:gcc -g -fPIC -shared -o libtest.so test.c
call.py(python調(diào)用C語言生成的動態(tài)庫):
#!/bin/env python
# coding=UTF-8
from ctypes import *
#python中結(jié)構(gòu)體定義
class StructPointer(Structure):
_fields_ = [("name", c_char * 20), ("age", c_int)]
if __name__ == "__main__":
lib = cdll.LoadLibrary("./libtest.so")
lib.test.restype = POINTER(StructPointer)
p = lib.test()
print "%s: %d" %(p.contents.name, p.contents.age)
最后運行結(jié)果:
[zcm@c_py #112]$make clean
rm -f *.o libtest.so
[zcm@c_py #113]$make
gcc -g -fPIC -shared -o libtest.so test.c
[zcm@c_py #114]$./call.py
Joe: 20
[zcm@c_py #115]$
以上就是關(guān)于python調(diào)用ctypes相關(guān)問題的回答。希望能幫到你,如有更多相關(guān)問題,您也可以聯(lián)系我們的客服進(jìn)行咨詢,客服也會為您講解更多精彩的知識和內(nèi)容。
推薦閱讀:
利用Python批量爬取網(wǎng)頁圖片(利用python批量爬取網(wǎng)頁圖片文字)
python能做網(wǎng)站開發(fā)嗎(python可以用來開發(fā)網(wǎng)站嗎)