当我使用Python ctypes调用rs232.c时,如何解决分段错误问题



我将rs232.c构建为一个共享库,并尝试使用python3来调用它;分段故障";尝试获取com端口的属性时出错,tcgetattr((。有人知道这个问题是什么吗?我的操作系统是树莓派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添加了一个名为error的函数,您的库最终将两者混淆,并试图在名为error的函数上写入tcgetattr的返回值。要修复它,可以将error重命名为其他名称,声明为static,或者将其声明移动到RS232_OpenComport中。

最新更新