I need to call from a Python script a C library which parses a string to a double and prints the result.
The parsing works or not depending on the IDE I use. My OS is Debian 11. Here is a minimal example.
The library (file 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));
}
It is compiled in a terminal with:
gcc -shared -o test.so -Wall test.c
The Python script calls the library and passes the string parameter using ctypes (file 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'))
I run this script from a terminal with
python3 test.py
and I get
Argument as string: 356.5684
Argument converted to double: 356.568400
It works as expected. When I run this script with Eric-ide, it works too. However, when I run this script with Spyder or Pyzo, I get:
Argument as string: 356.5684
Argument converted to double: 356,000000
Only the integer part is converted and a comma is used as the decimal separator instead of a dot. I suspect an encoding issue. I tried '356.5684'.encode('ascii') in the Python script, but the problem remains.
Have you got any ideas?
Thanks KamilCuk. Problem solved. I followed the section "Standard" here: https://wiki.debian.org/Locale.
I generated the locale
en_US.utf8and then chose it as default. Reboot, and now the conversion from string to double works, even with Spyder and Pyzo.