回覆列表
  • 1 # 世界中心的飼養員

    下面是一個例子:

    首先是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

  • 中秋節和大豐收的關聯?
  • 快熱式電熱水器的故障有哪些解決辦法?