简体   繁体   English

在python中使用ctypes与只包含函数指针的ac结构进行交互

[英]Interacting with a c struct containing only function pointers using ctypes in python

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). 我在一个dll中有一个结构,它只包含我想在python中与之交互的函数指针(即vtable)(用于测试目的)。 I am having a bit of trouble working out how to do this using ctypes. 我在使用ctypes来解决这个问题时遇到了一些麻烦。

What I have is: 我有的是:

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); 

A 'real' Test object will fill in the struct as appropriate. “真正的”Test对象将根据需要填充结构。 This gets compiled into a DLL (test.dll). 这会被编译成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. 我想,在python中,能够调用工厂方法来获取指向我的Test结构的指针,然后调用结构中包含的函数指针,但我似乎无法理解它是怎么回事会使用ctypes。 Does anyone have any pointers / examples of doing something similar or should I be using something like SWIG or Boost? 有没有人有任何关于做类似事情的指针/例子,或者我应该使用像SWIG或Boost这样的东西?

Thanks for any help. 谢谢你的帮助。

Something like this should be a good starting point (I don't have your DLL compiled to test) 这样的事情应该是一个很好的起点(我没有编译你的DLL来测试)

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)

After this, you'll need to call make_Test() to get the struct, and try calling the functions. 在此之后,您需要调用make_Test()来获取结构,并尝试调用函数。 Perhaps with code like this: 也许使用这样的代码:

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

Provide the dll or test and give me your results and I can help more if you still have problems. 提供dll或测试并给我你的结果,如果你还有问题,我可以提供更多帮助。

The ctypes documentation says that you can create a ctypes.PYFUNCTYPE from an address. ctypes文档说您可以从地址创建ctypes.PYFUNCTYPE。

If you get the address of the functions in your structure then you can wrap it as a Python function thanks to ctypes.PYFUNCTYPE and then call it as a regular ctype function. 如果你获得了结构中函数的地址,那么你可以将它包装成Python函数,这要归功于ctypes.PYFUNCTYPE,然后将其称为常规ctype函数。

I didn't test it myself but I think it maybe something to explore in your case 我自己没有测试过,但我觉得在你的情况下可能需要探索一些东西

See http://docs.python.org/library/ctypes.html#ctypes.PYFUNCTYPE 请参阅http://docs.python.org/library/ctypes.html#ctypes.PYFUNCTYPE

I hope it helps 我希望它有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM