在Ubuntu下,Fortran与Python可以通过多种方式结合使用,以下是几种常见的方法:
f2py是NumPy提供的一个工具,可以将Fortran代码转换为Python模块。以下是使用f2py的基本步骤:
sudo apt update
sudo apt install gfortran python3-numpy
创建一个名为example.f90
的文件,内容如下:
subroutine add(a, b, c) bind(c, name="add") use, intrinsic :: iso_c_binding real(c_double), intent(in) :: a, b real(c_double), intent(out) :: c c = a + b end subroutine add
f2py -c example.f90 -m example
import example
result = example.add(2.0, 3.0)
print(result) # 输出 5.0
Cython是一个编程语言,可以将Python代码转换为C代码,并且可以调用Fortran代码。以下是使用Cython的基本步骤:
sudo apt update
sudo apt install gfortran python3-cython
创建一个名为example.f90
的文件,内容如下:
subroutine add_(double *a, double *b, double *c)
use iso_c_binding
implicit none
*a = *b + *c
end subroutine add_
创建一个名为example.pyx
的文件,内容如下:
cdef extern from "example.f90":
void add_(double *a, double *b, double *c)
def add(double a, double b):
cdef double c
add_(&a, &b, &c)
return c
setup.py
文件:from setuptools import setup
from Cython.Build import cythonize
setup(
ext_modules=cythonize("example.pyx"),
extra_link_args=['-lgfortran']
)
python setup.py build_ext --inplace
import example
result = example.add(2.0, 3.0)
print(result) # 输出 5.0
pybind11是一个轻量级的头文件库,用于将C++代码暴露给Python。虽然它主要用于C++,但也可以通过一些技巧来调用Fortran代码。以下是使用pybind11的基本步骤:
sudo apt update
sudo apt install gfortran python3-pybind11-dev
创建一个名为example.f90
的文件,内容如下:
subroutine add(a, b, c) bind(c, name="add") use iso_c_binding real(c_double), intent(in) :: a, b real(c_double), intent(out) :: c c = a + b end subroutine add
创建一个名为wrapper.cpp
的文件,内容如下:
#include <pybind11/pybind11.h>
#include "example.f90"
namespace py = pybind11;
double add(double a, double b) {
double c;
add_(&a, &b, &c);
return c;
}
PYBIND11_MODULE(example, m) {
m.def("add", &add, "A function that adds two numbers");
}
CMakeLists.txt
文件:cmake_minimum_required(VERSION 3.4)
project(example)
set(CMAKE_CXX_STANDARD 11)
find_package(pybind11 REQUIRED)
pybind11_add_module(example wrapper.cpp example.f90)
mkdir build
cd build
cmake ..
make
import example
result = example.add(2.0, 3.0)
print(result) # 输出 5.0
以上方法各有优缺点,选择哪种方法取决于你的具体需求和偏好。