gpt4 book ai didi

python - PyUnicode_AsUTF8() 段错误

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:39 32 4
gpt4 key购买 nike

#include <Python.h>

int
main (int argc, char *argv[])
{
PyObject *pName, *pModule, *pFunc;
PyObject *pValue;

Py_Initialize ();

pName = PyUnicode_FromString ("uuid");

pModule = PyImport_Import (pName);
Py_DECREF (pName);

pFunc = PyObject_GetAttrString (pModule, "uuid4");

pValue = PyObject_CallObject (pFunc, NULL);

printf ("%s\n", PyUnicode_AsUTF8 (pValue));

Py_Finalize ();

return 0;
}

编译为

gcc test.c `python3.4-config --cflags --ldflags`

我得到了Segmentation fault。如何解决这个问题?我想要的是从 uuid4() 取回字符串。谢谢。

最佳答案

我可以通过一些修改成功地让它编译并打印出值:

#include <Python.h>
#include <stdio.h>

int
main (int argc, char *argv[])
{
PyObject *pName, *pModule, *pFunc;
PyObject *pValue;

Py_Initialize ();

pName = PyUnicode_FromString ("uuid");

pModule = PyImport_Import (pName);
Py_DECREF (pName);

pFunc = PyObject_GetAttrString (pModule, "uuid4");

pValue = PyObject_CallObject (pFunc, NULL);

PyObject_Print(pValue, stdout, Py_PRINT_RAW); // my change
printf ("\n"); // make the printout look nicer

Py_Finalize ();

return 0;
}

这是输出:

$ ./a.out
bd94cb52-9278-41a8-bc5a-ad05eff91188

我认为你的问题的原因很可能是:编译python的编译器与你用来编译测试程序test.c的编译器不一样。您可以找到正确的 gcc 版本来编译您的代码,或者简单地使用您当前的 gcc 编译器重新编译 python3.4。

至于你的原始版本的 test.c,它在我的 MBP 上给出了这个错误:

$ ./a.out
(null)
Exception ignored in: <module 'threading' from '/usr/local/Frameworks/Python.framework/Versions/3.4/lib/python3.4/threading.py'>
Traceback (most recent call last):
File "/usr/local/Frameworks/Python.framework/Versions/3.4/lib/python3.4/threading.py", line 1292, in _shutdown
t = _pickSomeNonDaemonThread()
File "/usr/local/Frameworks/Python.framework/Versions/3.4/lib/python3.4/threading.py", line 1299, in _pickSomeNonDaemonThread
for t in enumerate():
File "/usr/local/Frameworks/Python.framework/Versions/3.4/lib/python3.4/threading.py", line 1269, in enumerate
return list(_active.values()) + list(_limbo.values())
TypeError: bad argument type for built-in operation

我真的不知道发生了什么。

关于python - PyUnicode_AsUTF8() 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25440377/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com