XL Fortran for AIX V8.1.1

ユーザーズ・ガイド


Fortran と C++ の混在

この章の多くの情報は Fortran、C、および Pascal (これらの言語はデータ型と命名体系が似ている) に適用されます。しかし、Fortran と C++ を同じプログラムに混合させるためには、間接のレベルを余分に追加し、C の「wrapper」関数で言語間呼び出しを渡す必要があります。

C++ コンパイラーはいくつかの C++ オブジェクト名を「壊してしまう」ため、xlC コマンドを使用して最後のプログラムをリンクし、ld コマンドを使用した 32 ビット非 SMP オブジェクト・ファイルのリンクに示されているように 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 ラップ関数 (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 コマンドとリンクして実行したときの出力は次のようになります。

 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


[ ページのトップ | 前ページ | 次ページ | 目次 | 索引 ]