C语言调用python3教程

首先得安装对应python不同版本的调用库,在ubuntu环境下执行:
    sudo apt-get install python3.5-dev 
之后在ide中加上-lpython3.5m 注意要对应版本

如果是采用makefile,则在编译时加上 -lpython3.5m 

  • Python文件
# hello.py
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()
  • C语言文件
// pyapi.c
#include 
#include 
#include 
#include 

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
  • 1

你可能感兴趣的:(Linux嵌入式)