id: 12327    nodeId: 12327    type: General    point: 155.0    linkPoint: .0    maker: cella    permission: linkable    made at: 2017.07.10 02:55    edited at: 2017.07.17 07:19
Python calling C functions with ctypes
https://www.quora.com/How-can-I-call-C-C++-from-Python
https://stackoverflow.com/questions/145270/calling-c-c-from-python
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
https://docs.python.org/2/library/ctypes.html
<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>
https://stackoverflow.com/questions/14884126/build-so-file-from-c-file-using-gcc-command-line
http://www.auctoris.co.uk/2017/04/29/calling-c-classes-from-python-with-ctypes/
http://egloos.zum.com/mcchae/v/11024689

Return to 자바라 펌프 or Python calling C functions with ctypes