如何为参数化类型编写不重新编译的扩展子模块
解读
国内超算中心、气象与 CFD 部门面试时,这道题考察的是“在不触碰主框架源码、不重新编译主库的前提下,为带 KIND 或 LEN 参数的派生类型追加新功能”的工程落地能力。
关键词是“参数化类型”(Parameterized Derived Type,PDT)与“不重新编译”。
如果候选人只回答“写个 submodule 就行”,会被追问“PDT 的 TBP 在子模块里如何保持接口一致性”“二进制接口(ABI)如何保证跨编译单元”“Coarray 并行库如何热插拔”等细节,必须给出可交付的源码组织与编译脚本。
知识点
- Fortran 2018 的 PDT 语法:KIND 与 LEN 参数在类型实例化时确定,编译期即实例化,因此主库必须只出现抽象接口,把具体实例推迟到扩展子模块。
- submodule 的分离编译机制:主模块用
interface ... module procedure声明类型绑定过程(TBP),实体在子模块实现;子模块可单独编译成.o后打包为*.a或*.so,主框架无需重编。 - 泛型接口与参数化类型的协同:用
GENERIC接口包裹 PDT 的 TBP,保证扩展子模块新增重载时不会破坏主库符号表。 - ABI 稳定技巧:
- 禁止在公开派生类型中直接包含 LEN 参数变量,改用指针或 ALLOCATABLE 组件,避免编译器在派生类型大小上产生不同实例化结果。
- 所有 TBP 第一参数用
CLASS(*)或CLASS(t_template)并加上NOPASS属性,消除 THIS 传递方式差异。
- 构建系统:国内超算环境多用 Make + CMake + 模块文件搜索路径;扩展子模块编译时加
-I$MAIN_BUILD/include拾取主模块的*.mod,但主库链接阶段完全不用感知子模块。 - 运行期插件发现:借助
dlopen(Linux)或LoadLibrary(Windows)在 C 接口层把扩展子模块的register_pdt_extension符号动态注入,Fortran 端通过BIND(C)回调完成热插拔。
答案
步骤一:主框架只暴露抽象模板
! kernel/pdt_template.f90
module pdt_template
implicit none
private
! 1) 定义含 LEN 参数的抽象类型,不实例化
type, public, abstract :: vector_t(n)
integer, len :: n
contains
procedure(norm_interface), deferred :: norm
end type
abstract interface
function norm_interface(this) result(r)
import :: vector_t
class(vector_t(*)), intent(in) :: this
real :: r
end function
end interface
end module
步骤二:在主库源码里绝不出现任何具体 PDT 实例化,只通过泛型工厂接口返回 CLASS(*) 指针,留给扩展子模块完成实例化。
步骤三:扩展子模块单独编译
! ext/vector_real64.f90
submodule (pdt_template) vector_real64
implicit none
type, public, extends(vector_t) :: vector_r64(n)
integer, len :: n
real(real64), allocatable :: data(:)
contains
procedure :: norm => norm_r64
end type
contains
real function norm_r64(this)
class(vector_r64(*)), intent(in) :: this
norm_r64 = sqrt(sum(this%data**2))
end function
end submodule
编译命令(国内超算常用 Intel oneAPI 为例):
ifort -c -fPIC -module $MAIN_BUILD/include -o vector_real64.o ext/vector_real64.f90
ar rcs libvector_r64.a vector_real64.o
步骤四:主程序运行期动态加载
! app/main.f90
use pdt_template, only: vector_t
use iso_c_binding, only: c_funptr, c_f_procpointer
external :: load_extension
type(c_funptr) :: h
procedure(register_vec), pointer :: reg
h = load_extension('libvector_r64.so') ! 由 C 层 dlopen 封装
call c_f_procpointer(h, reg)
call reg() ! 把 vector_r64 的构造函数注入工厂表
通过以上四步,主框架与扩展子模块物理隔离,新增 KIND/LEN 组合只需重新编译 libvector_r64.so,主库二进制纹丝不动,满足面试题“不重新编译”的硬要求。
拓展思考
- 国产超算异构环境:在 申威 或 海光 DCU 上,子模块需额外加
!$acc routine seq或!dir$ attributes offload:mic,主库仍保持可移植。 - MPI 多进程插件:每个 rank 独立
dlopen,但需在MPI_Init前通过 环境变量 传递扩展库路径,避免进程间符号冲突。 - 与 Python 生态对接:用 f2py 生成 C 接口时,PDT 的 LEN 参数必须退化为
int显式传入,扩展子模块需提供bind(c)的构造函数,否则 f2py 无法识别。 - 版本控制:国内研究院常要求“二进制兼容 5 年”,建议在主模块中预留
integer, parameter :: abi_version = 20240801,扩展子模块编译时静态断言比对,防止 ABI 漂移。