如何解决使用Python ctypes 调用rs232.c 时的段错误问题?

How to solve the segmentation fault issue when I use Python ctypes to call rs232.c?

我将 rs232.c 构建为共享库并尝试使用 python3 调用它。但是当我尝试获取 com 端口的属性 tcgetattr() 时,出现了“Segmentation fault”错误。任何人都知道这是什么问题? 我的 os 系统是 raspberry pi p3.

testcom.py

from ctypes import *
comdll = cdll.LoadLibrary("rs232.so")
comdll.RS232_OpenComport(c_int(22),c_int(115200),c_char_p(b'8N1'))

rs232.c

#include <termios.h>
#include <unistd.h>
#define RS232_PORTNR  39
int Cport[RS232_PORTNR],error;
struct termios old_port_settings[RS232_PORTNR];

int RS232_OpenComport(int comport_number, int baudrate, const char *mode)
{
    error = tcgetattr(Cport[comport_number], old_port_settings + comport_number); //segmentation fault at this line
    return error;
}

问题是您将变量命名为 error 并使其成为全局变量。作为 GNU 扩展,glibc adds a function named error,您的库最终混淆了两者并试图在名为 error 的函数上写入 tcgetattr 的 return 值。要修复它,请将 error 重命名为其他名称,将其声明为 static,或者将其声明移动到 RS232_OpenComport.