4

所以我有一个从 Python 运行的 C 程序。但是我收到分段错误错误。当我单独运行 C 程序时,它运行良好。C 程序使用 fprint 库连接指纹传感器。

#include <poll.h>
#include <stdlib.h>
#include <sys/time.h>
#include <stdio.h>
#include <libfprint/fprint.h>



int main(){

struct fp_dscv_dev **devices;
struct fp_dev *device;
struct fp_img **img;

int r;
r=fp_init();

if(r<0){
    printf("Error");
    return 1;
}

devices=fp_discover_devs();
if(devices){
    device=fp_dev_open(*devices);

    fp_dscv_devs_free(devices);
}
if(device==NULL){
    printf("NO Device\n");
    return 1;
}else{
    printf("Yes\n");
   
}


int caps;

caps=fp_dev_img_capture(device,0,img);

printf("bloody status %i \n",caps);

    //save the fingerprint image to file. ** this is the block that 
     causes the segmentation fault.

    int imrstx;
    imrstx=fp_img_save_to_file(*img,"enrolledx.pgm");
    fp_img_free(*img);


fp_exit();
return 0;
}

蟒蛇代码

from ctypes import *
so_file = "/home/arkounts/Desktop/pythonsdk/capture.so"
my_functions = CDLL(so_file)

a=my_functions.main()
print(a)
print("Done")

capture.so 是在 python 中构建和访问的。但是从 python 调用,我得到一个分段错误。我的问题可能是什么?

非常感谢

4

1 回答 1

4

尽管我对libfprint不熟悉,但在查看了您的代码并将其与文档进行比较后,我发现您的代码存在两个问题,这两个问题都可能导致分段错误:


首要问题:

根据函数的文档,fp_discover_devs错误NULL返回。成功时,返回一个以 NULL 结尾的列表,该列表可能为空。

在以下代码中,您检查失败/成功,但不检查空列表:

devices=fp_discover_devs();
if(devices){
    device=fp_dev_open(*devices);

    fp_dscv_devs_free(devices);
}

如果devices为非 NULL,但为空,则devices[0](相当于*devices)为 NULL。在这种情况下,您将此 NULL 指针传递给fp_dev_open. 这可能会导致分段错误。

不过,我认为这不是您的分段错误的原因,因为只有在返回空列表时才会触发代码中的此错误。


第二题:

的最后一个参数fp_dev_img_capture应该是指向已分配类型变量的指针struct fp_img *。这告诉函数它应该写入的变量的地址。然而,随着代码

struct fp_img **img;
[...]
caps=fp_dev_img_capture(device,0,img);

您正在向该函数传递一个野指针,因为img它不指向任何有效对象。一旦函数取消引用野指针或导致某种其他类型的未定义行为,例如覆盖程序中的其他变量,这可能会导致分段错误。

我建议您改为编写以下代码:

struct fp_img *img;
[...]
caps=fp_dev_img_capture(device,0,&img);

现在第三个参数指向一个有效对象(指向变量img)。

由于img现在是单指针而不是双指针,因此您必须传递img而不是传递*img给函数fp_img_save_to_filefp_img_free.

第二个问题可能是您的分段错误的原因。您的程序没有作为独立程序出现段错误似乎只是“幸运”。

于 2020-07-11T01:16:30.350 回答