2010-11-19 78 views
3

我想從python調用一個dll,但得到一個訪問衝突。可以請告訴我如何在下面的代碼中正確使用ctypes。 GetItems應該返回一個結構,看起來像這樣從python中調用dll函數

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) 

回答

0

首先,你要調用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

然後,指定函數類型項目:

myDLL.get_item.restype = ITEM 

(見http://docs.python.org/library/ctypes.html#return-types

現在你應該是abl e來調用該函數,並且它應該返回一個包含結構成員的對象作爲屬性。

+0

好吧,我添加了這個,現在我得到了 AttributeError:'instancemethod'對象沒有'restype'屬性 – poco 2010-11-19 19:50:10

+0

您需要在實際的DLL函數上設置restype,而不是在您的自定義類上。在你的情況:把'self._dll.get_item_restype = ITEM'放在類的方法中。對困惑感到抱歉。 – 2010-11-20 15:21:13