Load a 32-bit FORTRAN library in 64-bit Python

This example shows how to access a 32-bit FORTRAN library from 64-bit Python. Fortran32 is the 32-bit server and Fortran64 is the 64-bit client. The source code of the FORTRAN program is available here.

Note

If you have issues running the example please make sure that you have the prerequisites installed for your operating system.

Important

By default ctypes expects that a ctypes.c_int data type is returned from the library call. If the returned value from the library is not a ctypes.c_int then you must redefine the ctypes restype value to be the appropriate data type. The Fortran32 class shows various examples of redefining the restype value.

Create a Fortran64 client to communicate with the 32-bit fortran_lib32 library

>>> from msl.examples.loadlib import Fortran64
>>> f = Fortran64()

Add two int8 values, see sum_8bit()

>>> f.sum_8bit(-50, 110)
60

Add two int16 values, see sum_16bit()

>>> f.sum_16bit(2**15-1, -1)
32766

Add two int32 values, see sum_32bit()

>>> f.sum_32bit(123456788, 1)
123456789

Add two int64 values, see sum_64bit()

>>> f.sum_64bit(-2**63, 1)
-9223372036854775807...

Multiply two float32 values, see multiply_float32()

>>> f.multiply_float32(1e30, 2e3)
1.99999998899...e+33

Multiply two float64 values, see multiply_float64()

>>> f.multiply_float64(1e30, 2e3)
2.00000000000...e+33

Check if a value is positive, see is_positive()

>>> f.is_positive(1e-100)
True
>>> f.is_positive(-1e-100)
False

Add or subtract two integers, see add_or_subtract()

>>> f.add_or_subtract(1000, 2000, True)
3000
>>> f.add_or_subtract(1000, 2000, False)
-1000

Calculate the n’th factorial, see factorial()

>>> f.factorial(0)
1.0
>>> f.factorial(127)
3.012660018457658e+213

Calculate the standard deviation of an list of values, see standard_deviation()

>>> f.standard_deviation([float(val) for val in range(1,10)])
2.73861278752583...

Compute the Bessel function of the first kind of order 0, see besselJ0()

>>> f.besselJ0(8.6)
0.0146229912787412...

Reverse a string, see reverse_string()

>>> f.reverse_string('hello world!')
'!dlrow olleh'

Add two 1D arrays, see add_1d_arrays()

>>> a = [float(val) for val in range(1, 10)]
>>> b = [0.5*val for val in range(1, 10)]
>>> a
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
>>> b
[0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
>>> f.add_1d_arrays(a, b)
[1.5, 3.0, 4.5, 6.0, 7.5, 9.0, 10.5, 12.0, 13.5]

Multiply two matrices, see matrix_multiply()

>>> m1 = [[1, 2, 3], [4, 5, 6]]
>>> m2 = [[1, 2], [3, 4], [5, 6]]
>>> f.matrix_multiply(m1, m2)
[[22.0, 28.0], [49.0, 64.0]]

Shutdown the 32-bit server when you are done communicating with the 32-bit library

>>> stdout, stderr = f.shutdown_server32()