ctypespython下載
❶ ctypes怎麼下
1、首先在瀏覽器中搜索ctypes官網,點擊下載。
2、其次上傳到/opt目錄下,並執行解壓操作。猛迅返
3、最後准備編譯環境、准枝飢備安裝依賴包zlibopenssl、預編譯:安裝到/usr/python-3.7.0目錄,安昌碰裝即可。
❷ ctypes找不到指定模塊
途徑不對或者被殺毒軟體隔離。
可以把文件路徑改為絕對路徑,把殺毒軟體關閉芹歲重新操作。嫌缺睜
ctypes是Python的外部函數庫,它提供了與c語言兼容的數據類型,並允許調用DLL或共享庫中的函扮弊數。
❸ 我現在想把自己寫的python模塊源代碼封裝成dll,然後在別的python腳本里調用,可以嗎
可以的,只要把python模塊轉換成dll模塊,利用Python自帶的ctypes模塊載入調用就行。
ctypes 是Python的外部函數庫。它提供了與 C語言兼容的數據類型,並允許調用 DLL 或共享庫中的函數。可使用該模塊以純 Python 形式對這些庫進行封裝。
ctypes導出了cdll對象,在 Windows 系統中還導出了windll和oledll對象用於載入動態鏈接庫。通過操作這些對象的屬性,你可以載入外部的動態鏈接庫。cdll載入按標準的cdecl調用協議導出的函數,而windll導入的庫按stdcall調用協議調用其中的函數。
(3)ctypespython下載擴展閱讀:
載入調用DLL的相關方法:
1、載入DLL
載入的時候要根據你將要調用的函數是符合什麼調用約定的。
stdcall調用約定:兩種載入方式
Objdll = ctypes.windll.LoadLibrary("dllpath")
Objdll = ctypes.WinDLL("dllpath")
cdecl調用約定:也有兩種載入方式
Objdll = ctypes.cdll.LoadLibrary("dllpath")
Objdll = ctypes.CDLL("dllpath")
其實windll和cdll分別是WinDLL類和CDll類的對象。
2、調用dll中的方法
載入dll的時候會返回一個DLL對象(假設名字叫Objdll),利用該對象就可以調用dll中的方法。 e.g.如果dll中有個方法名字叫Add(注意如果經過stdcall聲明的方法,如果不是用def文件聲明的導出函數或者extern 「C」 聲明的話,編譯器會對函數名進行修改,這個要注意。)
調用:nRet = Objdll.Add(12, 15) 即完成一次調用。
❹ python使用ctypes調用C編譯dll函數方法
在函數聲明加入前綴,如
__declspec(dllexport) int Fun(int a, int b)
否則在載入該dll時會提示找不到該符號
在windows下可以通過vs自帶的mpbin工具查看可被調用符號
mpbin /exports test.dll
C函數在調用過程中關於參數傳遞和壓棧由多種規定,作為dll提供給其他程序調用時,必須明確並統一為同一種調用規定,否則會導致棧破壞,編譯器負責具體實現調用規定,主要有以下幾種調用規定
python下調用C庫有多種方式,ctypes是其中一種比較方便的,調用時首先需要載入dll文件,根據C dll的調用規定不同需要使用不同介面,使用ctypes需要 import ctypes 庫
對於簡單的C函數,例如 int add(int a, int b) , 此時就可以直接調用了,如
對於較復雜的C函數的參數情況,ctypes調用時對入參和出餐做一定處理,這里分情況討論
以上包含了幾種主要的參數傳遞情況,ctypes也提供了一個較為完整的python類型和C類型的對照,如下:
❺ Python 外部函數調用庫ctypes簡介
一直對不同語言間的交互感興趣,python和C語言又深有淵源,所以對python和c語言交互產生了興趣。
最近了解了python提供的一個外部函數庫 ctypes , 它提供了C語言兼容的幾種數據類型,並且可以允許調用C編譯好的庫。
這里是閱讀相關資料的一個記錄,內容大部分來自 官方文檔 。
ctypes 提供了一些原始的C語言兼容的數據類型,參見下表,其中第一列是在ctypes庫中定義的變數類型,第二列是C語言定義的變數類型,第三列是Python語言在不使用ctypes時定義的變數類型。
創建簡單的ctypes類型如下:
使用 .value 訪問和改變值:
改變指針類型的變數值:
如果需要直接操作內存地址的數據類型:
下面的例子演示了使用C的數組和結構體:
創建指針實例
使用cast()類型轉換
類似於C語言定義函數時,會先定義返回類型,然後具體實現再定義,當遇到下面這種情況時,也需要這么干:
可以簡單地將"so"和"dll"理解成linux和windows上動態鏈接庫的指代,這里我們以Linux為例。注意,ctypes提供的介面會在不同系統上有出入,比如為了載入動態鏈接庫, 在Linux上提供的是 cdll , 而在Windows上提供的是 windll 和 oledll 。
ctypes會尋找 _as_paramter_ 屬性來用作調用函數的參數傳入,這樣就可以傳入自己定義的類作為參數,示例如下:
用 argtypes 和 restype 來指定調用的函數返回類型。
這里我只是列出了 ctypes 最基礎的部分,還有很多細節請參考官方文檔。
這兩天文章沒有寫,先是早出晚歸出去玩了一整天,然後加班到凌晨3點左右,一天一篇計劃劃水得嚴重啊…
❻ python3.2 下的抓包庫。。無論是pypcap還是scapy。貌似都沒有py3的版本。。跪求一個可以python3用
有一個py3kcap是pycap的封裝版本,可以用於python3版本。
給你一個使用的示例代碼:
#!/usr/bin/env python3.2
import ctypes,sys
from ctypes.util import find_library
#pcap = ctypes.cdll.LoadLibrary("libpcap.so")
pcap = None
if(find_library("libpcap") == None):
print("We are here!")
pcap = ctypes.cdll.LoadLibrary("libpcap.so")
else:
pcap = ctypes.cdll.LoadLibrary(find_library("libpcap"))
# required so we can access bpf_program->bf_insns
"""
struct bpf_program {
u_int bf_len;
struct bpf_insn *bf_insns;}
"""
class bpf_program(ctypes.Structure):
_fields_ = [("bf_len", ctypes.c_int),("bf_insns", ctypes.c_void_p)]
class sockaddr(ctypes.Structure):
_fields_=[("sa_family",ctypes.c_uint16),("sa_data",ctypes.c_char*14)]
class pcap_pkthdr(ctypes.Structure):
_fields_ = [("tv_sec", ctypes.c_long), ("tv_usec", ctypes.c_long), ("caplen", ctypes.c_uint), ("len", ctypes.c_uint)]
pkthdr = pcap_pkthdr()
program = bpf_program()
# prepare args
snaplen = ctypes.c_int(1500)
#buf = ctypes.c_char_p(filter)
optimize = ctypes.c_int(1)
mask = ctypes.c_uint()
net = ctypes.c_uint()
to_ms = ctypes.c_int(100000)
promisc = ctypes.c_int(1)
filter = bytes(str("port 80"), 'ascii')
buf = ctypes.c_char_p(filter)
errbuf = ctypes.create_string_buffer(256)
pcap_close = pcap.pcap_close
pcap_lookupdev = pcap.pcap_lookupdev
pcap_lookupdev.restype = ctypes.c_char_p
#pcap_lookupnet(dev, &net, &mask, errbuf)
pcap_lookupnet = pcap.pcap_lookupnet
#pcap_t *pcap_open_live(const char *device, int snaplen,int promisc, int to_ms,
#char *errbuf
pcap_open_live = pcap.pcap_open_live
#int pcap_compile(pcap_t *p, struct bpf_program *fp,const char *str, int optimize,
#bpf_u_int32 netmask)
pcap_compile = pcap.pcap_compile
#int pcap_setfilter(pcap_t *p, struct bpf_program *fp);
pcap_setfilter = pcap.pcap_setfilter
#const u_char *pcap_next(pcap_t *p, struct pcap_pkthdr *h);
pcap_next = pcap.pcap_next
# int pcap_compile_nopcap(int snaplen, int linktype, struct bpf_program *program,
# const char *buf, int optimize, bpf_u_int32 mask);
pcap_geterr = pcap.pcap_geterr
pcap_geterr.restype = ctypes.c_char_p
#check for default lookup device
dev = pcap_lookupdev(errbuf)
#override it for now ..
dev = bytes(str("wlan0"), 'ascii')
if(dev):
print("{0} is the default interface".format(dev))
else:
print("Was not able to find default interface")
if(pcap_lookupnet(dev,ctypes.byref(net),ctypes.byref(mask),errbuf) == -1):
print("Error could not get netmask for device {0}".format(errbuf))
sys.exit(0)
else:
print("Got Required netmask")
handle = pcap_open_live(dev,snaplen,promisc,to_ms,errbuf)
if(handle is False):
print("Error unable to open session : {0}".format(errbuf.value))
sys.exit(0)
else:
print("Pcap open live worked!")
if(pcap_compile(handle,ctypes.byref(program),buf,optimize,mask) == -1):
# this requires we call pcap_geterr() to get the error
err = pcap_geterr(handle)
print("Error could not compile bpf filter because {0}".format(err))
else:
print("Filter Compiled!")
if(pcap_setfilter(handle,ctypes.byref(program)) == -1):
print("Error couldn't install filter {0}".format(errbuf.value))
sys.exit(0)
else:
print("Filter installed!")
if(pcap_next(handle,ctypes.byref(pkthdr)) == -1):
err = pcap_geterr(handle)
print("ERROR pcap_next: {0}".format(err))
print("Got {0} bytes of data".format(pkthdr.len))
pcap_close(handle)
❼ 如何讓python調用C和C++代碼
要搞明白如何讓python調用C/C++代碼(也就是寫python的extension),你需要征服手冊中的<<Extending && embedding>>厚厚的一章。在昨天花了一個小時看地頭暈腦脹,仍然不知道如何寫python的extension後,查閱了一些其他書籍,最終在<<Python Programming On Win32>>書中找到了教程。
1. 首先要明白的是,所謂的python擴展(也就是你提供給python的c/c++代碼,不一定是c/c++代碼,可以是其他語言寫的代碼)是一個dll,並且這個dll放在本機python安裝目錄下的DLLs目錄下(譬如我機器上的路徑是:F:/Program Files/Python25/DLLs),假如我們接下來要寫的擴展mole名為mb,python調用的代碼為:import mbmb.showMsg("Python's really amazing, I kindda love it!")
2. 搭建環境,我們要使用python提供的c頭文件和lib庫來進行擴展的開發。
在vs 2005下點擊菜單 "工具"->"選項", 打開選項對話框,選擇"項目和解決方案->VC++目錄", 然後在右邊"顯示以下內容的目錄"得comboBox上選擇"包含文件」,添加python的include目錄(我的機器上是"F:/Program Files/Python25/include"),然後選擇庫文件,添加python的libs目錄(我的機器上是"F:/Program Files/Python25/libs")。
既然擴展是一個dll,接下來我們要建立一個「動態鏈接庫」工程,然後開始寫代碼:
#include <python.h> //python.h是包含python一些定義的頭文件,在python的include目錄下/*我的python版本是2.5, 因為安裝python後它沒提供debug下的lib庫文件,因此你必須生成release版的dll,
想要生成dll版本的,你要到python官網上自己去下載python源代碼,當然你可以繼續生成release版本的dll,但dll中包含調試信息*/#pragma comment(lib, "python25.lib")//先不管static PyObject* mb_showMsg(PyObject* self, PyObject *args);/*如果你的擴展是mb,那麼必須實現一個initmb函數,並且從dll中導出這個函數,但我們在python中調用import mb時,python會去dll里去調用
extern "C" __declspec(dllexport) void initmb(){/*當調用mb.showMsg("Python's really amazing, I kindda love it!")時, 相當於你告訴python我有一個showMsg函數,我們怎麼告訴python去調用我們dll里的mb_showMsg函數呢?技巧就是下面的方式,定義一個字典數據結構,key => showMsg, value =>mb_showMsg,METH_VARARGS是函數調用方式,仔細查手冊吧*/static PyMethodDef mbMethods[] = {
{"showMsg", mb_showMsg, METH_VARARGS},
{NULL, NULL, NULL} /*sentinel,哨兵,用來標識結束*/};//告訴python我們的模塊名叫mb, 模塊包含的函數都在mbMethods字典里
PyObject *m = Py_InitMole("mb", mbMethods);}/*接下來實現核心功能showMsg*///第一個self參數我們用不著,具體查手冊,第二個參數是python傳給我們的參數,它是一個python的參數tuple
static PyObject* mb_showMsg(PyObject* self, PyObject *args){//我們的showMsg函數需要的是一個字元串參數
const char* msg = NULL;/*調用特殊參數解碼python傳遞給我們的參數,s是string,我們傳遞接收參數的變數地址,
如果你的功能函數需要兩個參數,在PyArg_parseTuple後面繼續添加接受參數的變數地址,
這個函數的原型是類似printf的不定參數的形式
PyAPI_FUNC(int) PyArg_ParseTuple(PyObject *, const char *, ...);*/if (!PyArg_ParseTuple(args, "s", &msg))
return NULL;//調用MBint r = ::MessageBox(NULL, "hello", "Caption:Form C mole", MB_ICONINFORMATION | MB_OK);//返回值return Py_BuildValue("i", r);}將上面這段混雜著大量注釋的代碼拷貝到你的編輯器里,然後編譯生成mb.dll,修改後綴成mb.pyd,然後拷貝到python的DLLs目錄下,打開idle(python的交互程序),寫入代碼:import mbmb.showMsg("Python's really amazing, I kindda love it!")
❽ 如何利用python使用libsvm
把包解壓在C盤之中,如:C:\libsvm-3.182.
因為要用libsvm自帶的腳本grid.py和easy.py,需要去官網下載繪圖工具gnuplot,解壓到c盤.進入c:\libsvm\tools目錄下,用文本編輯器(記事本,edit都可以)修改grid.py和easy.py兩個文件,找到其中關於gnuplot路徑的那項,根據實際路徑進行修改,並保存
python與libsvm的連接(參考SVM學習筆記(2)LIBSVM在python下的使用)
1.打開IDLE(pythonGUI),輸入>>>importsys>>>sys.version
2.如果你的python是32位,將出現如下字元:
(default,Apr102012,23:31:26)[MSCv.150032bit(Intel)]』
這個時候LIBSVM的python介面設置將非常簡單。在libsvm-3.16文件夾下的windows文件夾中找到動態鏈接庫libsvm.dll,將其添加到系統目錄,如`C:\WINDOWS\system32\』,即可在python中使用libsvm
wk_ad_begin({pid : 21});wk_ad_after(21, function(){$('.ad-hidden').hide();}, function(){$('.ad-hidden').show();});
3.執行一個小例子
importos
os.chdir('C:\libsvm-3.18\python')#請根據實際路徑修改
fromsvmutilimport*
y,x=svm_read_problem('../heart_scale')#讀取自帶數據
m=svm_train(y[:200],x[:200],'-c4')
p_label,p_acc,p_val=svm_predict(y[200:],x[200:],m)
##出現如下結果,應該是正確安裝了optimizationfinished,#iter=257nu=0.351161
obj=-225.628984,rho=0.636110nSV=91,nBSV=49
TotalnSV=91
Accuracy=84.2857%(59/70)(classification)
❾ python ctypes 問題
我在互動式環境下使用沒問題,你查一下環境吧。另外,庫名可以不加後綴名,因為linux下可能是so後綴的,加了也沒關系。
C:\Users\s>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "right", "credits" or "license" for more information.
>>> from ctypes import *
>>> dir(CDLL)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__',
'__getattribute__', '__getitem__', '__hash__', '__init__', '__mole__', '__new
__', '__rece__', '__rece_ex__', '__repr__', '__setattr__', '__sizeof__', '__
str__', '__subclasshook__', '__weakref__', '_func_flags_', '_func_restype_']
>>> dll=CDLL("msvcrt")
>>> dll
<CDLL 'msvcrt', handle 75b30000 at 2624570>
>>> dll=CDLL("msvcrt.dll")
>>> dll
<CDLL 'msvcrt.dll', handle 75b30000 at 2608ed0>
❿ python用ctypes操作剪切板遇到問題!!
這邊執行沒有問題,版本如下
Python3.5.0(v3.5.0:374f501f4567,Sep132015,02:27:37)[MSCv.190064bit(AMD64)]onwin32
代碼如下
importctypes
defget():
'''從剪切板中獲得字元串'''
h=ctypes.WinDLL('user32.dll')
h.OpenClipboard(0)
aa=h.GetClipboardData(13)
ss=ctypes.c_wchar_p(aa)
h.CloseClipboard()
returnss.value
defset(mystr):
'''把字元串放到剪切板中,成功返回1,失敗返回0'''
u=ctypes.WinDLL('user32.dll')
k=ctypes.WinDLL('kernel32.dll')
s=mystr.encode('utf-16')
s=s[2:]+b'