combining ctypes and swig

一曲冷凌霜 提交于 2020-01-15 02:55:10

问题


I have been using SWIG for a long time - generally I like it. But doing callback functions seems (much) easier using ctypes.

How can I combine the two "ways" of interacting with a C dll ?

The first step would be to know, how to get a ctypes object to the dll after the dll is already loaded via the import of the corresponding SWIG module.

Thanks,
Sebastian.


回答1:


If x.pyd is the swig compiled extension module, then you can load the dll via ctypes in this way:

import x
from ctypes import PyDLL
dll = PyDLL(x.__file__)

Depending on the calling conventions used by the exported functions, you may need to use PyDLL, WinDLL, or CDLL.




回答2:


The Buffer Protocol may be your best bet ( http://docs.python.org/c-api/buffer.html ).

From C code (eg swig generated code) you can get the pointer to the underlying C data by accessing this interface.

Watch out there are two versions of the buffer interface, ctypes objects in python 2.x will expose the old protocol, in python 3.x they expose the new one.

You will have to go down to the Python C API level, but only once if you wrap everything up nicely - eg maybe make an %inline function returning a void* for anything supporting a buffer protocol, and use that in typemaps for your callback types.



来源:https://stackoverflow.com/questions/7886790/combining-ctypes-and-swig

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!