在python中使用ctypes与仅包含函数指针的c结构进行交互 [英] Interacting with a c struct containing only function pointers using ctypes in python

查看:77
本文介绍了在python中使用ctypes与仅包含函数指针的c结构进行交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在dll中有一个结构,该结构只包含我想在python中进行交互的函数指针(即vtable)(出于测试目的)。我在解决如何使用ctypes进行操作时遇到了一些麻烦。

I have a struct in a dll that only contains function pointers (ie a vtable) that I would like to interact with in python (for test purposes). I am having a bit of trouble working out how to do this using ctypes.

我所拥有的是:

struct ITest  
{  
    virtual char const  *__cdecl GetName() = 0;  
    virtual void  __cdecl SetName(char const *name) = 0;  
};

/* Factory function to create 'real' Test object */  
extern "C" __declspec(dllexport) struct ITest * CALLCONV make_Test(char const * name); 

真实测试对象将在相应的结构中填充。这被编译成DLL(test.dll)。我希望在python中能够调用factory方法来获取指向我的Test结构的指针,然后调用该结构中包含的函数指针,但是我似乎无法理解它的原理将使用ctypes工作。是否有人有做类似事情的指针/示例,还是我应该使用SWIG或Boost之类的东西?

A 'real' Test object will fill in the struct as appropriate. This gets compiled into a DLL (test.dll). I'd like, in python, to be able to call the factory method to get back a pointer to my Test struct and then call the function pointers contained in the struct, but I just can't seem to get my head around how it would work using ctypes. Does anyone have any pointers / examples of doing something similar or should I be using something like SWIG or Boost?

感谢您的帮助。

推荐答案

类似的东西应该是一个很好的起点(我没有编译您的DLL以进行测试)

Something like this should be a good starting point (I don't have your DLL compiled to test)

from ctypes import Structure, CFUNCTYPE, POINTER, c_char_p, windll
class ITest(Structure):
    _fields_ = [
            ('GetName', CFUNCTYPE(c_char_p)),
            ('SetName', CFUNCTYPE(None, c_char_p)
        ]

test = windll.LoadLibrary('test.dll')
test.make_Test.restype = POINTER(ITest)

之后,您需要调用make_Test( )以获取结构,然后尝试调用函数。

After this, you'll need to call make_Test() to get the struct, and try calling the functions. Perhaps with code like this:

itest = test.make_Test().contents
itest.SetName('asdf')
print itest.GetName()

提供dll或测试并给我你r的结果,如果您仍然有问题,我可以提供更多帮助。

Provide the dll or test and give me your results and I can help more if you still have problems.

这篇关于在python中使用ctypes与仅包含函数指针的c结构进行交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆