繁体   English   中英

使用ctypes将文档字符串添加到从dll提取的python函数中

[英]Adding docstrings to python functions pulled from dll using ctypes

我正在尝试从Windows dll创建一堆python函数,并希望将文档字符串附加到每个新函数。

我当前的代码:

import ctypes

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

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

当我在解释器中运行此脚本并尝试使用该函数时,我收到“无文档字符串”消息。

想不通在那儿加些东西。 任何帮助表示赞赏。

在此处输入图片说明

分配给ctypes函数指针的__doc__属性:

VCS_OpenDevice.__doc__ = 'My docstring'

__doc__是Python对象的docstring属性,而ctypes对象则允许您写入该属性。

强制性的libc演示(我使用Mac,而不是Windows,但原理相同):

>>> 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似乎可以做到这一点:

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

但是我想使用help()!!!!!

因此,我没有赢得生活上的不公平,而是创建了help_support模块,该模块在导入时将允许您对已记录的ctypes函数和结构使用帮助。 它还允许您记录额外的内容,例如ctypes函数参数的名称,它们也会显示出来。

https://pypi.org/project/help-support/0.2/

如果您要进行Python绑定,请包括help_support.py并将其导入,以使像我这样的脚底不好的人可以更快地使用您的lib进行开发。

真正的文档对A ...来说很痛苦,我对原始的Python控制台感到满意。

通过从C扩展名向我的函数中添加doc字符串来做明显的事情之后,在help()中看不到任何结果,并且在Internet上找不到解决方案之后,我简直无法忍受这种情况。 所以你来了。 现在,您可以对从DLL提取的函数使用help()(至少在Python 2中)。

这是一个例子:

# examp_module:
import ctypes
import ctypes.util

import help_support
del help_support # If you want you can remove it now
                 # to avoid cluttering your globals() namespace.
                 # Once it is called you do not usually need it any more.

l = ctypes.CDLL(ctypes.util.find_library("c"))

# Pull the time() function from libc,
# declare and document it:
time = l.time
time.argtypes = []
#time.argnames = ["c_void"] # The function takes no arguments, but you can trick help_support 
                            # to show something in parenthesis if you want to be consistent with C
                            # If there is/are argument(s) you should put its/their name(s) in "argnames".
time.restype = ctypes.c_int
time.__doc__ = "Function that returns a system time in seconds."
-------------------------------------------
>>> # Usage:
>>> import examp_module
>>> help(examp_module)
>>> help(examp_module.time)
>>>

暂无
暂无

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

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