我需要从 Python 脚本调用一个 C 库,它将字符串解析为双精度并打印结果。
解析是否有效取决于我使用的 IDE。我的操作系统是 Debian 11。这是一个最小的例子。
库(文件 test.c):
#include <stdio.h>
#include <stdlib.h>
void func(char * c){
printf("Argument as string: %s\n",c);
printf("Argument converted to double: %lf\n",strtod(c,NULL));
}
它在终端中编译:
gcc -shared -o test.so -Wall test.c
Python 脚本调用库并使用 ctypes(文件 test.py)传递字符串参数:
# -*- coding: utf-8 -*-
import ctypes as ct
# Load the library
lib = ct.cdll.LoadLibrary("./test.so")
# Run my function
lib.func('356.5684'.encode('utf8'))
我从终端运行这个脚本
python3 test.py
我得到
Argument as string: 356.5684
Argument converted to double: 356.568400
它按预期工作。当我用 Eric-ide 运行这个脚本时,它也可以工作。但是,当我使用 Spyder 或 Pyzo 运行此脚本时,我得到:
Argument as string: 356.5684
Argument converted to double: 356,000000
仅转换整数部分,并使用逗号而不是点作为小数分隔符。我怀疑是编码问题。我在 Python 脚本中尝试过'356.5684'.encode('ascii')
,但问题仍然存在。
你有什么想法吗?