【问题标题】:calling C program function in python - Segmentation fault在python中调用C程序函数 - 分段错误
【发布时间】:2020-10-31 08:02:18
【问题描述】:

所以我有一个从 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;
}

python 代码

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 调用,我得到一个分段错误。我的问题可能是什么?

非常感谢

【问题讨论】:

    标签: python c pointers ctypes digital-persona-sdk


    【解决方案1】:

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


    第一期:

    根据documentation of the function 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);
    

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

    我建议你改写以下代码:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 2010-12-05
      • 2021-02-25
      • 1970-01-01
      相关资源
      最近更新 更多