首页 > 解决方案 > 与 ctypes 一起使用时,串行通信共享库发送错误数据

问题描述

我已经构建了一个简单的串行通信共享库,我正在尝试使用 ctypes 库在 python 中使用它。我遵循的步骤是:

  1. 通过调用 ctypes.cdll.loadlibrary() 加载 .so 文件。
  2. 初始化串行通信模块。
  3. 发送 0xFF 作为同步字节。

当我执行上述步骤时,我不会只在另一端获得垃圾数据。有趣的是,当我在 C 中使用 .so 文件并执行相同的操作时,它工作得非常好。所以我的问题是 ctypes 模块是否以任何方式操纵加载的库?我对在 Python 中使用 C 非常陌生,我在这里画空白。任何建议都会非常有帮助。

#!/usr/bin/env python3
import ctypes
test_lib = ctypes.cdll.LoadLibrary("./demo_static.so")
string2 = "/dev/ttyS2"
# create byte objects from the strings
UART_RIGHT = string2.encode('utf-8')
baud = 500000
test_lib.serial_com_init(0, UART_RIGHT, baud)

(相关)C代码:

int serial_com_init(char *left, char *right, int baudrate) {
    int fd_l, fd_r;
    uart_t uart_left, uart_right;
    uint8_t flags_l, flags_r;
    if (left) {
        fd_l = uart_init_linux(left, baudrate);
        uart_left->fd = fd_l;
    }
    if (right) {
        fd_r = uart_init_linux(right, baudrate);
        uart_right->fd = fd_r;
    }
    serial_com_init_cr(uart_left, uart_right, flags_l, flags_r); 
    serial_com_hello_init();
    return 0;
}

标签: python-3.xctypes

解决方案


根据[Python]: ctypes: Specifying the required argument types (function prototypes),对于像这样的函数:

int serial_com_init(char *left, char *right, int baudrate);

您需要指定参数类型(函数调用之前)。这对 64 位Python产生了至关重要的影响:

test_lib.serial_com_init.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int]
init_result = test_lib.serial_com_init(None, UART_RIGHT, baud)

备注

  • 这是可能的原因之一
  • 始终检查函数返回代码(好吧,这里它总是0,这可能会隐藏C代码中的错误)
  • 您可以直接使用字节文字:UART_RIGHT = b"/dev/ttyS2"

推荐阅读