开发者

calling a function from dll in python

I am trying to make a call from python to a dll but am getting an access violation.开发者_开发技巧Can some please tell me how to use ctypes correctly in the following code. GetItems is supposed return a struct that looks like this

struct ITEM
{
 unsigned short id;
 unsigned char i;
 unsigned int c;
 unsigned int f;
 unsigned int p;
 unsigned short e;
};

I'm really only interested in getting the id, do not need the other fields. I have my code listed below, what am i doing wrong? Thanks for the help.

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)


First off, you're calling get_item, while your class only has get_inventory_item defined, and you're discarding the result, and capitalization of myDLL is inconsistent.

You need to define a Ctypes type for your struct, like this:

class ITEM(ctypes.Structure):
    _fields_ = [("id", c_ushort),
                ("i", c_uchar),
                ("c", c_uint),
                ("f", c_uint),
                ("p", c_uint),
                ("e", c_ushort)]

(see http://docs.python.org/library/ctypes.html#structured-data-types )

Then specify that the function type is ITEM:

myDLL.get_item.restype = ITEM

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

Now you should be able to call the function and it should return an object with members of the struct as attributes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜