简体   繁体   中英

How to solve the segmentation fault issue when I use Python ctypes to call rs232.c?

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;
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM