Skip to main content
 首页 » 编程设计

python之Python 包装器中的 Fortran DLL,相同功能的输出不同

2025年02月15日10bjzhanghao

我已经根据这个 question 改编了我的代码

我的最终目标是: - 在 DLL 中打包一些 Fortran 代码(已完成) - 创建一个 Python 包装器作为从源接收输入的接口(interface),并将这些输入提供给 DLL 并将它们传递给 DLL 的 Fortran 函数 - 返回函数的输出以传递给另一个 Python 程序。

到目前为止,我一直在使用这个示例作为原型(prototype)(我最终会对其进行调整),每次都会获得不同的输出。

如图所示:

    C:\Users\NAME\Desktop>python.exe py_wrapper.py 
    <CDLL 'fort_test', handle 6f800000 at 0x25e174ec2e8> 
    <_FuncPtr object at 0x0000025E17617388> 
    <_FuncPtr object at 0x0000025E17617388> 
    c_long(3) 
    390943376        <---int value (my annotation for clarity) 
    <class 'int'> 
    c_long(390943376) 
    <__main__.LP_c_long object at 0x0000025E174D54C8> 

和

    C:\Users\NAME\Desktop>python.exe py_wrapper.py 
    <CDLL 'fort_test', handle 6f800000 at 0x23fa636c2e8> 
    <_FuncPtr object at 0x0000023FA6497388> 
    <_FuncPtr object at 0x0000023FA6497388> 
    c_long(3) 
    -1506454896       <---int value (my annotation for clarity) 
    <class 'int'> 
    c_long(-1506454896) 
    <__main__.LP_c_long object at 0x0000023FA63554C8> 

这是我的 Fortran 代码的内容:

    subroutine ex(i) 
    integer i 
    i=i+1 
    return i 
    end      

这是我的 Python 包装器:(这里有很多测试内容)

    from ctypes import * 
 
    DLL = CDLL('fort_test') 
    print(DLL) 
 
    print(getattr(DLL, 'ex_')) 
    print(DLL.ex_) 
 
    x = pointer(c_int(3)) 
    print(x.contents) 
    res = DLL.ex_(x) 
    print(res) 
    print(type(res)) 
    proc_res = pointer(c_int(res)) 
    print(proc_res.contents) 
    print(proc_res) 

我的问题是,有人知道为什么这个输出不断变化吗?我在代码中的输入是 3,我希望给定函数的输出是 4,但我得到的看起来像内存地址(请参阅输出示例中的注释)或内存地址的带符号整数表示形式?

请您参考如下方法:

更新:

我已经解决了我的问题。

from ctypes import * 
 
DLL = windll.fort_test 
print DLL 
 
x = byref(c_int(3))  
print x res = DLL.ex_( x ) 
print cast(res,POINTER(c_int)).contents 

我也清理了很多。 我仍然通过引用传递,然后转换作为 c_int 指针返回的内存地址(全部大写很重要)并使用 '.contents' 函数指针取消引用它