从 python 中的共享 fortran 库调用函数
我想在 Python 中调用 Fortran 共享库中的一些函数。我在网上找到了一些链接并阅读了它们,根据我发现的内容,我应该
libadd = cdll.LoadLibrary('./libbin.so')
加载共享对象。但是,此共享对象包含来自另一个共享库的一些符号。我阅读了 cdll 的帮助,但是似乎不可能同时加载多个共享对象文件。我如何调用这个 Fortran 库中的函数(该库很可能是由英特尔 Fortran 编译器编译的)?
I would like to call some functions from a Fortran shared library in Python. I have found some links on the net and read them, and according what I found, I should do
libadd = cdll.LoadLibrary('./libbin.so')
to load the shared object. However, this shared object includes some symbols from another shared library. I read the help of cdll however it does not seem possible to load several shared object files at the same time. How may I call functions from this Fortran library, which is most probably compiled by the Intel Fortran compiler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要知道共享对象中函数的签名。您有源代码或一些解释函数名称和参数类型的参考吗?
例如,我有这个源代码(mult.f90):
..为了演示如何一次加载和使用多个共享对象,我还有(add.f90 strong>):
编译,检查符号:
注意共享库中的符号名称附加了下划线。由于我有源代码,我知道签名是
multiply_(int *a, int *b)
,因此很容易从ctypes
调用该函数:输出:
You'll need to know the signatures of the functions in the shared object. Do you have the source code, or some reference which explains the function names and argument types?
For example, I have this source code (mult.f90):
.. and to demonstrate how you can load and use multiple shared objects at once, I also have (add.f90):
Compile, examine symbols:
Notice the symbol name in the shared object has an underscore appended. Since I have the source, I know that the signature is
multiply_(int *a, int *b)
, so it is easy to invoke that function fromctypes
:Output:
我想在 @sameplebias 答案中添加一点,即可以使用 iso_c_binding 模块强制(任何)fortran 编译器生成正确的 C 签名。使用示例:
这将具有以下 C 签名:
然后您可以像往常一样从 Python 调用它。这种方法的优点是它适用于所有平台(无需使用任何特殊的编译器选项)。
I would add to @sameplebias answer, that one can use the
iso_c_binding
module to force (any) fortran compiler to produce the correct C signature. Example of usage:this will have the following C signature:
and then you can call it from Python as usual. The advantage of this approach is that it works on all platforms (without using any special compiler options).
要使 f2py(来自 NumPy)正常工作,请借用@samplebias 中的
mult.f90
和add.f90
示例。从 shell 编译 Python 可导入共享库:现在在 Python 中使用它们:
For f2py (from NumPy) to work, borrow both the
mult.f90
andadd.f90
examples from @samplebias. From a shell, compile the Python importable shared libraries:Now use them in Python: