在python中从dll调用函数

在python中从dll调用函数,python,dll,ctypes,Python,Dll,Ctypes,我试图从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

我试图从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\u item
,而您的类只定义了
get\u inventory\u 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)]
(见附件)

然后指定函数类型为ITEM:

myDLL.get_item.restype = ITEM
(见附件)


现在,您应该能够调用该函数,并且它应该返回一个对象,其中包含结构的成员作为属性

好的,我添加了这个,现在我得到了AttributeError:'instancemethod'对象没有属性'restype',您需要在实际的DLL函数上设置
restype
,而不是在自定义类上。在您的情况下:将
self.\u dll.get\u item\u restype=item
放入类的方法中。很抱歉给你带来了困惑。