C language to see and remember Part 5 Call C language from Python (argument) Array

Pass an array of floats from Python and return the sum and average in tuples.

capi.py


import myModule as capi
import random
x=[random.uniform(0, 100) for x in range(100)]
s=0.0
for a in x:
    s=s+a
print("c ",s,s/len(x))
a=capi.fsum_avr(x)
print("py",a)

When you run
>python capi.py
py 5025.24247203747 50.252424720374705
c  (5025.24247203747, 50.252424720374705)

capilib.c


#include <Python.h>
static PyObject* fsum_avr(PyObject* self, PyObject* args)
{
    long n;
    double sum=0.0,avr,a;
    PyObject* c_list, *item;
    if (!PyArg_ParseTuple(args, "O", &c_list)) return NULL;   
    // Check list
    if PyList_Check(c_list) n = PyList_Size(c_list);
    else return NULL;
    for (int i = 0; i < n; i++){
        item = PyList_GetItem(c_list, i);
        a = PyFloat_AsDouble(item); // Increment the reference count
        sum = sum + a;
        Py_DECREF(item); // Decrement the reference count
    }
    avr=sum/n;
    return Py_BuildValue("(dd)",sum,avr);
}
static PyMethodDef myMethods[] = {
    { "fsum_avr",fsum_avr, METH_VARARGS, "sum avr"},
    { NULL }
};
static struct PyModuleDef myModule = {
    PyModuleDef_HEAD_INIT,"myModule","C API Module",-1,myMethods
};
PyMODINIT_FUNC PyInit_myModule(void){
    return PyModule_Create(&myModule);
}

** Attention point **

  1. PyArg_ParseTuple (args, "O", & c_list) sets the address to & c_list by "O" in the list array. O (object) [PyObject *] Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. The object's reference count is not increased. The pointer stored is not NULL.
  2. return Py_BuildValue ("(dd)", sum, avr); returns the sum and average as tuples.

Please see the link for ** Argument Interpretation and Value **.

setup.py


from distutils.core import setup, Extension
setup(name = 'myModule', version = '1.0.0',  \
   ext_modules = [Extension('myModule', ['capilib.c'])])

** Creating a library **

capi>python setup.py install

Recommended Posts

C language to see and remember Part 5 Call C language from Python (argument) Array
C language to see and remember Part 2 Call C language from Python (argument) string
C language to see and remember Part 3 Call C language from Python (argument) c = a + b
C language to see and remember Part 1 Call C language from Python (hello world)
Go language to see and remember Part 8 Call GO language from Python
Go language to see and remember Part 7 C language in GO language
Call c language from python (python.h)
Call C language functions from Python to exchange multidimensional arrays
[Python] How to call a c function from python (ctypes)
Call Matlab from Python to optimize
Call C from Python with DragonFFI
Python to switch from another language
Call C / C ++ from Python on Mac
[Python] Hit Keras from TensorFlow and TensorFlow from c ++ to speed up execution
Call your own C language shared library from Python using ctypes
[It's not too late to learn Python from 2020] Part 3 Python Language Basic (1)
From Python to using MeCab (and CaboCha)
Porting and modifying doublet-solver from python2 to python3.
Socket communication by C language and Python
Generate C language from S-expressions in Python
Try porting the "FORTRAN77 Numerical Computing Programming" program to C and Python (Part 1)
How to generate permutations in Python and C ++
Create a C array from a Python> Excel sheet
Writing logs to CSV file (Python, C language)
[Python] How to read data from CIFAR-10 and CIFAR-100
Try porting the "FORTRAN77 Numerical Computing Programming" program to C and Python (Part 3)
Call Rust from Python to speed it up! PyO3 Tutorial: Wrapping Classes Part ➀
Try porting the "FORTRAN77 Numerical Computing Programming" program to C and Python (Part 2)
Call Rust from Python to speed it up! PyO3 Tutorial: Wrapping Classes Part ➁
Call a Python script from Embedded Python in C ++ / C ++
List of Python code to move and remember
I want to make C ++ code from Python code!
An easy way to call Java from Python
The story of porting code from C to Go and getting hooked (and to the language spec)
Pass an array from PHP to PYTHON and do numpy processing to get the result
Try to make a Python module in C language
Changes from Python 2 to Python 3.0
Introduction to Python language
Call Rust from Python to speed it up! PyO3 Tutorial: Wrapping a Simple Function Part ➀
Call Rust from Python to speed it up! PyO3 Tutorial: Wrapping a Simple Function Part ➁
[Introduction to cx_Oracle] (Part 6) DB and Python data type mapping
How to slice a block multiple array from a multiple array in Python
How to swap elements in an array in Python, and how to reverse an array.
Python regular expression basics and tips to learn from scratch
I tried to illustrate the time and time in C language
Object-oriented in C: Refactored "○ ✕ game" and ported it to Python
Use a scripting language for a comfortable C ++ life-OpenCV-Port Python to C ++-
How to call Python or Julia from Ruby (experimental implementation)
Cheating from PHP to Python
Anaconda updated from 4.2.0 to 4.3.0 (python3.5 updated to python3.6)
Switch from python2.7 to python3.6 (centos7)
Connect to sqlite from python
Ported from R language of "Sazae-san's rock-paper-scissors data analysis" to Python
Solving AOJ's Algorithm and Introduction to Data Structures in Python -Part1-
[First Ripple] [I am] Call JavaScript (Node.js) from Python and process Ripple
Introduction to Socket API Learned in C Language Part 1 Server Edition
Install mecab on Sakura shared server and call it from python
[Introduction to Python] I compared the naming conventions of C # and Python.
How to get a string from a command line argument in python
Solving AOJ's Algorithm and Introduction to Data Structures in Python -Part2-
[C language] How to create, avoid, and make a zombie process