【问题标题】:Have C Start Python Interpreter under a USC-2让 C 在 USC-2 下启动 Python 解释器
【发布时间】:2019-07-04 20:50:00
【问题描述】:

我正在尝试运行嵌入在简单 C 程序中的 Python。但是,当我导入一个模块时,我收到了一个错误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 - 当文件与 /usr/bin/python 一起运行时会导致打印不同的值吗?

标签: python c python-embedding


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多