我将 rs232.c 构建为共享库并尝试使用 python3 调用它.但是我得到了分段错误";尝试获取 com 端口 tcgetattr() 的属性时出错.有谁知道这是什么问题?我的操作系统是树莓派 p3.
I build the rs232.c as a shared library and try to use python3 to call it. But I got the "Segmentation fault" error when try to get the attributes of com port, tcgetattr(). Anyone know what's this problem? my os system is 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 添加了一个名为error
,你的库最终混淆了两者,并试图将 tcgetattr
的返回值写入名为 error
的函数上.要修复它,请将 error
重命名为其他名称,将其声明为 static
,或将其声明移至 RS232_OpenCompport
.
The problem is that you named your variable error
and made it global. As a GNU extension, glibc adds a function named error
, and your library ends up confusing the two and trying to write the return value of tcgetattr
over the function called error
. To fix it, either rename error
to something else, declare it static
, or move its declaration inside RS232_OpenComport
.
这篇关于使用 Python ctypes 调用 rs232.c 时如何解决分段错误问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!