python - 在python中调用C程序函数-段错误

标签 python c pointers ctypes digital-persona-sdk

所以我有一个从 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 调用,我得到了一个段错误。我的问题可能是什么?
非常感谢

最佳答案

虽然我不熟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 .
第二个问题可能是您的段错误的原因。看来您只是“幸运”,您的程序没有作为独立程序出现段错误。

关于python - 在python中调用C程序函数-段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62836653/

相关文章:

python - Pandas read_csv() 给出 DtypeWarning

c - 与指针比较数组末尾后的一个元素是否定义明确?

c - 为什么 register_tm_clones 和 deregister_tm_clones 引用的地址超过 .bss 部分?这个内存分配在哪里?

c - 结构内部定义的 MACRO 的范围是什么?

c - 如何在任务/线程之间共享数据而不耦合它们?

pointers - 将指针字段分配给强制转换的值

c - cir.radius 和 (cir.radius) 之间的差异

python - 存储子图的非浪费方式

java - 运行一个包含 R 脚本的文件夹,每个脚本都在不同的 R 实例中

python ttk TreeView : Different background or font color for values in item