0

I'm trying to get in a Visual Studio 2012 C++ program the value of a string variable defined in a embedded Python environment using Python's C API.

As embedded environment, I'm using Python 3.4.3 64-bit, which I downloaded from https://www.python.org/downloads/

This is the code I'm using in Visual Studio 2012 (target: Release, x64):

#include <Python.h>

int _tmain(int argc, _TCHAR* argv[])
{

  Py_Initialize();

  PyObject *main = PyImport_AddModule("__main__");
  PyObject *globals = PyModule_GetDict(main);
  PyRun_SimpleString("my_var = 'Hello, World!'; print('Value of my_var in Python: ' +  my_var)");

  PyObject* value = PyDict_GetItemString(globals, "my_var");
  wchar_t* fetched_value = PyUnicode_AsWideCharString(value, NULL);
  Py_DECREF(value);

  wchar_t result[20];
  wcscpy_s(result, 19, fetched_value);
  PyMem_Free(fetched_value);

  printf("Value of my_var in C: %s", result);

  Py_Finalize();

  return 0;
}

When I run this code, I get this output:

Value of my_var in Python: Hello, World!
Value of my_var in C: H

Why am I getting only the first character of Hello, World! in my call to PyUnicode_AsWideCharString(value, NULL);?

Pep
  • 1,957
  • 2
  • 24
  • 40

1 Answers1

3

The %s format specifier denotes a narrow string (char*). You want %ls, which denotes a wide string (wchar_t*):

printf("Value of my_var in C: %ls", result);

You should also be preferring wprintf; it's not a good idea to mix narrow and wide strings, as you're doing here.

Collin Dauphinee
  • 13,664
  • 1
  • 40
  • 71