How to solve the segmentation fault issue when I use Python ctypes to call rs232.c?(使用 Python ctypes 调用 rs232.c 时如何解决分段错误问题?)
问题描述
我将 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 时如何解决分段错误问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Python ctypes 调用 rs232.c 时如何解决分段错误问题?


- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01