Python Unicode 对象和 C API(从 pyunicode 对象中检索 char*)

标签 python string unicode binding ascii

我目前正在将我所有的 C++ 引擎类绑定(bind)到 python 以用于游戏脚本编写。 最新的挑战是,当假设您在脚本中将变量设为字符串时,例如

string = 'hello world'

这成为一个 PyUnicodeObject。接下来,我们要从绑定(bind)的 C 端函数调用脚本中此对象的函数。 PrintToLog( string ),举个例子,假设这个 c 函数是这样的

void PrintToLog( const char * thisString )
{
   //file IO stuff as expected
   myLog << thisString;
   //more stuff involving fileIO
}

所以我的绑定(bind)需要从 PyUnicodeObject 中提取一个 char * ,它首先由 python 传递给我的通用函数处理程序,后者又将 pyobjects 提取并转换为正确的 c 端类型并将其传递给我的功能。

我能找到的唯一函数是提取一个 wchar_t*... 因为我们将只使用 ascii 字符集,所以无论如何都可以获得 ascii 表示。

编辑:我使用的是 Python 3.2,其中所有字符串都是 unicode

最佳答案

我在使用 Python3 时遇到了类似的问题。我是这样解决的。

如果你有一个 PyUnicodeObject “mystring”,做类似的事情

PyObject * ascii_mystring=PyUnicode_AsASCIIString(mystring);
PrintToLog(PyBytes_AsString(ascii_mystring));
Py_DECREF(ascii_mystring);

PyBytes 解释 here .

关于Python Unicode 对象和 C API(从 pyunicode 对象中检索 char*),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6783493/

相关文章:

c - 在函数中传递字符串 (C)

python - Django - 使用自定义的 login_required 装饰器保护 Apache 提供的媒体文件

javascript - 如何拆分和分配 2 个单词?

python - 根据单选按钮答案更改框架

php 大括号和字符串

PYTHON:将 unicode 附加到列表会将其类型更改为 str

c# - 我如何在 C# 中读写智能引号(和其他愚蠢的字符)

javascript - Node.js 源代码需要什么编码?

Python - 在没有 python 解释器的情况下运行 numpy

python - 连接 Python 列表时出现问题