Search code examples
pythoncdllunicode

Why can't I print a Unicode character in Python from a .DLL file?


I made a .DLL project in Visual Studio (with C, not C++), and I have a function as follows:

//lib.c
void print_star() {
    printf("\u2606"); //should print: ☆
}
//lib.h
#pragma once

#ifdef LIB_EXPORTS
#define LIB __declspec(dllexport)
#else
#define LIB __declspec(dllimport)
#endif

LIB void print_star();

I then compiled it into a .DLL file with Build>Build Solution, and then imported the .DLL file into a python project in this way:

import ctypes

lib = ctypes.CDLL(r"C:\\path\\to\\lib.dll")

lib.print_star()

However, when I execute the Python code, it does not print a star, but instead just ?.
I tried putting the actual character in the source code, but I simply got this error when building:

warning C4566: character represented by universal-character-name '\u2606' cannot be represented in the current code page (1252)

What am I doing wrong here, and how do I make it print the star?


Solution

  • After a bit of searching, I have found a method that works for me.

    First, I compiled the code with UTF-8 instead of UTF-16. I went to: Project > [projectname] Properties > Configuration Properties > C/C++ > Command line, and adding '/utf-8' to the "Additional Options" textbox. (Thanks to @n. m. for that)

    Second, I changed the code in the C File to this:

    #include <io.h>
    #include <fcntl.h>
    #include <wchar.h>
    
    void print_star() {
        _setmode(_fileno(stdout), _O_U16TEXT);
        wprintf(L"%s", (wchar_t*) L"☆"); //using "\u2606" instead of the star also works
    }
    

    Thankfully, I did not have to change any of the code in the python file.