首先是python的一个简单函数
class Hello:
def __init__(self, x):
self.a = x
def print(self, x=None):
print(x)
def xprint():
print("hello world")
if __name__ == "__main__":
xprint()
h = Hello(5)
h.print()1
下面是C语言
#include <python3.4m/Python.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
Py_Initialize()
// 将当前目录加入sys.path
PyRun_SimpleString("import sys")
PyRun_SimpleString("sys.path.append('./')")
// 导入hello.py模块
PyObject *pmodule = PyImport_ImportModule("hello")
// 获得函数xprint对象,并调用,输出“hello world\n”
PyObject *pfunc = PyObject_GetAttrString(pmodule, "xprint")
PyObject_CallFunction(pfunc, NULL)
// 获得类Hello并生成实例pinstance,并调用print成员函数,输出“5 6\n”
PyObject *pclass= PyObject_GetAttrString(pmodule, "Hello")
PyObject *arg = Py_BuildValue("(i)", 5)
PyObject *pinstance = PyObject_Call(pclass, arg, NULL)
PyObject_CallMethod(pinstance, "print", "i", 6)
Py_Finalize()
return 0
}
编译命令如下:
gcc pyapi.c -lpython3.4m -o pyapi
可以的。C中内嵌Python
新建立一个工程,首先需要将工作目录设置到Python-3.1.1PCbuild中,以获取到动态库,至于静态库的包含,Include目录的指定,那自然也是少不了的。文件中需要包含Python.h文件,这也是必须的。
接口中
Py_Initialize()
Py_Finalize()
其他的根据需求,再引入相应的python builder 即可