『Python CoolBook』C擴充庫_其五_C語言層面Python庫之間調用API(待續)

來源:互聯網
上載者:User

標籤:inter   ons   之間   執行個體   使用   info   def   object   cpp   

一、C層面模組添加API

我們仍然操作如下結構體,

#include <math.h>typedef struct Point {    double x,y;} Point;

本節目標是封裝兩個Point結構體的操作函數為sample庫的C級API,可以被sample以外的C庫調用,首先寫出以下函數指標結構體執行個體,

/* pysample.c */static PyObject *PyPoint_FromPoint(Point *p, int must_free) {  /* 膠囊和C指標類似。在內部,它們擷取一個通用指標和一個名稱,可以使用      PyCapsule_New() 函數很容易的被建立。 另外,一個可選的解構函式能被     綁定到膠囊上,用來在膠囊對象被記憶體回收時釋放底層的記憶體*/  return PyCapsule_New(p, "Point", must_free ? del_Point : NULL);}/* Utility functions */static Point *PyPoint_AsPoint(PyObject *obj) {  return (Point *) PyCapsule_GetPointer(obj, "Point");}static _PointAPIMethods _point_api = {  PyPoint_AsPoint,  PyPoint_FromPoint};

結構體定義如下,位於一個新的頭函數中

/* pysample.h *//* Public API Table *//* 這裡最重要的部分是函數指標表 _PointAPIMethods.   它會在匯出模組時被初始化,然後匯入模組時被尋找到。 */typedef struct {  Point *(*aspoint)(PyObject *);  PyObject *(*frompoint)(Point *, int);} _PointAPIMethods;

 

『Python CoolBook』C擴充庫_其五_C語言層面Python庫之間調用API(待續)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.