在Python中调用DLL中的函数
我正在尝试从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)
1 个回答
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 )
然后要指定这个函数的类型是 ITEM:
myDLL.get_item.restype = ITEM
(可以参考 http://docs.python.org/library/ctypes.html#return-types )
现在你应该能调用这个函数,它会返回一个对象,这个对象的属性就是结构体里的成员。