【问题标题】:Modify a Numpy string array from Fortran with f2py使用 f2py 从 Fortran 修改 Numpy 字符串数组
【发布时间】:2018-07-21 14:35:30
【问题描述】:

我正在尝试使用包装器 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 测试: 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

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

f2py -c -m Test module1.f90

只有将intent (inout) 更改为(in) 才能打印NumPy 字符串数组。一般来说,带有字符串数组的 f2py 的行为似乎并不清晰/稳定。

【问题讨论】:

  • 请注意,这两个 !f2py 注释只是额外的工作,f2py 可以从您的 Fortran 声明中自动计算出来。
  • 请阅读minimal reproducible example。您的代码应该是实际代码。我真的怀疑您的代码是否与dimention 一起编译!
  • 您的问题是基于stackoverflow.com/questions/22293180/… 吗?提到这一点通常很有用。那里的方法不适合你吗?
  • @Vladimir F,感谢您的回复,我已经非常仔细地阅读了您建议给我的链接,在他们的情况下,他们只需要将 numpy 数组从 python 打印到 fortran,我需要修改fortran 中的 numpy 数组。

标签: python string numpy fortran f2py


【解决方案1】:

我刚刚以最明显的方式从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。

【讨论】:

    猜你喜欢
    • 2014-04-13
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多