【问题标题】:calling a function from dll in python在python中从dll调用函数
【发布时间】:2010-11-19 11:02:20
【问题描述】:

我正在尝试从 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)

【问题讨论】:

    标签: python dll ctypes


    【解决方案1】:

    首先,您调用的是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

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

    【讨论】:

    • 好的,我添加了这个,现在我得到 AttributeError: 'instancemethod' object has no attribute 'restype'
    • 您需要在实际的 DLL 函数上设置restype,而不是在您的自定义类上。在您的情况下:将 self._dll.get_item_restype = ITEM 放入类的方法中。很抱歉造成混乱。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    相关资源
    最近更新 更多