There are several methods for python to use to call C functions such as:
Python-C-API
ctypes
cython
SWIG
And I choose ctypes.
The main reference document for ctypes is found in
<hello.c example>
0. make a hello.c:
#include <stdio.h>
void hello()
{
printf("Hello world!\n");
}
1. make a .so file:
$ gcc -shared -o libhello.so -fPIC hello.c
NOTE:
if hello.cpp is used instead of hello.c,
extern "C" void hello()
is to be used.
And to make .so file, (some flags are optional, maybe):
$ g++ -c -fPIC hello.cpp -o hello.o
$ g++ -shared -Wl,-soname,libhello.so -o libhello.so hello.o
2. make a .py file:
import ctypes as c
import numpy as np
libhello = c.cdll.LoadLibrary('/path/to/directory/libhello.so') # sometimes, relative path results in an error
libhello.hello()
<how to send and change array arguments for C functions>
$ vi sy.c
void change(int length, int *in, int *out) {
for (int k=0; k < length; k++) {
out[k] = in[k] + 11;
}
}
$ vi test.py
import ctypes as c
import numpy as np
sy = c.cdll.LoadLibrary('/home/soh/tf/test/libsy.so')
length = 5
intA5 = c.c_int * length
#floatA5 = c.c_int * length
before = np.random.random_integers(1, 10, length)
print(before)
#a = intA5(1,2,3,4,5)
a = intA5()
for j in range(length): a[j] = before[j]
sy.change(length, a)
for i in a: print(i)
after = np.arange(length)
for j in range(length): after[j] = a[j]
print(after)
<and other pages referenced>