用f2py修改Fortran中的Numpy字符串数组

2024-04-16 15:25:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

这是我的代码:

模块1.f90

^{2}$

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

我在LinuxCentOS 7中,使用的是gfortran、f2py和python2.7。 我用以下方法编译:

f2py -c -m Test module1.f90

只有将intent (inout)更改为(in),我才能打印NumPy字符串数组。通常,f2py与字符串数组的行为似乎不清晰/不稳定。在


Tags: to字符串代码testimportnp数组array
1条回答
网友
1楼 · 发布于 2024-04-16 15:25:05

我刚从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

编译:

^{pr2}$

以及

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。在

相关问题 更多 >