我使用巨大的解決方法實現了這一點。我將C和Python都讀取並寫入文件。我還沒有找到更好的選擇。
我找到了一個實際的解決方案。它由2個文件組成:「main.c」打開腳本文件「script.py」,它比較兩個字符串(這裏是:「Hello」和「Mars」)並返回較長的一個。我仍然感到奇怪的是,要達到這個目標需要20個指令,也許還有更好的解決方案。
[main.c中]
//compile me with "gcc main.c -I/usr/include/python2.7 -lpython2.7"
//original source: "http://python.haas.homelinux.net/python_kapitel_26_003.htm"
//owner is Peter Kaiser and Johannes Ernesti who published the Book "Python" under Galileo Computing
//Translation from german with many additional (and very unprofessional) comments and slight adaption by Cupacoffee, 17.02.2015.
//bugs, grammar mistakes and wrong explainations are my contribution
#include <Python.h>
int main (int argc, char *argv[])
{
char *result;//This char will receive the return value.
PyObject *module, *func, *prm, *ret;//These are some helping variables i don't understand.
Py_Initialize();
PySys_SetPath(".");//Sets the working path to the current path
module = PyImport_ImportModule("script");//Import of the script-file, note that the actual script name is "script.py"!
if (module != 0)//Asks if the script was loaded at all.
{
func = PyObject_GetAttrString(module, "compare_function");//Opens a function within the python script. Notice that you must use a function within the python script, because otherwise you can't return anything.
prm = Py_BuildValue("(ss)", "Hello", "Mars");//The "(ss)" means two strings are passed (replace with "i" for integer for instance), the "Hello" and "Mars" are the strings i pass to the script.
ret = PyObject_CallObject(func, prm);//Returns some python object i have literally no idea about ...
result = PyString_AsString(ret);// ... but luckily there's a function to cast it back to a c-compatible char*!
printf("The Script decdided that '%s' is longer!",result);
Py_DECREF(module);//cleanup?
Py_DECREF(func);//cleanup?
Py_DECREF(prm);//cleanup?
Py_DECREF(ret);//cleanup?
}
else//No script found
{
printf("Error: No script file named \"script.py\" was found!\n");
}
Py_Finalize();
return 0;
}
[script.py]
def compare_function(a, b):#this function takes 2 parameters, they are strings
return (a if min(a) < min(b) else b)#they get compared and returned to the c-program
好運。
*發牢騷,我花了2個多小時到這個文本的格式,所以我可以將它張貼。*
停止使用最高級別的功能。 – 2015-02-10 18:03:44
另外,我不確定「Return Output」的含義。 Python模塊本身不會「返回」任何東西,所以你可能意味着要在該文件中執行特定的功能,並獲得它的結果。你也可以使用各種'PySys_'函數,但是我懷疑這是你實際打算的 – 2015-02-10 22:09:25