简体   繁体   English

使用cffi从python调用fortran dll

[英]Calling a fortran dll from python using cffi

I am currently working on a simultion-tool that requires a PDE Solver from a Fortran dll. 我目前正在使用simultion工具,该工具需要来自Fortran dll的PDE解算器。 In order to figure how calling a dll from python I used a simpler function from the same dll but can't get it to work. 为了弄清楚如何从python调用dll,我从同一个dll使用了一个更简单的函数,但无法使其正常工作。

Systemspecs: Windows 7 Professional (64bit) Spyder 3.2.8 Python 3.6.5 (32bit) 系统规格:Windows 7专业版(64位)Spyder 3.2.8 Python 3.6.5(32位)

I am now using cffi to call the fortran function but it doesn't work either. 我现在正在使用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

This is the code i am using to call the function with cffi. 这是我使用cffi调用函数的代码。 The dll i am loading contains the function S01BAF which i intend to call. 我正在加载的dll包含我要调用的函数S01BAF。 The error message I recieve is: 我收到的错误消息是:

   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

I don't know what that means. 我不知道那是什么意思

To check if the function itself is working I tryed calling it from a different language (VBA) and it worked just fine. 为了检查该函数本身是否正常工作,我尝试使用另一种语言(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

The messagebox displays the correct value for ln(2). 该消息框显示ln(2)的正确值。

I have read the previously asked questions but couldn't apply the answers to my problem. 我已经阅读了之前提出的问题,但是无法将答案应用于我的问题。

Here is the code that works thanks to @Joe! 这是使用@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))

Cheers, Thilo 干杯,蒂洛

The function definition of S01BAF S01BAF的功能定义

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

indicates that the variables x and ifail are pointers. 指示变量xifail是指针。 Please try 请试试

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM