我有一个我想在python中使用的API.该API包含使用#define实现的标志和枚举.
// it's just almost C so don't bother adding the typedef and parenthesis diarrhea here.
routine(API_SOMETHING | API_OTHERTHING)
stuff = getflags()
? stuff & API_SOMETHING
action(API_INTERESTING)
mode = getaction()
? mode == INTERESTING
Run Code Online (Sandbox Code Playgroud)
如果现在忽略除枚举和标志之外的所有其他内容,我的绑定应该将其转换为:
routine(["something", "otherthing"])
stuff = getflags()
if 'something' in stuff
action('interesting')
mode = getaction()
if mode == 'interesting'
Run Code Online (Sandbox Code Playgroud)
ctypes是否提供直接执行此操作的机制?如果没有,那么就告诉你在python绑定中处理标志和枚举的"通常"工具.
我对自己回答这个问题感到有点失望。特别是因为我从 f* 手册中找到了这一切。
http://docs.python.org/library/ctypes.html#calling-functions-with-your-own-custom-data-types
为了完成我的答案,我将编写一些包装项目的代码。
from ctypes import CDLL, c_uint, c_char_p
class Flag(object):
flags = [(0x1, 'fun'), (0x2, 'toy')]
@classmethod
def from_param(cls, data):
return c_uint(encode_flags(self.flags, data))
libc = CDLL('libc.so.6')
printf = libc.printf
printf.argtypes = [c_char_p, Flag]
printf("hello %d\n", ["fun", "toy"])
Run Code Online (Sandbox Code Playgroud)
encode_flags 将这个漂亮的列表转换为一个整数。
| 归档时间: |
|
| 查看次数: |
3531 次 |
| 最近记录: |