2009年2月12日 星期四

Embedded Python

我是依thinker的文章(Embedded Python 之一)來作學習。
連結:http://heaven.branda.to/~thinker/GinGin_CGI.py/show_id_doc/234
原始的程式碼
#foo.py
def hello(a, b):
return a + b
#include <Python.h>
#include <stdio.h>

int main() {
PyObject *foo;
PyObject *hello, *ro;
int r;

Py_Initialize();
foo = PyImport_ImportModule("foo");
hello = PyObject_GetAttrString(foo, "hello");
ro = PyObject_CallFunction(hello, "ii", 15, 20);
r = PyInt_AsLong(ro);

printf("result is %d\n", r);

Py_DECREF(ro);
Py_DECREF(hello);
Py_DECREF(foo);
Py_Finalize();
}
因為執行環境是mac
所以先將
#include <python.h>
#include <python2.5/python2.5>
編譯時記得連結 -lpython2.5
編譯完成候執行時,一直說Bus error。
這是因為PYTHONPATH的問題。
解決發法如下。
Py_Initialize();
//只要利用PySys_SetPath,就可以設定PYTHONPATH
PySys_SetPath("py檔路徑");
foo = PyImport_ImportModule("foo");
hello = PyObject_GetAttrString(foo, "hello");
ro = PyObject_CallFunction(hello, "ii", 15, 20);
r = PyInt_AsLong(ro);
但是問題來了:
我在terminal下./tool(我的執行檔)可以正常工作,但是在tool的圖示點二下,卻在PyObject_GetAttrString的地方,顯示bus error。這是為甚麼?
Thinker said ..
可能和 current working directory 有關或環境變數有關係,請檢查透過桌面執行時的 current working directory 和相關的環境變數。
(在此,再次感謝thinker的協助)
所以還是老問題PYTHONPATH,只好在程式執行是動態來判斷路徑。
整個主程式如下:
#include <Python2.5/Python.h>
#include <stdio.h>
//將SCRIPT_PATH設定成py檔和執行檔的相對路徑
#define SCRIPT_PATH "/"
int main(int argc, char* argv[]) {
char pch[1024]={0};
char scriptpath[1024]={0};
int i=strrchr(argv[0],'/')-argv[0];
strncpy (pch,argv[0],i);
strcpy(scriptpath,SCRIPT_PATH);
strcat(pch,scriptpath);

PyObject *foo;
PyObject *hello, *ro;
int r;

Py_Initialize();
PySys_SetPath(pch);
foo = PyImport_ImportModule("foo");
hello = PyObject_GetAttrString(foo, "hello");
ro = PyObject_CallFunction(hello, "ii", 15, 20);
r = PyInt_AsLong(ro);

printf("result is %d\n", r);

Py_DECREF(ro);
Py_DECREF(hello);
Py_DECREF(foo);
Py_Finalize();
}

沒有留言: