這裏是一個示例代碼,我寫的(有各種在線資源的幫助下)發送一個字符串到一個Python代碼,然後返回一個值。
這裏是C代碼call_function.c
:
#include <Python.h>
#include <stdlib.h>
int main()
{
// Set PYTHONPATH TO working directory
setenv("PYTHONPATH",".",1);
PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *presult;
// Initialize the Python Interpreter
Py_Initialize();
// Build the name object
pName = PyString_FromString((char*)"arbName");
// Load the module object
pModule = PyImport_Import(pName);
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, (char*)"someFunction");
if (PyCallable_Check(pFunc))
{
pValue=Py_BuildValue("(z)",(char*)"something");
PyErr_Print();
printf("Let's give this a shot!\n");
presult=PyObject_CallObject(pFunc,pValue);
PyErr_Print();
} else
{
PyErr_Print();
}
printf("Result is %d\n",PyInt_AsLong(presult));
Py_DECREF(pValue);
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
// Finish the Python Interpreter
Py_Finalize();
return 0;
}
這裏是Python代碼,在文件arbName.py
:
def someFunction(text):
print 'You passed this Python program '+text+' from C! Congratulations!'
return 12345
我使用命令gcc call_function.c -I/usr/include/python2.6 -lpython2.6 ; ./a.out
運行此過程。我在redhat上。我建議使用PyErr_Print();進行錯誤檢查。
你看過這樣的:HTTP:// docs.python.org/c-api/?它似乎回答你的問題。 http://docs.python.org/c-api/number.html#PyNumber_Float似乎是你要找的。它出什麼問題了?你還需要什麼? – 2010-07-20 02:04:13
真正的問題是如何從'mytest.myabs(2.0)'訪問返回的對象。一旦我有了一個指針,我可以使用PyNumber_Float函數輕鬆地將其轉換爲浮點數。 – dzhelil 2010-07-20 02:16:09
我們只能看到一個代碼示例的答案,並用它來完成嗎? – 2010-07-21 00:16:21