本節の多くの情報は、Fortranおよび C (これらの言語はデータ型と命名体系が似ている) に適用されます。 しかし、Fortran と C++ を同じプログラムに混合させるためには、間接のレベルを余分に 追加し、C++ の wrapper 関数で 言語間呼び出しを渡す必要があります。
C++ コンパイラーはいくつかの C++ オブジェクトの名前をマングル処理してしまう ため、C++ コンパイラーを 使用して最後のプログラムをリンクし、 XL Fortran ライブラリー・ディレクトリーおよびライブラリーのために -L および -l オプションを 組み込む必要があります。
図 1. C++ を呼び出す Fortran のメイン・プログラム (main1.f)
program main integer idim,idim1 idim = 35 idim1= 45 write(6,*) 'Inside Fortran calling first C function' call cfun(idim) write(6,*) 'Inside Fortran calling second C function' call cfun1(idim1) write(6,*) 'Exiting the Fortran program' end
図 2. C++ を呼び出すための C++ Wrapper 関数 (cfun.C)
#include <stdio.h> #include "cplus.h" extern "C" void cfun(int *idim); extern "C" void cfun1(int *idim1); void cfun(int *idim){ printf("%%Inside C function before creating C++ Object¥n"); int i = *idim; junk<int>* jj= new junk<int>(10,30); jj->store(idim); jj->print(); printf("%%Inside C function after creating C++ Object¥n"); delete jj; return; } void cfun1(int *idim1) { printf("%%Inside C function cfun1 before creating C++ Object¥n"); int i = *idim1; temp<double> *tmp = new temp<double>(40, 50.54); tmp->print(); printf("%%Inside C function after creating C++ temp object¥n"); delete tmp; return; }
図 3. Fortran から呼び出される C++ コード (cplus.h)
#include <iostream.h> template<class T> class junk { private: int inter; T templ_mem; T stor_val; public: junk(int i,T j): inter(i),templ_mem(j) {cout <<"***Inside C++ constructor" << endl;} junk() {cout <<"***Inside C++ Destructor" << endl;} void store(T *val){ stor_val = *val;} void print(void) {cout << inter << "t" << templ_mem ; cout <<"¥t" << stor_val << endl; }}; template<class T> class temp { private: int internal; T temp_var; public: temp(int i, T j): internal(i),temp_var(j) {cout <<"***Inside C++ temp Constructor" <<endl;} temp() {cout <<"***Inside C++ temp destructor" <<endl;} void print(void) {cout << internal << "¥t" << temp_var << endl;}};
このプログラムをコンパイルし、xlC またはg++ コマンドとリンクして実行したときの出力は次のようになります。
Inside Fortran calling first C function %Inside C function before creating C++ Object ***Inside C++ constructor 10 30 35 %Inside C function after creating C++ Object ***Inside C++ Destructor Inside Fortran calling second C function %Inside C function cfun1 before creating C++ Object ***Inside C++ temp Constructor 40 50.54 %Inside C function after creating C++ temp object ***Inside C++ temp destructor Exiting the Fortran program