所以我有一个从 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_file
和 fp_img_free
.第二个问题可能是您的段错误的原因。看来您只是“幸运”,您的程序没有作为独立程序出现段错误。
关于python - 在python中调用C程序函数-段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62836653/