Search code examples
c++python-3.xvisual-c++python-c-api

PyRun_SimpleString failing for special characters


I was trying Basics embedding Python in C++ and when i run this code i get error "SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xf4 in position 10 : invalid continuation byte". I am not able to figure out what's wrong in this. I encoded this txt on Pycharm it worked perfectly fine but not when i try to embed this with C++. Thanking in advance for the help

PyObject* pInt;

    Py_Initialize();

    PyRun_SimpleString("txt = u\"flag_for_Côte_d’Ivoire\"\nx = txt.encode()\nprint(x)");

    Py_Finalize();

    printf("\nPress any key to exit...\n");
    if(!_getch()) _getch();
    return 0;

if i only do

PyRun_SimpleString("txt = u\"flag_for_Côte_d’Ivoire\"")

it fails for that too. Python Version which i am using is Python 3.7.3 and on windows VS 2008


Solution

  • Before Sending the string converted string to UTF8 and passed to Pyrun_simplestring() and it worked. So if you are working on older version of VS do as said and if you are working on new VS you need to add "#define PY_SSIZE_T_CLEAN" before Python.h

    NOTE:-This solution is for those people who are working on Python 3