简体   繁体   English

使用 CFFI 在 Fortran 中使用 Python 函数。 cffi 构建中的警告。 我无法通过控制台或文件中的打印获得结果,但在运行时不会出错

[英]Use CFFI for using Python function inside Fortran. Warnings in cffi build. I can't get results from print in console or file, but not error in running

Coding编码

I followed documentation described in "CFFI Documentation Release 1.15.0" section "9.1 Usage" but with semplification, using a 'identity' function.我遵循“CFFI 文档版本 1.15.0”部分“9.1 用法”中描述的文档,但使用“身份”函数进行了简化。

Step 1 - plugin.h第 1 步 - plugin.h

# ifndef CFFI_DLLEXPORT
# if defined(_MSC_VER)
# define CFFI_DLLEXPORT extern __declspec(dllimport)
# else
# define CFFI_DLLEXPORT extern
# endif
#endif
CFFI_DLLEXPORT int identity(int);

Step 2 - plugin_build.py第 2 步 - plugin_build.py

import cffi
ffiBuilder = cffi.FFI()
with open('plugin.h') as f:
    data = ''.join([line for line in f if not line.startswith('#')])
    data = data.replace('CFFI_DLLEXPORT', '')
    ffiBuilder.embedding_api(data)

ffiBuilder.set_source("my_plugin", r'''
#include "plugin.h"
''')

# Here thanks to @Armin in the comment I replace 'value'
# inside print and fw.write with 'str(value)' to avoid "python crash"
ffiBuilder.embedding_init_code("""
    from my_plugin import ffi
    @ffi.def_extern()
    def identity(value):
        print(str(value))
        with open('results.txt', 'w') as fw:
            fw.write(str(value))
        return value
""")

ffiBuilder.compile(target="plugin-1.5.*", verbose=True)

Step 4 - Execute plugin_build.py第 4 步 - 执行 plugin_build.py

python plugin_build.py I received that in console python plugin_build.py 我在控制台收到了

generating .\my_plugin.c
the current directory is 'C:\\Users\\utente\\...\\FortranFiles\\CFFIexample5'
running build_ext
building 'my_plugin' extension
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\include -IC:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\include -IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\ATLMFC\include -IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include -IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt /Tcmy_plugin.c /Fo.\Release\my_plugin.obj
my_plugin.c
my_plugin.c(1060): warning C4047: 'function': 'volatile PVOID *' differs in levels of indirection from 'volatile int *'
my_plugin.c(1060): warning C4022: '_InterlockedCompareExchangePointer': pointer mismatch for actual parameter 1
my_plugin.c(1060): warning C4022: '_InterlockedCompareExchangePointer': pointer mismatch for actual parameter 2
my_plugin.c(1060): warning C4022: '_InterlockedCompareExchangePointer': pointer mismatch for actual parameter 3
my_plugin.c(1060): warning C4047: '==': 'PVOID' differs in levels of indirection from 'int'
my_plugin.c(1095): warning C4047: 'function': 'volatile PVOID *' differs in levels of indirection from 'volatile int *'
my_plugin.c(1095): warning C4022: '_InterlockedCompareExchangePointer': pointer mismatch for actual parameter 1
my_plugin.c(1095): warning C4022: '_InterlockedCompareExchangePointer': pointer mismatch for actual parameter 2
my_plugin.c(1095): warning C4022: '_InterlockedCompareExchangePointer': pointer mismatch for actual parameter 3
my_plugin.c(1095): warning C4047: '==': 'PVOID' differs in levels of indirection from 'int'
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\libs /LIBPATH:C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\PCbuild\amd64 /LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\ATLMFC\lib\x64 /LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\lib\x64 /LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64 /LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17763.0\ucrt\x64 /LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17763.0\um\x64 python39.lib /EXPORT:PyInit_my_plugin .\Release\my_plugin.obj /OUT:.\plugin-1.5.dll /IMPLIB:.\Release\plugin-1.5.lib /MANIFEST
   Library creation .\Release\plugin-1.5.lib e dell'oggetto .\Release\plugin-1.5.exp
Code generation in progress ...
Code generation finished

This command creates my_plugin.c, plugin-1.5.dll in root project folder and my_plugin.obj, plugin-1.5.exp and plugin-1.5.lib in Release folder inside root project folder.此命令在根项目文件夹中创建 my_plugin.c、plugin-1.5.dll 和在根项目文件夹中的 Release 文件夹中创建 my_plugin.obj、plugin-1.5.exp 和 plugin-1.5.lib。

Step 5 - Create Fortran esempio.f90第 5 步 - 创建 Fortran esempio.f90

program esempio
  use, intrinsic :: iso_c_binding, only : c_int

  integer(c_int) :: intero
  interface
     subroutine identity(a, output) bind (c, name="identity")
        use iso_c_binding
        integer(c_int), intent(in) :: a
        integer(c_int), intent(out) :: output
     end subroutine identity
  end interface

  call identity(4, intero)
  open(unit=100, file='filename.txt', status="unknown", action="write")
  write(100, '(I0)') intero
end program esempio

Step 6 - Link everything第 6 步 - 链接所有内容

gfortran -o testtest.exe esempio.f90 -L. plugin-1.5.dll

Command executed without any message printed in console, executable file testtest.exe was generated.命令执行时没有在控制台打印任何消息,生成了可执行文件 testtest.exe。

Step 7 - Run executable file步骤 7 - 运行可执行文件

Before run testtest.exe, I set PYTHONHOME env.在运行 testtest.exe 之前,我设置了 PYTHONHOME env。 Command executed without any message printed in console and any files was created.命令执行时没有在控制台中打印任何消息,并且创建了任何文件。 Why?为什么? I expect files and print in console but nothing happen.我希望在控制台中文件和打印,但没有任何反应。

Tech Context技术背景

  • OS Windows 10操作系统Windows 10
  • Python Anaconda3, Python 3.9.7 Python Anaconda3、Python 3.9.7
  • gFortran GNU Fortran (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0 gFortran GNU Fortran(x86_64-posix-seh-rev0,由 MinGW-W64 项目构建)8.1.0

Help Please tell me something to go on, because I saw "warnings" in step 4, I don't know if they are negligible and how to procede to correct them.帮助请告诉我要继续做的事情,因为我在第 4 步中看到了“警告”,我不知道它们是否可以忽略不计以及如何进行更正。 Thank you.谢谢你。

I managed to get your code working on Linux .我设法让你的代码在 Linux 上工作。 I cannot guarantee it will work properly on Windows, but the changes make sense and should get you at least very close.我不能保证它会在 Windows 上正常工作,但这些更改是有道理的,至少应该让你非常接近。

  1. use a function, not a subroutine when you have a non-void function in C当你在 C 中有一个非空函数时,使用一个函数,而不是一个子程序

  2. pass the arguments with the value attribute使用value属性传递参数

  integer(c_int) :: intero
  interface
     function identity(a) result(output) bind (c, name="identity")
        use iso_c_binding
        integer(c_int), value :: a
        integer(c_int) :: output
     end function identity
  end interface

  intero =  identity(4_c_int)

Disclaimer: I never used CFFI nor did I study any documentation for it, I just applied changes that seemed obvious enough.免责声明:我从未使用过 CFFI,也没有研究它的任何文档,我只是应用了看起来足够明显的更改。

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

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