python-3.x - 与 ctypes 一起使用时,串行通信共享库发送错误数据
问题描述
我已经构建了一个简单的串行通信共享库,我正在尝试使用 ctypes 库在 python 中使用它。我遵循的步骤是:
- 通过调用 ctypes.cdll.loadlibrary() 加载 .so 文件。
- 初始化串行通信模块。
- 发送 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]: 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"
推荐阅读
- sql - SQL Server 代理作业和 SSIS 项目
- javascript - 引导卡页脚通过滑动动画上下移动
- mysql - SQL:计算行数并返回最大计数的所有行:无效使用组函数
- php - Laravel 6.18.2:Process 类依赖于 proc_open,这在您的 PHP 安装中不可用
- apache-poi - 如何验证 apache poi 中的列、行或单元格是否在一个组中以及它是否折叠
- python - python中菱形数组的数据结构
- wso2 - POST、PUT 和 PATCH 资源在 WSO2 Api 网关中不起作用
- rest - 反应管理员:
卡在加载状态,即使数据获取成功 - python - 拥有“符合 RFC 标准”的代码是什么意思?
- python-3.x - 如何将其他人的 Google 电子表格添加到我的 Pandas 数据框中?