My aim is to print the 2nd string from a python numpy array in fortran, but I only ever get the first character printed, and it's not necessarily the right string either.
Can anyone tell me what the correct way to pass full string arrays to fortran?
The code is as follows:
testpy.py
import numpy as np
import testa4
strvar = np.asarray(['aa','bb','cc'], dtype = np.dtype('a2'))
testa4.testa4(strvar)
testa4.f90
subroutine testa4(strvar)
implicit none
character(len=2), intent(in) :: strvar(3)
!character*2 does not work here - why?
print *, strvar(2)
end subroutine testa4
Compiled with
f2py -c -m testa4 testa4.f90
Output of above code
c
Desired output
bb
I don't know how to do that using f2py
. But it can be done with ctypes
. You get an array of characters, but you can convert it to a string very easily.
subroutine testa4(strvar) bind(C, name='testa4')
use iso_c_binding
implicit none
character(len=1,kind=c_char), intent(in) :: strvar(2,3)
print *, strvar(:,2)
end subroutine testa4
compile: gfortran -shared -fPIC testa4.f90 -o testa4.so
import numpy as np
import ctypes
testa4 = ctypes.CDLL("./testa4.so")
strvar = np.asarray(['aa','bb','cc'], dtype = np.dtype('a2'))
strvar_p = ctypes.c_void_p(strvar.ctypes.data)
testa4.testa4(strvar_p)
run:
> python testpy.f90
bb
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With