C API из модуля расширения в Python | Комплект 2

Опубликовано: 12 Апреля, 2022

Предварительное условие: C API из модуля расширения в Python | Комплект 1

Давайте посмотрим на пример нового модуля расширения, который загружает и использует эти функции API, которые мы создали в предыдущей статье.

Code #1 :

#include "pythonsample.h"
/* An extension function that uses the exported API */
static PyObject *print_point(PyObject *self, PyObject *args)
{
    PyObject *obj;
    Point *p;
    if (!PyArg_ParseTuple(args, "O", &obj))
    {
        return NULL;
    }
    /* Note: This is defined in a different module */
    p = PyPoint_AsPoint(obj);
    if (!p)
    {
        return NULL;
    }
    printf("%f %f ", p->x, p->y);
    return Py_BuildValue("");
}
  
static PyMethodDef PtExampleMethods[] =
{
    {"print_point", print_point, METH_VARARGS, "output a point"},
    { NULL, NULL, 0, NULL}
};
  
static struct PyModuleDef ptexamplemodule =
{
    PyModuleDef_HEAD_INIT,
    /* name of module */
    "ptexample"
    /* Doc string (may be NULL) */
    "A module that imports an API"
    /* Size of per-interpreter state or -1 */
    -1, 
    /* Method table */
    PtExampleMethods 
      
};

 
Code #2 : Module initialization function

PyMODINIT_FUNC
PyInit_ptexample(void)
{
    PyObject *m;
      
    m = PyModule_Create(&ptexamplemodule);
      
    if (m == NULL)
        return NULL;
      
    /* Import sample, loading its API functions */
    if (!import_sample())
    {
        return NULL;
    }
      
    return m;
}

Now to compile this new module, one need not bother about how to link against any of the libraries or code from the other module. One can just simply use work.py file as shown below.

Code #3 :

# setup.py
from distutils.core import setup, Extension
  
# May need pythonsample.h directory
setup(name ="ptexample"
      ext_modules = [ Extension("ptexample"
                     ["ptexample.c"], include_dirs = [], )])

После выполнения всей этой задачи эта новая функция расширения отлично работает с функциями C API, определенными в другом модуле.

Code #4 : Using CPI API functions defined in the other module

import ptexample
import work
  
point1 = work.Point(2, 3)
print ("Point_1 : ", point1)
  
print (" ", ptexample.print_point(p1))

Выход :

Пункт_1: 

2.000000 3.000000

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.