0%

How to call Python code from C code

在Mint 15下測試,Python版本2.7.3。以下的操作步驟跟Python相關,有需要的話需要修改。
首先,先安裝python-dev

1
$ apt-get install python-dev

測試的Python code cal.py

1
2
3
4
def mix(a, b) :  
r1 = a + b
r2 = a - b
return (r1, r2)

C語言本體:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include "Python.h"
#include <string>
using namespace std;

int main(int argc, char * argv[])
{
string filename = "cal"; // cal.py
string methodname_mix = "mix"; // function name

Py_Initialize();
PyRun_SimpleString ("import sys; sys.path.insert(0, '.')");

// load the module
PyObject * pyFileName = PyString_FromString(filename.c_str());
PyObject * pyMod = PyImport_Import(pyFileName);

// load the function
PyObject * pyFunc_mix = PyObject_GetAttrString(pyMod, methodname_mix.c_str());

// test the function is callable
if (pyFunc_mix && PyCallable_Check(pyFunc_mix))
{
PyObject * pyParams = PyTuple_New(2);
PyTuple_SetItem(pyParams, 0, Py_BuildValue("i", 5));
PyTuple_SetItem(pyParams, 1, Py_BuildValue("i", 2));

// ok, call the function
int r1 = 0, r2 = 0;
PyObject * pyValue = PyObject_CallObject(pyFunc_mix, pyParams);
PyArg_ParseTuple(pyValue, "i|i", &r1, &r2);
if (pyValue)
{
printf("%d,%d\n", r1, r2); //output is 7,3
}
}

// Clean up
Py_DECREF(pyMod);
Py_DECREF(pyFileName);

Py_Finalize();

return 0;
}

編譯他

1
$ g++ pythontest.cpp -o pythontest -I/usr/include/python2.7 -lpython2.7

其中值得注意的是PyRun_SimpleString ("import sys; sys.path.insert(0, '.')");這行。這樣的話他才會在目前目錄下找cal.py這個檔案,不然會尋找/usr/lib/python2.7這個目錄。找不到會Segmentation fault。
cal.py會先被編譯成cal.pyc,之後只需要這檔案即可。

而在Visual Studio使用的時候,要注意以下情況

  • 假設你是用x86版的Python,只能使用Win32版的Setting,不然就只能使用x64版。
  • 在Windows下需要PyRun_SimpleString ("import sys; sys.path.insert(0, '.')");即可找到目錄下的cal.py。當然,放到Python27\Lib也是可以。

如果要讓事情變得更簡單,SWIG或是Boost.Python都是不錯的解決方案。

參考文章