繁体   English   中英

当从 Python ctypes 调用并从 Spyder 或 Pyzo 运行时,strtod 返回错误值

[英]strtod returns wrong value when called from Python ctypes and run from Spyder or Pyzo

我需要从 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

仅转换 integer 部分,并使用逗号而不是点作为小数分隔符。 我怀疑是编码问题。 我在 Python 脚本中尝试'356.5684'.encode('ascii') ,但问题仍然存在。

你有什么想法吗?

谢谢卡米尔库克。 问题解决了。 我在这里遵循了“标准”部分: https://wiki.debian.org/Locale

我生成了语言环境en_US.utf8 ,然后将其选为默认值。 重新启动,现在从字符串到双精度的转换工作,即使使用 Spyder 和 Pyzo。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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