python - 如何使用 Python 的 cffi 和 enum 数组

标签 python c enums python-cffi

我有一个用 C 实现的函数,它将字符串转换为定义的枚举数组。 C 代码如下所示:

头文件(描述枚举):

/* File `asdf.h` */
enum translation {
        ONE,
        ANOTHER,
        FINISH,
};

void translate(char *origin, enum translation *destination);

源文件(实现进行翻译的函数):

/* File `asdf.c` */
#include "asdf.h"


void translate(char *origin, enum translation *destination)
{
    while (1) {
        if (*origin == 'F')
            break;
        if (*origin == 'O')
            *destination++ = ONE;
        if (*origin == 'A')
            *destination++ = ANOTHER;
        origin++;
    }
    *destination = FINISH;
}

现在我希望能够使用 CFFI 从 Python 调用这个函数。 ,并能够检查输出数组的正确值(翻译)。我怎样才能做到这一点?

我尝试先编译模块,然后创建变量并以这种方式调用函数,但没有成功:

# File `cffienum.py`
from pathlib import Path
from cffi import FFI


ffibuilder = FFI()
ffibuilder.cdef(Path('asdf.h').read_text())
ffibuilder.set_source(
    '_asdf',  # name of the output C extension
    '#include "asdf.h"',
    sources=['asdf.c'])   # includes asdf.c as additional sources
ffibuilder.compile()


if __name__ == '__main__':
    from _asdf.lib import translate

    ffi = FFI()
    ffi.cdef(Path('asdf.h').read_text())
    c = ffi.dlopen('c')
    source = ffi.new('char source[]', b'OAF')
    destination = ffi.new('enum translation destination[10]')

    translate(source, destination)
    print(source, destination)

这是我得到的错误:

$ pipenv run python cffienum.py 
Traceback (most recent call last):
  File "cffienum.py", line 24, in <module>
    translate(source, destination)
TypeError: initializer for ctype 'enum translation *' must be a pointer to same type, not cdata 'enum translation[10]'

第一次接触 CFFI,并不是一个经验丰富的 C 程序员,所以我敢打赌我在这里做错了很多事情。

更新

请注意,如果代替:

void translate(char *origin, enum translation *destination)

我使用:

void translate(char *origin, char *destination)

或者:

void translate(char *origin, uint8_t *destination)

它工作得很好。因此,在使用枚举翻译*时我必须遗漏一些东西...

最佳答案

您必须使用 _adsl 模块中的 ffi 对象:

from _asdf import ffi

而不是创建一个新的 FFI 实例并重新定义恰好相同的不相关类型枚举翻译

关于python - 如何使用 Python 的 cffi 和 enum 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52999127/

相关文章:

java - QueryDSL 和 PostgreSQL 枚举?

python - Request.args 没有所有表单数据

python - 如何从具有特定要求的字典中打印键和值

python - 监控 Chrome 中的下载过程

c - 通过网络发送数字时是否必须颠倒字节顺序?

c - gtk vbox 或 hbox

用于自定义类型的 python sqlite3 适配器

python - 在Python中Merge()两个Dataframe,查看ID的重复情况

c - 警告 : Function must be extern error in C

c - MISRA 违反规则 10.1 和枚举