在 USC-2 下让 C 启动 Python 解释器

Have C Start Python Interpreter under a USC-2

我正在尝试 运行 Python 嵌入到一个简单的 C 程序中。但是,当我导入模块时,出现错误 undefined symbol: PyUnicodeUCS2_DecodeUTF8

经过进一步调查,我发现在 Py_Initialize(); 下启动的 Python 解释器使用 UCS-4 编码,而我尝试导入的模块使用 UCS-2 编码。我在问是否有办法用正确的编码初始化 Python 解释器。我正在使用主要使用 USC2 的 centos7 linux 系统,我不知道为什么嵌入式解释器使用 USC-4

C代码:embed.c

#include <Python.h>
int main (int argc, char *argv[]) 
{
  Py_Initialize();
  pName = PyString_FromString(argv[1]); //get name of module to import
  pModule = PyImport_Import(pName);
}

Python

print( __file__ + ": Encoding: " + str(sys.maxunicode)) #How I printed out the interpreter encoding which is 1114111
import torch

生成文件

gcc -I /usr/include/python2.7 embed.c -o embed -lpython2.7

代码编译但我收到此错误消息:undefined symbol: PyUnicodeUCS2_DecodeUTF8

无法使用正确的编码初始化解释器。解释器使用 UCS2 还是 UCS4 是 compile-time 的选择。您需要做的是从源代码重新编译整个模块。如果您没有模块的源代码,那么您必须从源代码编译 Python 2.7 并注意不要用它替换系统 python 2.7 .

UCS2 构建被认为是一个错误,因为 non-BMP 字符将表示为 UTF-16 代理项对,现在作为单独的代码点可见。这就是 Python 3 没有此 compile-time 选项的原因,因为它始终在内部使用 UCS4 来表示无法在 UCS2 中表示的字符串。