跳到主要內容

發表文章

目前顯示的是 7月, 2018的文章

在 Python 中使用 DLL

參考網址: 如Py似C:Python 與 C 的共生法則 https://medium.com/pyladies-taiwan/%E5%A6%82py%E4%BC%BCc-python-%E8%88%87-c-%E7%9A%84%E5%85%B1%E7%94%9F%E6%B3%95%E5%89%87-568add0ba5b8 總共介紹三種方法,以下是該文介紹的第二種方法:ctypes 的節錄。 ctypes ctypes  是 Python 提供的一個 library,可以在 Python 中匯入一些外部 dynamic-link library (DLL) 或 shared library,來調用其中的 function。 如果是已經存在的 library,可以直接從下面的第二步開始。現在假設我們想把前面提到自己寫的,很花時間運算的  slow_calc  function 打包給  ctypes 調用,且這個 function 寫在  speedup_performance.c  裡。 ctypes  簡單三步驟: Step 1: 建立 Shared Library 首先用 gcc 建立 shared library,產生  speedup_performance.so  檔: $ gcc -shared -fPIC speedup_performance.c -o speedup_performance.so Step 2: 匯入 Library 接著在 Python 用  ctypes  提供的 function 來匯入剛剛建立的  so  檔: from ctypes import * m = cdll.LoadLibrary('./speedup_performance.so') 如此一來 library 中的 function 就能以  m.func()  取用。 Step 3: 呼叫 Function 調用的時候,需要傳入對應原 C function 中的 parameter types。 這邊 有列出每個 C type 對應的 ctypes ty...

在 Python 中使用 DLL 檔

參考網址: 簡單示例  https://stackoverflow.com/questions/252417/how-can-i-use-a-dll-file-from-python 完整說明 ctypes module https://docs.python.org/3/library/ctypes.html#module-ctypes 標題:How can I use a DLL file from Python? 作者:paxdiablo https://stackoverflow.com/users/14860/paxdiablo It's very easy to call a DLL function in Python. I have a self-made DLL file with two functions: add and sub which take two arguments. add(a, b) returns addition of two numbers sub(a, b) returns substraction of two numbers The name of the DLL file will be "demo.dll" Program: from ctypes import* # give location of dll mydll = cdll.LoadLibrary("C:\\demo.dll") result1= mydll.add(10,1) result2= mydll.sub(10,1) print "Addition value:"+result1 print "Substraction:"+result2 Output: Addition value:11 Substraction:9