简体   繁体   English

是否可以使用F2PY从共享库中包装函数?

[英]Is it possible to wrap a function from a shared library using F2PY?

I'm developing a package that requires Python bindings for the dgtsv subroutine from the LAPACK Fortran library. 我正在开发一个包,需要来自LAPACK Fortran库的dgtsv子例程的 Python绑定。 At the moment, I'm distributing the Fortran source file, dgtsv.f , alongside my Python code, and using numpy.distutils to automatically wrap it and compile it into a shared library, _gtsv.so , that is callable from Python. 目前,我正在分发Fortran源文件dgtsv.f以及我的Python代码,并使用numpy.distutils自动将其包装并编译成可从Python调用的共享库_gtsv.so

Here's what my setup.py file looks like at the moment: 这是我的setup.py文件目前的样子:

from numpy.distutils.core import setup, Extension, build_ext
import os


fortran_sources = ["dgtsv.f"]
gtsv = Extension(
    name="pyfnnd._gtsv",
    sources=[os.path.join("pyfnnd", "LAPACK", ff) for ff in fortran_sources],
    extra_link_args=['-llapack']
)

setup(
    name='pyfnnd',
    py_modules=['_fnndeconv', 'demo', '_tridiag_solvers'],
    cmdclass={'build_ext': build_ext.build_ext},
    ext_modules=[gtsv],
)

Note that in order to actually use _gtsv.so , I still have to link against a pre-existing LAPACK shared library ( extra_link_args=['-llapack'] ). 请注意,为了实际使用_gtsv.so ,我仍然需要链接一个预先存在的LAPACK共享库( extra_link_args=['-llapack'] )。 Since this library should already contain the dgtsv subroutine, it seems to me that it would be cleaner to just wrap the function in the existing shared library, rather than having to distribute the actual Fortran source. 由于这个库应该已经包含了dgtsv子例程,在我看来,将函数包装在现有的共享库中会更加清晰,而不必分发实际的Fortran源。

However I've never come across any examples of using F2PY to wrap functions that are part of a shared library rather than just raw Fortran source code. 但是,我从未遇到任何使用F2PY来包装作为共享库的一部分的函数而不仅仅是原始Fortran源代码的示例。 Is this possible? 这可能吗?

I think you just need ctypes, there is a complete example on calling a lapack function on this page: http://www.sagemath.org/doc/numerical_sage/ctypes.html 我想你只需要ctypes,在这个页面上有一个关于调用lapack函数的完整例子: http//www.sagemath.org/doc/numerical_sage/ctypes.html

You get your function like this: 你得到这样的功能:

import ctypes
from ctypes.util import find_library
lapack = ctypes.cdll.LoadLibrary(find_library("lapack"))
dgtsv = lapack.dgtsv_

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

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