有限元动态链接库编程中巧用抽象类 动态链接库以dll为后缀,软件开发中采用动态链接库有利于开发时的分工、后期维护,以及防止代码泄密。有限元软件架构中,经常会将不同的功能划分为不同的模块,每个模块采用动态链接库来完成。如现有的有限元软件中,常常将计算模块以及图象显示模块设计为动态链接库,在界面程序中调用。 在动态链接库程序开发中,巧用抽象类常常可以起到举足轻重的作用。本文简单讲解在有限元程序开发时,如何在动态链接库中使用抽象类。 举个小例子说明: 制作有限元计算模块FemModel链接库,并在程序Main中调用FemModel链接库。 先看通常采用的方式,在VC6.0中新建FemModel链接库工程,建立有限元模型输出类FemModel,包含成员为节点数nPoint,函数ReadFile,其中ReadFile函数用来读取文件读取节点数。 //FemModel.h Class __declspec(dllexport) FemModel : { public: FemModel(); virtual ~FemModel(); void ReadFile(FILE* _ifile);//读取文件,设置节点数 private: int nPoint; //节点数 }; FemModel.cpp内容略。 编译工程,生成FemModel.lib、FemModel.dll文件。 在程序Main中调用FemModel链接库时,需要在工程中导入FemModel.h文件,调用方式如下, #include "FemModel.h" int main() { FemModel iFem; iFem. ReadFile(_ifile); return 0; } 此时,问题就产生了。通常情况下,FemModel链接库和调用程序(程序Main)的开发者为不同的小组,若程序升级时,需要在FemModel类中加入新成员,例如单元数int nElement,其值同样通过ReadFile函数读入。那么,更新完FemModel类后,就必须重新编译界面程序Main。这样就给程序开发带来了不必要的开销。 下面介绍如何采用抽象类避免上述问题, 抽象类的用途是被继承。定义抽象类就是在类的定义中至少定义一个纯虚函数。纯虚函数的声明形式是在虚函数的后面加上“=0”。 例如virtual void Init() = 0; 在FemModel链接库中加入文件IFemModel.h,代码如下, //IFemModel.h class __declspec(dllexport) IFemModel { public: void ReadFile(FILE* _ifile)=0;//读取文件,设置节点数 }; __declspec(dllexport) IFemModel* GetFemModelInterface();//全局函数,用来获取IFemModel接口 同时FemModel.h文件更新如下, //FemModel.h #include "IFemModel.h" Class FemModel : public IFemModel { public: FemModel(); virtual ~FemModel(); void ReadFile(FILE* _ifile);//读取文件,设置节点数 private: int nPoint; //节点数 }; 在FemModel.cpp内容顶部加入全局函数GetFemModelInterface的实现代码, IFemModel* GetFemModelInterface() { return (IFemModel* )(new FemModel); } 在程序Main中调用FemModel链接库时,在工程中导入IFemModel.h文件(注意不是FemModel.h),调用方式如下, #include "IFemModel.h" int main() { IFemModel* pIFem; pIFem = GetFemModelInterface(); pIFem-> ReadFile(_ifile); //通常还需释放pIFem接口 return 0; } 这样,在FemModel类中加入新成员int nElement时,只需要更新FemModel链接库代码,而无需要更新程序Main,从而也无需再重新编译。代码如下, //FemModel.h #include "IFemModel.h" Class FemModel : public IFemModel { public: FemModel(); virtual ~FemModel(); void ReadFile(FILE* _ifile);//读取文件,设置节点数、单元数 private: int nPoint; //节点数 int nElement; //单元数 };

评论