我有一个使用“ Python.h”将python嵌入其中的C代码,它工作正常,没有任何错误-但是它不能完全实现我想要的功能。
它的作用:C代码开始运行后,它将忽略我对python文件所做的所有更改,直到重新启动C代码为止。
我想要的是:在C代码运行时,如果我对python文件进行了更改,则它应该开始运行新代码。
在调用函数之前,我每次都尝试使用函数PyImport_ReloadModule
,但是它不起作用。难道我做错了什么 ?
我当前的代码:
#include "Strategy.h"
#undef _DEBUG /* Link with python24.lib and not python24_d.lib */
#include <Python.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
void import_py() {
pName = PyString_FromString("main");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule == NULL) {
cout << "ERR : Unable to load main.py\n";
return;
} else {
cout << "OK : Loaded main.py\n";
}
if ( PyObject_HasAttrString(pModule, "main") ) {
cout << "OK : main.py has function main\n";
} else {
cout << "ERR : main.py has no function main\n";
return;
}
pFunc = PyObject_GetAttrString(pModule, "main");
if ( pFunc == NULL ) {
cout << "OK : main.py's function main gave NULL when trying to take it\n";
return;
}
}
void remove_py() {
Py_XDECREF(pArgs);
Py_XDECREF(pModule);
Py_XDECREF(pFunc);
Py_Finalize();
}
void Construct() {
Py_Initialize();
import_py();
}
void Destruct() {
if ( pModule || pFunc ) {
remove_py();
}
}
void Loop () {
if ( ! ( pModule && pFunc ) ) {
cout << "Looped. But python values are null\n";
return;
}
cout << "Loop : ";
pArgs = PyTuple_New(2); // Create a tuple to send to python - sends 1,2
PyTuple_SetItem(pArgs, 0, PyInt_FromLong(1));
PyTuple_SetItem(pArgs, 1, PyInt_FromLong(2));
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
double t = 0; // Get the 2 return values
t = PyFloat_AsDouble(PyTuple_GetItem(pValue, 0));
cout << t << ", ";
t = PyFloat_AsDouble(PyTuple_GetItem(pValue, 1));
cout << t;
cout << "\n";
}
void main() {
Construct();
while(1) { // Using an infinite loop for now - to test
pModule = PyImport_ReloadModule(pModule);
Loop();
}
Destruct();
}
最佳答案
我发现了问题。
即使使用pModule = PyImport_ReloadModule(pModule)
获取新模块后,p
变量pFunc不会自动更新。因此,变量pFunc仍在引用旧模块!
因此,每个变量都需要重新获得。像这样:
void main() {
Construct();
while(1) { // Using an infinite loop for now - to test
pModule = PyImport_ReloadModule(pModule);
pFunc = PyObject_GetAttrString(pModule, "main");
Loop();
}
Destruct();
}
我不确定的一件事是是否应该对引用旧pModule的pFunc进行DECREF。