python - 在python中从dll调用函数

标签 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
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)

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

关于python - 在python中从dll调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4224331/

相关文章:

python - Plotly 中的等值线 map : colours not showing correctly

dll - 使用 Interop.SHDocVw.dll 我在哪里可以找到这个命名空间/dll?

在 Unix 系统上使用时,Python Ctypes 函数调用段错误

python - 打印一份拥有多个家庭的人员名单,每个家庭有多个电话号码

python - 如何在 Spyder IPython 控制台中从 sympy 获得 Latex 风格的输出?

c++ - 使用内联汇编创建一个 c++ dll

python - 在C中访问python结构数组

python - Ctypes CopyFileA 不起作用

javascript - 从 Facebook 上的 JavaScript 文件 (melonJS) 游戏调用 Python 函数 (Flask)

c - 程序无法启动,因为 MSVCR80D.dll