1. 一個(gè)有一個(gè)參數(shù)的例子
python文件
#Filename test2.py
def Hello(s):
print "Hello, world!"
print s
cpp文件
#include <python.h>
int main()
{
Py_Initialize();
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
PyObject * pArg = NULL;
pModule = PyImport_ImportModule("test2");
pFunc = PyObject_GetAttrString(pModule, "Hello");
pArg = Py_BuildValue("(s)", "function with argument");
PyEval_CallObject(pFunc, pArg);
Py_Finalize();
return 0;
}
注意,參數(shù)要以tuple元組形式傳入。因?yàn)檫@個(gè)函數(shù)只要一個(gè)參數(shù),所以我們直接使用(s)構(gòu)造一個(gè)元組了。
2. 一個(gè)有兩個(gè)參數(shù)的例子
python文件中加入以下代碼,一個(gè)加函數(shù)
def Add(a, b):
print "a+b=", a+b
cpp文件,只改了兩行,有注釋的那兩行
#include <python.h>
int main()
{
Py_Initialize();
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
PyObject * pArg = NULL;
pModule = PyImport_ImportModule("test2");
pFunc = PyObject_GetAttrString(pModule, "Add");//終于告別hello world了,開始使用新的函數(shù)
pArg = Py_BuildValue("(i,i)", 10, 15);//構(gòu)造一個(gè)元組
PyEval_CallObject(pFunc, pArg);
Py_Finalize();
return 0;
}
其它的就類似了。。。基本上,我們知道了怎么在c++中使用python中的函數(shù)。接下來學(xué)習(xí)一下如何使用python中的
class。
附:Py_BuildValue的使用例子,來自python documentation:
Py_BuildValue("") None
Py_BuildValue("i", 123) 123
Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)
Py_BuildValue("s", "hello") 'hello'
Py_BuildValue("ss", "hello", "world") ('hello', 'world')
Py_BuildValue("s#", "hello", 4) 'hell'
Py_BuildValue("()") ()
Py_BuildValue("(i)", 123) (123,)
Py_BuildValue("(ii)", 123, 456) (123, 456)
Py_BuildValue("(i,i)", 123, 456) (123, 456)
Py_BuildValue("[i,i]", 123, 456) [123, 456]
Py_BuildValue("{s:i,s:i}",
"abc", 123, "def", 456) {'abc': 123, 'def': 456}
Py_BuildValue("((ii)(ii)) (ii)",
1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))