Calling CVF-Fortran-dll with ctypes and simple structure

Michael Schäfer mcat.schaefer at gmx.de
Mon Apr 7 08:19:03 EDT 2008


Hi all,

I deal with the old problem passing characters from python to a
fortran dll build with CFV6.6c.
I reduced our complex structure to a simple one.  Here is the Fortran
code:

      SUBROUTINE DEMO2L(s)

C     sample for calling CVF6.6c-DLLs from
C     vb/vba/python with simple structure

	!DEC$ ATTRIBUTES DLLEXPORT::DEMO2L

	TYPE rcDEMO
	   INTEGER a
	   REAL b
	   CHARACTER c*9
	END TYPE

	TYPE(rcDEMO) :: s
C
	WRITE(*,*) s.a, s.b, s.c
C     sample calculation:
	s.a = s.a*10
	s.b = s.b**2.3
        s.c = 'Sample'

      RETURN
      END

From VB the calling is very simple:

Declare Sub DEMO2L Lib "release\demo1l.dll" (ByRef k As rcDEMO)

Type rcDEMO
  a As Long
  b As Single
  c As String * 9
End Type

Dim k As rcDEMO

Sub run()

    k.a = 2
    k.b = 3#
    k.c = "Test"

    Call DEMO2L(k)

    Debug.Print k.a, k.b, k.c

End Sub

and result to: "  20            12,5135      Sample"

When I try this from python:

from ctypes import *

class rcDemo(Structure):
  _fields_ = [
				('a', c_int),
				('b', c_float),
				('c', c_char_p),
                 ]

mydll = windll.LoadLibrary("release\DEMO1L.DLL")

rc = rcDemo()
rc.a = 2
rc.b = 3.
rc.c = "Test56789"

mydll.DEMO2L(byref(rc))

print rc.a
print rc.b
print ">" + rc.c + "<"

I got "           2   3.000000     ♀Å╣" from the debug print in
Fortran and

20
12.513502121
Traceback (most recent call last):
  File "run_demo.py", line 21, in ?
    print ">" + rc.c + "<"
ValueError: invalid string pointer 0x706D6153

from Python. When passing only the string in a argument list instead
of the structure and considering to pass the length of the string as
2nd argument I am be able to send this characters to the dll and
receive a changed value back.

Have anyone an idea or perhaps a solution ;-) doing this in a
structure?

Thank you!
Michael



More information about the Python-list mailing list