Commit 07df08d7 authored by Remi Perenon's avatar Remi Perenon
Browse files

Adding the iso-c-binding/Cython binding scheme

parent 276d027e
This repository illustrates the iso_c_binding-cython way to bind python and fortran.
It consists in
- A benchmark_binding.f90 Fortran source code file
- A benchmark_binding.pyx Cython source code file
- Files for building the benchmark (,
- A test script
To build the benchmark, do
To run the example, do (from the same terminal)
\ No newline at end of file
module test_iso_c_binding
use iso_c_binding, only: c_double, c_int, c_f_pointer, c_loc, c_null_char, c_char, c_ptr
implicit none
public :: add_function
subroutine add_function(array_length, i_array_1, i_array_2, o_array) bind(C)
integer, intent(IN) :: array_length
real(kind=c_double), dimension(array_length), intent(IN) :: i_array_1, i_array_2
real(kind=c_double), dimension(array_length), intent(OUT) :: o_array
integer :: i
end subroutine add_function
end module
import numpy as np
cimport numpy as np
from libc.stdlib cimport malloc
from libc.string cimport strcpy, strlen
cdef extern:
void add_function(bint *length, double *array, double *array, double *array)
# See
def add(np.ndarray[np.double_t,ndim=1] darray, np.ndarray[np.double_t,ndim=1] darray2): #str filename):
#cdef double* array = darray
cdef bint length = len(darray)
cdef np.ndarray[np.double_t,ndim=1] output = np.asarray(np.zeros(len(darray)), dtype=darray.dtype)
add_function(&length, &darray[0], &darray2[0], &output[0])
return output
\ No newline at end of file
mkdir shared
gfortran benchmark_binding.f90 -fPIC -shared -o shared/
export LD_LIBRARY_PATH=`pwd`/shared:$LD_LIBRARY_PATH
rm *.mod
python build gfortran
cp build/lib.linux-x86_64-2.7/ .
rm *.c
rm -rf build
\ No newline at end of file
import benchmark
import numpy as np
print(benchmark.add(np.asarray([1,2,3]).astype(np.float), np.asarray([1,2,3]).astype(np.float)))
\ No newline at end of file
# Pour compiler:
# python build_ext --inplace
import glob
import os
import sys
from Cython.Distutils import build_ext
from distutils.core import setup, Extension
from distutils.sysconfig import get_config_vars
import numpy
compiler = sys.argv.pop(2)
EXTENSIONS = [Extension('benchmark',
library_dirs = ["shared"],
sources = ['benchmark_binding.pyx']
setup (name = "Benchmark",
version = "1.0",
ext_modules = EXTENSIONS,
package = "Benchmark",
package_dir = {"Benchmark":"."},
cmdclass = {'build_ext': build_ext})
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment