Calling function in shared lib

Olaf Wasmuth olaf at wasmuth.net
Fri Jun 6 18:03:07 CEST 2003


Olaf Wasmuth wrote:

> I am trying to write python code that is able to invoke
> a function that was compiled into a shared library
> (actually, FORTRAN routines).  I did succeed for a specific
> routine in a specific library, but now I want to do this
> in a more flexible way.
> 
> That is, given the library path and the "signature" of the
> routine (e.g. from a configuration file) at run time, I
> would like to call this function from within Python. My
> target platform is Unix (Solaris), so I'm thinking of
> using the GNU libltdl to access the library and do the
> call. But how can I feed the parameters into it ? Did
> anybody do this already, or do you have some pointers
> for me ?
> 
> Regards,
> 
> Olaf.
Here is my update:

add.F:
======
       SUBROUTINE ADD_II(A,B)
       INTEGER*4 A,B

       A = A+B
       END

-> put this in libadd.so

add.py:
=======
from ctypes import *
libadd = cdll.LoadLibrary("./libadd.so")
#
# ADD_II becomes ADD_II_
# in Python, C and C++
#
method = libadd.ADD_II_
x = c_int(47)
y = c_int(11)
print "x = %d, y = %d" % (x.value, y.value)
#
# The byref() is necessary since
# FORTRAN does references,
# and not values (like e.g. C)
#
method( byref(x), byref(y) )
print "x = %d, y = %d" % (x.value, y.value)

-> now: python add.py

output:
======
x = 47, y = 11
x = 58, y = 11

Two things to keep in mind (at least under Solaris):
- FORTRAN uses call-by-reference (see code above)
- SUB(<string>,<int>)
  must be treated as if it were declared as:
  SUB(<string>,<int>,len(<string>))

Thomas, Fernando: thank you very much for your
advice ! I didn't try f2py yet, because building
it is quite an involved process, and ctypes seems
to be just what I wanted (I am trying to build RPMs
from all software I use and I was glad to find out
that it is supported by the distutils just fine).

Regards,

Olaf.




More information about the Python-list mailing list