【问题标题】:Calling a fortran dll from python using cffi使用 cffi 从 python 调用 fortran dll
【发布时间】:2018-08-09 06:57:04
【问题描述】:

我目前正在开发一个需要来自 Fortran dll 的 PDE 求解器的 simultion 工具。为了弄清楚如何从 python 调用 dll,我使用了来自同一个 dll 的更简单的函数,但无法让它工作。

系统规格: Windows 7 专业版(64 位) 蜘蛛3.2.8 Python 3.6.5(32 位)

我现在正在使用 cffi 来调用 fortran 函数,但它也不起作用。

    import cffi as cf

    ffi=cf.FFI()

    lib=ffi.dlopen("C:\Windows\SysWOW64\DLL20DDS")

    ffi.cdef("""
             double S01BAF(double X, int IFAIL);
    """)

    print (lib)   #This works
    print (lib.S01BAF)   #This works

    x = 1.
    ifail = 0

    print (lib.S01BAF(x,ifail)) #This doesn't work

这是我用来调用 cffi 函数的代码。我正在加载的 dll 包含我打算调用的函数 S01BAF。 我收到的错误信息是:

   runfile('C:/Users/Student/Desktop/Minimal.py', wdir='C:/Users/Student/Desktop')
   <cffi.api._make_ffi_library.<locals>.FFILibrary object at 0x0759DB30>
   <cdata 'double(*)(double, int)' 0x105BBE30>
   Kernel died, restarting

我不知道那是什么意思。

为了检查函数本身是否正常工作,我尝试从不同的语言 (VBA) 调用它,结果很好。

    Option Base 1
    Option Explicit

    Private Declare Function S01BAF Lib "DLL20DDS.dll" (x As Double, iFail As Long) As Double

    Sub ln()
        Dim iFail As Long
        Dim x As Double
        Dim y As Double

        x = 1
        iFail = 0
        y = S01BAF(x, iFail)
        MsgBox y
    End Sub

消息框显示 ln(2) 的正确值。

我已阅读之前提出的问题,但无法将答案应用于我的问题。

感谢@Joe,这是有效的代码!

    ffi=cf.FFI()
    lib=ffi.dlopen("C:\Windows\SysWOW64\DLL20DDS")
    ffi.cdef("double S01BAF(double *x, int *ifail);")

    x_1 = np.arange(-0.99,1,0.001)

    x = ffi.new('double*', 1)
    ifail = ffi.new('int*', 0)    

    y = (lib.S01BAF(x,ifail))

干杯, 蒂洛

【问题讨论】:

  • 一般建议不要直接使用ctypes。 cffi 提供了一个高级接口,并且更易于使用。它还在后台进行大量检查和类型转换。有关第一个示例,请参阅here
  • @Joe 感谢您的建议,但我仍然无法调用该函数。

标签: python python-3.x dll fortran cffi


【解决方案1】:

S01BAF的函数定义

double s01baf_ (const double *x, Integer *ifail)

表示变量xifail是指针。请尝试

x = cf.new('double*', 1.0)
ifail = cf.new("int*", 0)    
lib.S01BAF(x, ifail)

x = cf.new('double*')
x[0] = 1.0
ifail = cf.new("int*")    
ifail[0] = 0
lib.S01BAF(x, ifail)

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 2020-05-04
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    相关资源
    最近更新 更多