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

2023-03-12Python开发问题
4

本文介绍了使用 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 时如何解决分段错误问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10