python - Python C API Unicode 参数到 std::wstring
问题描述
在https://docs.python.org/3/extending/extending.html#keyword-parameters-for-extension-functions之后,我声明了以下函数:
PyObject* myFunction(PyObject *self, PyObject *args, PyObject *keywds) {
const wchar_t *query;
std::size_t query_len;
PyObject* py_choices;
double score_cutoff = 0;
bool preprocess = true;
static const char *kwlist[] = {"query", "choices", "score_cutoff", "preprocess", NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywds, "u#O|dp", const_cast<char **>(kwlist),
&query, &query_len, &py_choices, &score_cutoff, &preprocess)) {
return NULL;
}
PyObject* choices = PySequence_Fast(py_choices, "Choices must be a sequence of strings");
if (!choices) {
return NULL;
}
std::size_t choice_count = PySequence_Fast_GET_SIZE(choices);
std::wstring query_str(query, query_len);
for (std::size_t i = 0; i < choice_count; ++i) {
PyObject* py_choice = PySequence_Fast_GET_ITEM(choices, i);
const wchar_t *choice;
std::size_t choice_len;
if (!PyArg_Parse(py_choice, "u#", &choice, &choice_len)) {
PyErr_SetString(PyExc_TypeError, "Choices must be a sequence of strings");
Py_DECREF(choices);
return NULL;
}
std::wstring choice_str(choice, choice_len);
// do some stuff with both strings
}
Py_DECREF(choices);
Py_RETURN_NONE;
}
目标是在 python 中具有以下签名的函数
def myFunction(query: str, choices: Iterable[str], score_cutoff: float = 0, preprocess : bool = True):
在阅读了参数和命名参数后,我想将 unicode 字符串放在 std::wstring 中。
编辑:正如评论中所指出的,p
格式需要使用整数,因为 c 确实具有 bool 数据类型
解决方案
推荐阅读
- excel - 如果字段为空,VBA 循环取值
- git - 詹金斯:颤振酒吧获取,在PATH中找不到git
- powershell - 外部脚本未在 JEA PowerShell 中运行
- c# - 如何在 2 个 C# 类之间共享字符串
- bash - 以十六进制保存接下来的 32 个字节(搜索后)
- typescript - 在打字稿类中导入 p5
- java - 当 Java 进程被 OOM reaper 杀死时生成内存转储
- jpa - 使用 EmbeddedID 创建新的 JPA 实体
- javascript - 应用 JS 功能后“按钮”缩小
- javascript - 无法创建 Vue 应用程序 http-server - 错误:css 和 js 文件 404 未找到