c - Python CFFI - 无法在函数调用中使用格式化的 Python 字符串作为字节数组



我正在学习如何包含用Python C编写的代码的各种方法,因为我有一个漂亮的Microchip设备的API......使用起来很乏味,我想通过为它添加一个Python包装器来让我将来的生活更轻松,这将使我更快地测试东西。一种方法是使用 cffi 模块,该模块甚至为用户提供verify(),基本上调用 C 编译器来检查提供的cdef(...)是否正确。

我写了一个小项目,以便我可以首先学习如何正确使用cffi。它由两部分组成

  1. - 用 C 编写。我相应地使用cmakemake来编译其代码:

    CMakeLists.txt

    project(testlib_for_cffi)
    cmake_minimum_required(VERSION 2.8)
    set(CMAKE_BUILD_TYPE Release)
    set(CMAKE_CXX_FLAGS "-fPIC ${CMAKE_C_FLAGS}")
    # Debug build
    set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wall -g -O0")
    # Release build
    set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Os")
    aux_source_directory(. SRC_LIST)
    add_library(testcffi SHARED ${SRC_LIST})
    # Not required for the library but needed if I want to check for memory leaks with Valgrind
    set(SRC main.c)
    add_executable(${PROJECT_NAME} ${SRC})
    target_link_libraries(${PROJECT_NAME} PUBLIC testcffi)
    

    testcffi.h

    typedef struct
    {
      double x;
      double y;
      double z;
      char *label;
    } point_t;
    // Creation, printing and deletion
    point_t* createPoint(double x, double y, double z, char *label);
    void printPoint(point_t *point);
    void deletePoint(point_t *point);
    

    testcffi.c

    #include "testcffi.h"
    #include <stdio.h>
    #include <malloc.h>
    point_t* createPoint(double x, double y, double z, char *label) {
      point_t *p = malloc(sizeof(point_t));
      p->x = x;
      p->y = y;
      p->z = z;
      p->label = label;
      return p;
    }
    void printPoint(point_t *point) {
      if(point == NULL) return;
      printf("Data:ntx : %fnty : %fntz : %fntmsg : "%s"n", point->x, point->y, point->z, point->label);
    }
    void deletePoint(point_t *point) {
      if(point == NULL) return;
      free(point);
      point = NULL;
    }
    
  2. 在 Python 中测试代码 - 代码演示了struct的用法以及上面库中的三个函数:

            #!/usr/bin/python3
            from cffi import FFI
            import random
            ffi = FFI()
            # Add library's header
            ffi.cdef('''
                typedef struct
                {
                  double x;
                  double y;
                  double z;
                  char * label;
                } point_t;
                // Creation, printing and deletion
                point_t * createPoint(double x=0., double y=0., double z=0., char *label="my_label");
                void printPoint(point_t *point);
                void deletePoint(point_t *point);
            ''')
            # Load shared object from subdirectory `build`
            CLibTC = ffi.dlopen('build/libtestcffi.so')
            def createList(length=5):
                if len:
                    lst = []
                    for i in range(0, length):
                        lst.append(CLibTC.createPoint(
                            float(random.random()*(i+1)*10),
                            float(random.random()*(i+1)*10),
                            float(random.random()*(i+1)*10),
                            b'hello'  # FIXME Why does ONLY this work?
                            # ('point_%d' % i).encode('utf-8') # NOT WORKING
                            # 'point_{0}'.format(str(i)).encode('utf-8') # NOT WORKING
                            # ffi.new('char[]', 'point_{0}'.format(str(i)).encode('utf-8')) # NOT WORKING
                        ))
                    return lst
                return None
    
            def printList(lst):
                if lst and len(lst):
                    for l in lst:
                        CLibTC.printPoint(l)
            list_of_dstruct_ptr = createList(10)
            printList(list_of_dstruct_ptr)
    

问题来自字节数组,我必须将Python字符串转换为该数组才能将数据传递到C代码中的相应位置。

上面的代码正在工作,但是我想使用其他类似于b'hello'的字符串。这就是为什么我试图在Python中使用format()(以及它的简写%)来组合一堆字母和一个数字但是。它没有成功。我要么得到""作为point_t structlabel参数的值,要么得到一个奇怪的交替垃圾数据(主要是既不是字母也不是数字的奇怪字符)。

以为我错误地使用了 encode() 函数,但是当我在 Python 交互式 shell 中对其进行测试时,我得到了与使用 b'...' 相同的输出。

知道这里发生了什么吗?


一个很好知道的问题:从我目前所读到的内容来看,cffi似乎在 Python 中使用垃圾收集来释放 C 代码中动态分配的内存。我已经用一堆点测试了它,但我想确保这种情况实际上总是如此。


更新:好的,所以似乎没有new(...)的事情确实有效,但是在这种情况下,所有值都与循环中的最后一个值相同。例如,如果循环增加到 10,则所有 Python 对象struct标签中都将包含 10。这似乎是一个参考问题。当我使用new(...)时,我得到垃圾数据。

在你的 C 代码中,point_t结构label char *,即指向内存中其他地方的指针。 如果创建 10 个 point_t 结构,它们将包含指向内存中其他位置的 10 个字符串的指针。 您必须确保只要您使用point_t结构,这 10 个字符串就保持活动状态。 CFFI无法猜测有这样的关系。 当您执行调用CLibTC.createPoint(..., some_string)时,CFFI 会在调用周围分配一个char[]数组并复制其中some_string,但此char[]内存在调用后被释放。

请改用这种代码:

c_string = ffi.new("char[]", some_string)
lst.append(createPoint(..., c_string))
keepalive.append(c_string)

其中keepalive是另一个列表,只要您需要point_t包含有效的label,您就必须确保它保持活动状态。

最新更新