python - 在 python 中使用 ctypes 与仅包含函数指针的 c 结构体进行交互

标签 python ctypes

我在 dll 中有一个结构,它只包含我想在 python 中与之交互的函数指针(即 vtable)(用于测试目的)。我在弄清楚如何使用 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 中能够调用工厂方法来获取指向我的 Test 结构的指针,然后调用该结构中包含的函数指针,但我似乎无法理解它是如何实现的可以使用 ctypes 来工作。有没有人有任何类似的指示/示例,或者我应该使用 SWIG 或 Boost 之类的东西?

感谢您的帮助。

最佳答案

这样的东西应该是一个很好的起点(我没有编译你的 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)

此后,您需要调用 make_Test() 来获取结构,并尝试调用函数。也许用这样的代码:

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

提供 dll 或测试并向我提供您的结果,如果您仍然遇到问题,我可以提供更多帮助。

关于python - 在 python 中使用 ctypes 与仅包含函数指针的 c 结构体进行交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3854388/

相关文章:

python - 扭曲的启动/停止工厂/协议(protocol)噪音较小的日志消息

python - 手动标准化功能执行时间太长

python - 如何使用 ctypes 将数组从 Go [lang] 返回到 Python?

python - 如何通过ctype将字符串缓冲区从python函数传递给C Api

python - Cython + ctypes?

Python 一行获取枚举类列表的所有值的组合列表

python - Facebook 页面详细信息和 RESTful API?

python - 如何检查系统中是否存在文件或不在 html 页面中使用 jinja?

python - 使用 ctypes 使用 Ctrl-C 中断 Python C 扩展

Python 从不同平台(Windows、Linux 或 OS X)加载库