出于研究原因,我正在尝试将 C 和 Python 结合起来,但我的代码中遇到了问题。我使用了教程中的代码,但似乎获取 python 文件的代码不起作用。这是代码:
你好类.py
def sayHello(name):
return "Hello " + name + "!"
主程序
int main(int argc, const char * argv[]) {
char name[50];
printf("What's your name?\n");
fgets(name, 64, stdin);
char *answer = NULL;
PyObject *modname, *mod, *mdict, *func, *stringarg, *args, *rslt;
Py_Initialize();
PySys_SetPath(Py_GetPath());
modname = PyString_FromString("helloClass");
mod = PyImport_Import(modname);// Here mod = null because it can´t find it.
if (mod){
mdict = PyModule_GetDict(mod);
func = PyDict_GetItemString(mdict, "sayHello");
if (func){
if (PyCallable_Check(func)) {
stringarg = PyString_FromString(name);
args = PyTuple_New(1);
PyTuple_SetItem(args, 0, stringarg);
rslt = PyObject_CallObject(func, args);
if (rslt) {
answer = PyString_AsString(rslt);
Py_XDECREF(rslt);
}
Py_XDECREF(stringarg);
Py_XDECREF(args);
}
Py_XDECREF(mdict);
Py_XDECREF(func);
}
Py_XDECREF(modname);
Py_XDECREF(mod);
}
printf("%s", answer);
answer = NULL; }