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 时如何解决分段错误问题?
基础教程推荐
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
