問題描述
我將 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 時如何解決分段錯誤問題?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!