Try to make a Python module in C language

Let's make a Python module in C language

environment

Python 3.4.6 gcc version 4.8.5 openSUSE Leap 42.3

Overview

When I was studying Python, I came up with a way to make an extension module and decided to make it myself. I personally got stuck in various ways, so I'll write it here instead of a notebook.

Flow to the goal

Create Python module in C language ↓ Build C using Python ↓ Try importing with Python and using C module

Module creation in C language

First, let's create a Python module in C language. We make heavy use of the PyObject type. For the time being, I made Hello_world, push and pop.

practice.c


#include <Python.h>

//Functions created in C and used in Python use PyObject

static PyObject* 
hello_world (PyObject *self, PyObject *args) {
  printf("Hello_world\n");
  //The return of the function created on the C side is Py~~...Becomes
  Py_RETURN_NONE;
}

static PyObject*
push(PyObject *self, PyObject *args){
  PyObject *p_list, *inthert_val, *receive_list;
  //Parse the value sent
  if(!PyArg_ParseTuple(args, "O!i", &PyList_Type, &p_list, &inthert_val))
    return NULL;
  //Extract array
  receive_list = PySequence_List(p_list);
  //Add value to array
  printf("%push d\n", inthert_val);
  PyList_Append(receive_list, Py_BuildValue("i", inthert_val));
  
  //Return array
  return receive_list;
}

static PyObject*
pop (PyObject *self, PyObject *args){
  PyObject *p_list, *p_value;
  int size;
  long val;
  //Parse the value sent
  if(!PyArg_ParseTuple(args, "O!", &PyList_Type, &p_list))
    return NULL;
  //Get list size
  size = PyList_Size(p_list);
  //Extract value
  p_value = PyList_GetItem(p_list, size - 1);
  val = PyLong_AsLong(p_value);
  printf("%pop d\n", val);

  //Return value
  return p_value;
}

//Method definition
static PyMethodDef PracticeMethods[] = {
  {"hello_world", (PyCFunction)hello_world, METH_NOARGS, "practice1: hello_world"},
  {"push", (PyCFunction)push, METH_VARARGS, "practice2: push"},
  {"pop", (PyCFunction)pop, METH_VARARGS, "practice3: pop"},
  //Indicates the end
  {NULL, NULL, 0, NULL}
};

//Module definition
static struct PyModuleDef practicetmodule = {
  PyModuleDef_HEAD_INIT,
  "practice",
  NULL,
  -1,
  PracticeMethods
};

//Method initialization
PyMODINIT_FUNC PyInit_practice (void) {
  return PyModule_Create(&practicetmodule);
}

I will itemize the places I am addicted to. All I had to do was check it out, but it took a long time.

Personally, this was the best demon gate. So, if you can get over even here, the rest will be easy.

Build C using Python

As it is. Build C using Python. Specifically, use the following sources.

setup.py


from distutils.core import setup, Extension
setup(name='practice',
        version='1.0',
        ext_modules=[Extension('practice', ['practice.c'])]
)

After creating it, execute the following command to build it. This command is used when testing without installing the module.

command


python setup.py build_ext -i

Let's check.

command


ls

display


build  practice.c  practice.cpython-34m.so  setup.py

You now have a directory called build and a file called practice.cpython-34m.so. This completes the build.

Try importing with Python and using C module

I will try to see if it can actually be used. I wrote the following code.

try_module.py


import practice as c_practice
#First, operation verification
c_practice.hello_world()

# push
test_list = c_practice.push([50, 51, 52], 53)
print(test_list)

# pop
result = c_practice.pop(test_list)
print(result)

I will try it.

output


Hello_world
Push 53
[50, 51, 52, 53]
Pop 53
53

For the time being, it worked. It was good because it took quite a long time.

Recommended Posts

Try to make a Python module in C language
I made a module in C language to filter images loaded by Python
Try to calculate a statistical problem in Python
Try to make a "cryptanalysis" cipher with Python
To add a module to python put in Julialang
Try to make a dihedral group with Python
I tried adding a Python3 module in C
Make a bookmarklet in Python
Try to select a language
Try to make a command standby tool with python
Try embedding Python in a C ++ program with pybind11
To add a C module to MicroPython ...
ABC166 in Python A ~ C problem
Introduction to Protobuf-c (C language ⇔ Python)
Try to calculate Trace in Python
Solve ABC036 A ~ C in Python
How to wrap C in Python
Solve ABC037 A ~ C in Python
Try to make it using GUI and PyQt in Python
I tried to make a stopwatch using tkinter in python
I want to make input () a nice complement in python
Just try to receive a webhook in ngrok and python
Use a scripting language for a comfortable C ++ life-OpenCV-Port Python to C ++-
Solve ABC175 A, B, C in Python
[C language] [Linux] Try to create a simple Linux command * Just add! !!
Try logging in to qiita with Python
[Python] How to make a class iterable
Try to get a list of breaking news threads in Python.
How to make a string into an array or an array into a string in Python
Try to make a kernel of Jupyter
Try sending a SYN packet in Python
Try drawing a simple animation in Python
Make a relation diagram of Python module
How to get a stacktrace in python
Try to make a web service-like guy with 3D markup language
[C language] How to create, avoid, and make a zombie process
Module to generate word N-gram in Python
Generate C language from S-expressions in Python
Let's make a combination calculation in Python
Try a functional programming pipe in Python
Try to make something like C # LINQ
Try to make a capture software with as high accuracy as possible with python (2)
[Python] Try to make a sort program by yourself. (Selection sort, insertion sort, bubble sort)
[Python] [Word] [python-docx] Try to create a template of a word sentence in Python using python-docx
A note I looked up to make a command line tool in Python
How to make a request to bitFlyer Lightning's Private API in Go language
First steps to try Google CloudVision in Python
Try to implement Oni Maitsuji Miserable in python
3.14 π day, so try to output in Python
How to clear tuples in a list (Python)
Try auto to automatically price Enums in Python 3.6
How to generate permutations in Python and C ++
To execute a Python enumerate function in JavaScript
How to embed a variable in a python string
I want to create a window in Python
Ported a naive homebrew language compiler to Python
How to create a JSON file in Python
Try to draw a life curve with python
I want to make a game with Python
How to multi-process exclusive control in C language
Writing logs to CSV file (Python, C language)