Return text string from fortran routine in python using f2py

I got this simple module in Fortran:

test.f90

module test implicit none contains subroutine foo(chid) implicit none character(len=*),intent(out):: chid ! char. identifier chid = "foo" end subroutine foo end module test program bar use test character(len=20) text call foo(text) write(*,*) text end program bar 

compile it (in windows) gfortran test.f90 -o test.exe and run it, as expected:

  foo 

I can also compile it with f2py: c:\Python27\python.exe c:\Python27\Scripts\f2py.py --fcompiler=gnu95 --compiler=mingw32 -c -m test \test.f90

When I run this Python script:

test.py

 from id_map import test print "This should be 'foo':" print test.foo() print "was it?" 

I get the following output:

 This should be 'foo': was it? 

As you can see, the line, which should be "foo", is empty. Why is this?

+4
source share
1 answer

The problem here is the declaration of the len=* character. you tell the fortran compiler to accept any input string of length. This is great, unless you terminate it with f2py and have the intention of out , f2py needs to guess which length string to allocate and pass to your function, and it has no way to do this. (After all, what length of string should it take?).

It seems to me that f2py takes a string of length 0. When you assign a large string to a smaller string in fortran, the result is truncated (although I need to go back and read the standard to see if this can lead to memory errors). In any case, this is similar to what the gnu compiler does.

If you change it to len=3 , it will work.

Alternatively, something like this can make this work for f2py without changing the source code (except for some comments):

  !f2py character(len=256),intent(out):: chid character(len=*),intent(out):: chid ! char. identifier 
+5
source

Source: https://habr.com/ru/post/1488508/


All Articles