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 (build.sh, setup.py)
- A test script script.py
To build the benchmark, do
**source build.sh**
To run the example, do (from the same terminal)
**python script.py**
\ 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
contains
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
o_array=i_array_1+i_array_2
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 https://stackoverflow.com/questions/8215265/passing-python-strings-through-cython-to-c
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
#!/bin/bash
#
mkdir shared
gfortran benchmark_binding.f90 -fPIC -shared -o shared/libFortran.so
export LD_LIBRARY_PATH=`pwd`/shared:$LD_LIBRARY_PATH
rm *.mod
python setup.py build gfortran
cp build/lib.linux-x86_64-2.7/benchmark.so .
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 setup.py 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',
include_dirs=[numpy.get_include()],
library_dirs = ["shared"],
libraries=['Fortran'],
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