$ cc -o demo demo.c $(python-config --cflags) $(python-config --ldflags)
$ ./demo
hello: 1
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'greet' is not defined
hello: 3
$ cat demo.c
#include <Python.h>
int main(int argc, char *argv[])
{
PyThreadState *py1, *py2;
Py_Initialize();
py1 = Py_NewInterpreter();
PyRun_SimpleString("def greet(a):\n\tprint 'hello: ' + str(a)\n");
PyRun_SimpleString("greet(1)\n");
py2 = Py_NewInterpreter();
PyRun_SimpleString("greet(2)\n");
PyThreadState_Swap(py1);
PyRun_SimpleString("greet(3)\n");
Py_Finalize();
return 0;
}
【 在 oldsmthnet (oldsmthnet) 的大作中提到: 】
: 需要在C/C++里多线程调用Python,希望每个子线程有独立的interpreter,需要怎样调用Python C API?
: 环境是Win10 + Python 3.8。
: 谢谢!
--
FROM 27.38.249.*