0

我正在学习如何包含写入代码的各种方法,C因为Python我有一个用于 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:\n\tx : %f\n\ty : %f\n\tz : %f\n\tmsg : \"%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'. 这就是为什么我尝试使用format()(连同它的缩写%) inPython来组合一堆字母和一个数字但是。它没有成功。我要么得到my 参数的""值,要么得到一个奇怪的交替垃圾数据(主要是既不是字母也不是数字的奇怪字符)。labelpoint_t struct

我以为我使用的encode()函数不正确,但是当我在Python交互式 shell 中测试它时,我得到了与 using 相同的输出b'...'

知道这里发生了什么吗?


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


更新: 好的,所以看起来没有new(...)做的事情但是在这种情况下所有的值都与循环中的最后一个值相同。例如,如果循环达到 10,那么所有structPython 对象的标签中都会包含 10。这似乎是一个参考问题。当我使用时,new(...)我得到垃圾数据。

4

1 回答 1

1

在您的 C 代码中,point_t结构保存在labela中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的 ',您必须确保该列表保持有效。

于 2016-07-10T14:49:53.860 回答