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

2024-04-28 21:19:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我将rs232.c构建为一个共享库,并尝试使用python3调用它。但是我在尝试获取com端口tcgetattr()的属性时遇到了“分段错误”。有人知道这是什么问题吗? 我的操作系统是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;
}

Tags: numberincluders232erroroldintcomportchar
1条回答
网友
1楼 · 发布于 2024-04-28 21:19:54

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

相关问题 更多 >