首先,一些背景知识:我是一名Python开发人员,他使用PyGObject编写了一个中型应用程序,利用GObject自省来访问GSettings等内容。我的一些Python对象实际上是GObject.GObject的子类,所以我非常广泛地使用GObject。
最近,我注意到了一个用GObject (gexiv2,由Shotwell/Vala使用)包装C库的库,但是它目前还不支持自省。我对向gexiv2添加内省支持很感兴趣,这样我就可以从Python中访问它,但我甚至不知道从哪里开始这个主题。
当我研究自省和VAPI时,我看到很多文档引用了这样一个事实,即VAPI可以从自省注释中自动生成……但是,如果一个项目已经有了VAPI,但没有自省,那该怎么办呢?在给定VAPI的情况下,是否可以自动生成自省注释?
谢谢。
发布于 2012-06-30 15:37:17
嗯,在厌倦了将VAPI定义手工复制到自省注释中的单调乏味之后,我写了这个(粗糙的)脚本来为我做这件事:
#!/bin/env python
import sys
from collections import defaultdict
ANNOTATION = """/**
* %s:
%s *
* Returns:%s
*/
"""
PARAMETER = """ * @%s:%s
"""
methods = defaultdict(set)
attrs = defaultdict(dict)
with open(sys.argv[1]) as vapi:
for line in vapi:
tokens = line.split()
try:
names = tuple(tokens[0].split('.'))
except IndexError:
continue
attrs[names] = {}
for attribute in tokens[1:]:
key, val = attribute.split('=')
if val == '"1"': val = True
if val == '"0"': val = False
attrs[names][key] = val
methods[names[0]]
if len(names) > 1:
methods[names[0]].add(names[-1])
for method in methods:
params = ''
for param in methods[method]:
param_attributes = ''
param_attrs = attrs[(method, param)]
if param_attrs.get('hidden'):
param_attributes += ' (skip)'
if param_attrs.get('is_out'):
param_attributes += ' (out)'
if param_attrs.get('transfer_ownership'):
param_attributes += ' (transfer full)'
elif 'transfer_ownership' in param_attrs:
param_attributes += ' (transfer none)'
if param_attrs.get('array_null_terminated'):
param_attributes += ' (array zero-terminated=1)'
if param_attrs.get('array_length_pos'):
param_attributes += ' (array length=FIXME)'
if param_attributes:
param_attributes += ':'
params += PARAMETER % (param, param_attributes)
attributes = ''
method_attrs = attrs[(method,)]
if method_attrs.get('transfer_ownership'):
attributes += ' (transfer full)'
elif 'transfer_ownership' in method_attrs:
attributes += ' (transfer none)'
if method_attrs.get('nullable'):
attributes += ' (allow-none)'
if method_attrs.get('array_null_terminated'):
attributes += ' (array zero-terminated=1)'
if attributes:
attributes += ':'
print ANNOTATION % (method, params, attributes)这显然有一些缺点:它不会将注释插入到代码中,而只是打印它们,因此您必须执行相当多的复制和粘贴操作才能将所有内容放到正确的位置。它也不能很好地处理数组,但它至少让您知道何时需要手动修复数组。总而言之,与手动解析相比,运行此脚本然后处理结果的工作要少得多。我把它贴在这里,是希望它能被google和其他人所采用,并有一天能从中受益(尽管我非常希望从这里开始的所有基于GObject的项目都是从注释开始,然后使用vapigen)。
发布于 2012-06-26 06:55:39
VAPI绑定不一定与GObject自省相关。例如,有用于POSIX、Linux、libudev和其他绝对不是基于GObject的东西的VAPI绑定。没有一种直接的方法可以将VAPI转换为GObject绑定。
但是,如果您有C头文件和工作库,则通常可以从该库构建一个GObject内省文件。对于gexiv2,下载并构建源代码,然后执行:
g-ir-scanner -I gexiv2 gexiv2/gexiv2-{metadata,managed-stream,preview-properties,preview-image,log,startup}.h -n GExiv2 --library libgexiv2.la --pkg gobject-2.0这将生成一个可以在Python中使用的GIR绑定(XML)。
https://stackoverflow.com/questions/11197009
复制相似问题