Skip to main content
 首页 » 编程设计

python之使用 f2py 从 Fortran 修改 Numpy 字符串数组

2024年12月31日23birdshome

我正在尝试使用包装器 f2py 修改 Fortran 代码中 Numpy 字符串数组的内容。我总是有错误:

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

这是我的代码:

模块1.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 

python 测试: 测试Python.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 

我在 linux CentOS 7 中使用 gfortran、f2py 和 Python 2.7。 我通过使用编译:

f2py -c -m Test module1.f90 

仅当我将 intent (inout) 更改为 (in) 时,我才能打印 NumPy 字符串数组。通常,带有字符串数组的 f2py 的行为似乎不清楚/稳定。

请您参考如下方法:

我刚刚修改了 question I already linked 中的示例以最明显的方式,它工作正常:

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 

编译:

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

和

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) 

运行

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

f2py 当时对我不起作用,所以我现在甚至懒得去尝试。 我确实尝试调整 AMacK 的 f2py 答案,但我得到了与你相同的错误。我只会使用 ctypes。