[英]calling a function from dll in python
我正在嘗試從python調用到dll,但是我遇到了訪問沖突。有些請告訴我如何在以下代碼中正確使用ctypes。 GetItems應該返回一個看起來像這樣的結構
struct ITEM
{
unsigned short id;
unsigned char i;
unsigned int c;
unsigned int f;
unsigned int p;
unsigned short e;
};
我真的只對獲取id感興趣,不需要其他字段。 我的代碼列在下面,我做錯了什么? 謝謝您的幫助。
import psutil
from ctypes import *
def _get_pid():
pid = -1
for p in psutil.process_iter():
if p.name == 'myApp.exe':
return p.pid
return pid
class MyDLL(object):
def __init__(self):
self._dll = cdll.LoadLibrary('MYDLL.dll')
self.instance = self._dll.CreateInstance(_get_pid())
@property
def access(self):
return self._dll.Access(self.instance)
def get_inventory_item(self, index):
return self._dll.GetItem(self.instance, index)
if __name__ == '__main__':
myDLL = MyDLL()
myDll.get_item(5)
首先,你正在調用get_item
,而你的類只定義了get_inventory_item
,並且你丟棄了結果,並且myDLL的大小寫是不一致的。
您需要為結構定義Ctypes類型,如下所示:
class ITEM(ctypes.Structure):
_fields_ = [("id", c_ushort),
("i", c_uchar),
("c", c_uint),
("f", c_uint),
("p", c_uint),
("e", c_ushort)]
(見http://docs.python.org/library/ctypes.html#structured-data-types )
然后指定函數類型是ITEM:
myDLL.get_item.restype = ITEM
(見http://docs.python.org/library/ctypes.html#return-types )
現在你應該能夠調用該函數,它應該返回一個帶有struct成員作為屬性的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.