Search code examples
pythondllctypesdocstring

Adding docstrings to python functions pulled from dll using ctypes


I'm trying to create a bunch of python functions from a windows dll, and would like to have docstrings attached to each new function.

My current code:

import ctypes

lib=ctypes.WinDLL('example.dll')

VCS_OpenDevice=lib['VCS_OpenDevice']
VCS_OpenDevice.restype=ctypes.c_double

When i run this script in my interpreter and try to use the function, I get the 'no docstring' message.

Can't figure out to add something there. Any help is appreciated.

enter image description here


Solution

  • Assign to the __doc__ attribute of ctypes function pointers:

    VCS_OpenDevice.__doc__ = 'My docstring'
    

    __doc__ is the docstring attribute of Python objects, and ctypes objects allow you to write to this attribute.

    Obligatory libc demonstration (I use Mac, not Windows, but the principle is the same):

    >>> from ctypes import *
    >>> libc = cdll.LoadLibrary("libc.dylib") 
    >>> libc.time.__doc__ = 'time -- get time of day'
    >>> print libc.time.__doc__
    time -- get time of day
    

    IPython seems to be able to pick that up just fine:

    In [4]: libc.time?
    Type:       _FuncPtr
    String Form:<_FuncPtr object at 0x1054b8ef0>
    File:       /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ctypes/__init__.py
    Docstring:  time -- get time of day