使用f2py将numpy字符串格式数组传递给fortran

Ger*_*ard 5 python arrays fortran numpy f2py

我的目标是从fortran中的python numpy数组中打印第二个字符串,但我只打印出第一个字符,并且它也不一定是正确的字符串.

任何人都可以告诉我将完整的字符串数组传递给fortran的正确方法是什么?

代码如下:

testpy.py

import numpy as np
import testa4

strvar = np.asarray(['aa','bb','cc'], dtype = np.dtype('a2'))
testa4.testa4(strvar)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

编译

f2py -c -m testa4 testa4.f90
Run Code Online (Sandbox Code Playgroud)

输出上述代码

c
Run Code Online (Sandbox Code Playgroud)

期望的输出

bb
Run Code Online (Sandbox Code Playgroud)

Vla*_*r F 3

我不知道如何使用f2py. 但这可以用 来完成ctypes。您将获得一个字符数组,但您可以非常轻松地将其转换为字符串。

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
Run Code Online (Sandbox Code Playgroud)

编译: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 Code Online (Sandbox Code Playgroud)

跑步:

> python testpy.f90 
 bb
Run Code Online (Sandbox Code Playgroud)