Python 3.3 C字符串处理(wchar_t vs char)

问题描述 投票:7回答:2

我正在尝试在我们的C ++项目中嵌入Python 3.3。 Python 3.3似乎已经引入了UTF-8作为首选存储,PEP 393:“规范选择UTF-8作为向C代码公开字符串的推荐方法。”

我写了这个初始化代码,看似简单直观:

#include <Python.h>
#include "log.h"

void python_init(const char *program_name) {
    if (not Py_IsInitialized()) {
        Py_SetProgramName(program_name);
        Py_Initialize();
        const char *py_version = Py_GetVersion();
        log::msg("initialized python %s", py_version);
    }
}

但编译失败:

/home/jj/devel/openage/src/engine/python.cpp:13:3: error: no matching function for call to 'Py_SetProgramName'
                Py_SetProgramName(program_name);
                ^~~~~~~~~~~~~~~~~
/usr/include/python3.3/pythonrun.h:25:18: note: candidate function not viable: no known conversion from 'const char *' to 'wchar_t *' for 1st argument
PyAPI_FUNC(void) Py_SetProgramName(wchar_t *);
                 ^

所以,是的,显然我需要一个wchar_t *在这里,但我没有看到任何理由为什么char *不会在这里做这个工作。

这里的最佳做法是什么?将char *转换为wchar *并处理locales(mbstowcs),这也会引入不必要的动态内存分配?

此外,如果Python决定完全使用wchar,为什么Py_GetVersion()会像我预期的那样返回char *

我找到了similar question for Python <3.3 ,但我希望Python 3.3不同(PEP 393?)。

代码必须具有跨平台能力。

=>将C字符串(char *)传递给Python 3.3的快速有效的解决方案是什么?

python c++ c api python-3.x
2个回答
0
投票
// Convert a sequence of strings to an array of WCHAR pointers
PYWINTYPES_EXPORT void PyWinObject_FreeWCHARArray(LPWSTR *wchars, DWORD str_cnt);

你能用这个......?


0
投票

在Python 3.5中,Py_DecodeLocale可用于进行转换。

https://docs.python.org/3/c-api/sys.html#c.Py_DecodeLocale

© www.soinside.com 2019 - 2024. All rights reserved.