Search code examples
c++11unicodepycharmpybind11

Unicode problem when using cppimport/pybind11


I am trying to use cppimport, an lib based on pybind11, to import some *.cpp files directly into python, according to the author's example.

I am using Pycharm and python 3.7, installed both cppimport and pybind11, win10.
The import code is quite easy using cppimport.

import cppimport.import_hook
import DemoTrade

Then I got an error

mako.exceptions.CompileException: Unicode decode operation of encoding 'ascii' failed in file 'C:\Users\...\DemoTrade.cpp' at line: 0 char: 0

The files address is right, otherwise it will give another error

The problem seems in the coding of files, I changed other encoding, but nothing improved.
I don't know how to deal with this. Thank you for your help.


Solution

  • Since cppimport is based on pybind11 and mako, this is a mako problem.

    in cppimport lib, find templating.py.

    Then add the encode you want in mako.template.Template(). Following is an example

    mako.template.Template(filename = filepath, lookup = lookup,
                          input_encoding='gb2312', output_encoding='gb2312') 
    

    Then it is solved.