我这样写 C 源代码,旨在用 C 加速 Python 代码,所以我在 C 中包含了一些 py 对象和 func:
- 包括头文件
Python.h
和动态链接文件libpython3.8.so
。
// test.h
#include "Python.h"
#include <stdio.h>
// test.c
void main(){
PyObject *bigrams1 = PySet_New(0);
ret = PySet_Add(bigrams, PyUnicode_FromWideChar(L"nc", 2));
ret = PySet_Add(bigrams, PyUnicode_FromWideChar(L"ckd", 3));
ret = PySet_Add(bigrams, PyUnicode_FromWideChar(L"nc.3e", 5));
// and I check the following if the nc string in in bigrams:
ret = PySet_Contains(bigram, PyUnicode_FromWideChar(L"nc", 2));
}
- 在这段代码中,我创建了一个 Python
set
对象并向其添加三个字符串,'nc', 'ckd', 'nc.3e'
. 添加到集合中的字符串是随机的,这不是问题的关键。 - 当我检查与 func
if 'nc' in bigram
相对应的时PySet_Contains
,正在运行的代码会损坏。
./test: line 10: 2976044 Segmentation fault
但是当我nc
像其他人一样更改为其他字符串时'ok', 'ckd', 'project'
,代码运行正常。只有nc
引起的错误。
代码和奇怪的字符串有什么问题nc
?
附加说明
- 我都试过了
Python3.8
,Python3.11
结果是一样的。 - 我尝试了数千个其他字符串,例如
'中国', 'few', '$$####', '1e32e2'
,所有其他字符串都运行良好。 - 那是奇怪的字符串
'nc'
。