2

I am trying to modify the contents of an Numpy Array of string in a Fortran code by using the wrapper f2py. I always have the error:

ValueError: Failed to initialize intent (inout) array -- input 'c' not compatible to c.

Here is my code:

module1.f90

    module module1
    implicit none
    contains

    subroutine sub1(ddtype,nstr)
        integer,intent(in)::nstr
        character,intent(inout),dimension(2,nstr)::ddtype
        !f2py integer,intent(in)::nstr
        !f2py character,intent(inout),dimension(2,nstr)::ddtype

        ddtype(1,1) = 'X'
        write(*,*) 'From Fortran: ',ddtype
    end subroutine sub1
    end module module1

the python test: testPython.py

    import numpy as np
    import Test

    arg1 = np.array(['aa','bb','cc'],dtype='c').T

    Test.module1.sub1(arg1,arg1.shape[1])
    print arg1

I am in linux CentOS 7 and using gfortran, f2py and Python 2.7. I compiled by using:

f2py -c -m Test module1.f90

I can print the array of NumPy strings only if I change the the intent (inout) to (in). Generally the behavior of f2py with array of string seems not clear/stable.

libe
  • 21
  • 2

1 Answers1

1

I just modified my example from the question I already linked in the most obvious way and it works fine:

subroutine testa4(strvar) bind(C)
  use iso_c_binding
  implicit none

  character(len=1,kind=c_char), intent(inout) :: strvar(2,3)
  !character*2 does not work here - why?

  strvar(:,1) = ["a", "b"]
  strvar(:,2) = ["c", "d"]
  strvar(:,2) = ["e", "f"]

end subroutine testa4

compile:

gfortran -shared -fPIC testa5.f90 -o testa5.so

and

import numpy as np
import ctypes

testa4 = ctypes.CDLL("./testa5.so")

strvar = np.asarray(['aa','bb','cc'], dtype = np.dtype('a2'))
strvar_p = ctypes.c_void_p(strvar.ctypes.data)

testa4.testa4(strvar_p)

print(strvar)

run

   > python test.py
['ab' 'ef' 'cc']

f2py did not work for me back then so I did not even bother to try it now. I did try to adapt the f2py answer of AMacK and I got the same error you got. I would just use ctypes.