Re: [ROOT] How to link fortran and c++

From: Brett Viren (bv@bnl.gov)
Date: Wed Apr 04 2001 - 15:48:21 MEST


Besides the suggestion to make sure the fortran code actually takes
REAL*8 instead of just REAL, I think your declaration and calling is
wrong.  Fortran ``passes by reference'' but this really means ``passes
by pointer''.  (At least this has always been the case when I mix C
and Fortran).  So, I think your declaration should be:

    extern "C" void herfasy_(double*,double*, double*,double*);

And you should call it like:

    herfasy_(&Enbeam,&thetas,&omega,&asytt);

Luck,
-Brett.

Wang Xu writes:
 > Dear Rooters,
 > 	I try to link a fortran code(herasy.f) to the c++ code. The
 > fortran code by itself works fine but if it link to this c++ code, one of
 > subroutine of the fortran code dosen't give a right answer. Have you ever
 > met same problem? If you did, please give me some suggestion as soon as
 > possible.
 > (I suspicious that I didn't put correct flag when I complie these two
 > code. what I did is following:
 >  f77 -c herfasy.f *.f 
 >  g++ -c acceptance.cxx
 >  g++ herfasy.o *.o acceptance.o -L/lib -l* -lg2c)
 > 	Thanks,
 > 	wang   
 > Here is the acceptance.cxx
 > #include <stdio.h>
 > #include <iostream.h>
 > 
 > // ROOT include
 > #include "TROOT.h"
 > #include "TFile.h"
 > #include "TNtuple.h"
 > #include "TMath.h"
 > 
 > extern "C" void herfasy_(double &,double &, double &,double &);
 > 
 > int main()
 > {
 >   TROOT accept("accept","accept");
 >   TFile *f = new
 > TFile("/work/halla/e95001-2/wangxu/hbook/eq05/gmn_1pass_21067.root");
 > TNtuple *h1 = (TNtuple*) f->Get("h1");
 >   Float_t  asyt,thetat, yt, phit, deltat;
 >   double Enbeam,omega,thetas,asytt;
 >   Int_t nbytes;
 >   Enbeam=1.727; 
 >   Float_t Eset=1.453;
 >   Float_t thed = 25.80;
 >   // Set branch addresses
 >   h1->SetBranchAddress("Ethetat",     &thetat);  // in mr
 >   h1->SetBranchAddress("Ephit", &phit);          // in mr
 >   h1->SetBranchAddress("Eyt",     &yt);          // in mm
 >   h1->SetBranchAddress("Edelta", &deltat);      // in %  
 >   TFile *acceptance = new TFile("acceptance.root", "RECREATE");
 >     TNtuple *ntuple = new TNtuple("ntuple", "Asymetry Study",
 >      "Ethetat:Ephit:Eyt:Edelta:asyt");
 >   // Total event number
 >     //Int_t nentries = (Int_t) h1->GetEntries();
 >    Int_t nentries=1;
 >    for(Int_t i=0; i<nentries; i++) {
 >     nbytes += h1->GetEvent(i);
 >     thetas=acos(cos(thed*3.1415926/180+phit/1000)*cos(thetat/1000));
 >     thetas= thetas*180/3.1415926;
 >     omega=Enbeam-Eset*(1+deltat/100); 
 >     herfasy_(Enbeam,thetas,omega,asytt);
 >     asyt=asytt;
 >     printf("%f\n",asyt);
 >    ntuple->Fill(thetat,phit,deltat,asyt);
 >    }
 >  ntuple->Write(); 
 >   f->Close();
 >   acceptance->Close();  
 >    return(0);
 > }
 > 
 > 
 > 
 > 
 > 
 > 



This archive was generated by hypermail 2b29 : Tue Jan 01 2002 - 17:50:41 MET