TweetFollow Us on Twitter

C++ Methods, Fortran
Volume Number:7
Issue Number:2
Column Tag:Jörg's Folder

Related Info: Quickdraw

C++ Methods In FORTRAN

By Jörg Langowski, Editorial Board

“C++ Methods in FORTRAN”

This article had to come. Next thing you’ll see, you may think, is calling Eiffel from Forth. But seriously, implementing cross-language calling very often helps you to understand how one particular language really works and how to get most out of it. Also, the Fortran run time system has some advantages, like well-designed console I/O that may help in debugging, file I/O, an easily accessible output window, and therefore adding it may be very helpful in some applications. So here we go, and write a C++ method in Language Systems Fortran.

C++ methods are really independent subroutines, and the association between a method and its class is done through the header file - on the source code side - and through the modified method name on the object code side. When you define two different classes with methods of the same name, as in

// 1

class aaa {
 public:
 void doit();
}

class bbbb {
 public:
 void doit();
}

the methods are usually defined in a place different from where they are actually used. In fact, most often they may be pre-compiled in a library. The linker can distinguish between the two different doit methods, because their symbolic name on the linker level is modified by the class name. The two methods’ names in this case would be: doit__3aaaFv and doit__4bbbbFv.

C++ Function Name Encoding

To remind you of the C++ linker naming conventions: the first part of the linker name is the method name (doit), followed by two underscores. Then follows the class name, preceded by the number of characters in that name. Appended to that are some symbols describing the parameter list. In our case, for methods taking no parameters, it is simply “Fv”. F stands for a function, v for a void parameter list. I am not describing all the modifiers that are used in creating a linker name out of a C++ method name; the full encoding scheme is described in the AT&T C++ release notes, chapter 6, page 22.

Usually, you never see the encoded names; only when e.g. a method is defined in a class header file, then referenced by some code using objects from that class, but never actually implemented, the linker might complain about a missing function. There, you will probably have seen those funny names already, and used the MPW unmangle tool to make sense out of them.

Here, we want to go the other direction. When we implement a C++ method in some non-object language, we must write a routine that has the encoded method’s name. The easiest way to find out about the linker name of a C++ method is not to construct it yourself (you never get it right in the first place), but just to define the method in the class header, use it in the code, and never actually implement it. The linker will tell you in its error message what function it is looking for.

That way I found out that the name for the method pascal void FtnCall() in the class TMacTutorDocument is FTNCALL__17TMACTUTORDOCUMENT. The characters “Fv” are not appended here, and the name is written in all capitals, because of the “pascal” keyword. This also means that all external Pascal-type methods of the same name in the same class will have the same linker name, regardless of the argument list.

Language Systems Fortran, of course, uses Pascal calling conventions, so a method written in Fortran will have to be defined in C++ as pascal. We want to pass some parameters, so lets define an argument list:

{2}

pascal void FtnCall(short *menuitem, long k, float *r);

The method will later be called from a menu handler, just for the fun of it, and we pass the number of the menu item selected, and some numbers. Note one restriction here: LS Fortran symbolic names are limited to 31 characters, so don’t use too complicated class and method names if you don’t want to run out of space.

The Sample Program

We use the sample program that I showed you in V6#1: Apple’s C++ mini-application skeleton. You should now go back to your library and get that MacTutor issue, or reorder it, because we obviously cannot reprint its full source here. Listing 2 only shows those parts that have been changed.

In the constructor and destructor methods of the application class we have added calls to InitFortran() and ExitFortran() for initializing the Fortran run time system at the start of the program and leaving it properly at the end. During the program, then, the run time system is at our disposal. The Fortran method is defined in the class TMacTutorDocument. It is used in the TMacTutorApp class, in its DoMenuCommand method:

// 3

x = 4.567;
fMacTutorCurDoc->FtnCall(&menuItem,3456,&x);

This way we have some calls by reference (standard Fortran calling convention), and one call by value.

The Fortran routine (listing 1) receives the three parameters in the same order. Furthermore, on every method call a handle to the method’s current object (this) is pushed on the stack after all the method’s parameters. The Fortran code has to take that extra parameter into account. Thus, the first line of the Fortran routine will be

C 4

subroutine FTNCALL__17TMACTUTORDOCUMENT
 (menuitem,%val(k),r,%val(this))  .

menuitem and r are passed by reference, k is received by value (Language Systems Fortran has an option for receiving parameters by value in the subroutine definition). this is also received by value. Through this, we can access the instance variables of the method’s current object. We also define the list of instance variables, which becomes rather complicated as we have to dereference handles in the (Languages Systems) Fortran way. The structure definitions at the beginning of the Fortran routine show you how to do that.

this points to the beginning of the object’s instance variables, starting with those of the topmost ancestor class and descending through the class hierarchy. In our case, we have a window pointer fDocWindow and the pointer to the virtual methods table vptr from the TDocument class, then the instance variables of TMacTutorDocument, fItemSelected and fDisplayString.

The main body of the routine displays the passed parameters and some information about the instance variables in the Fortran output window.

That’s all! You’re now able to add Fortran code to C++ programs as you like, and have it behave like real C++ methods.

Listing 1: C++ method written in Fortran

CC++ test method written in Language Systems Fortran
CFor editing, some of the lines had to be split. I have not
Ccreated proper Fortran continuation lines, because a. C I’m lazy and 
b. I think the text can be read better that 
Cway -- jl --

 subroutine FTNCALL__17TMACTUTORDOCUMENT
 (menuitem,%val(k),r,%val(this))
Cpascal void FtnCall__17TMacTutorDocument
 (short *menuitem, long k, float *r, 
 struct TMacTutorDocument **);
 include “Quickdraw.f”

 structure /MTDocVars/
 record /WindowPtr/ fDocWindow
 integer*4 vptr
 integer*2 fItemSelected
 record /StringPtr/ fDisplayString
 end structure
 
 structure /MTDocPtr/
 pointer /MTDocVars/ p
 end structure
 
 structure /MTDocHdl/
 pointer /MTDocPtr/ h
 end structure
 
 record /MTDocHdl/ this
 
 integer*2 menuitem

 integer top,left,bottom,right
 
 call MoveOutWindow (20,260,490,340)
 write (*,*) “Arguments to FtnCall:”,menuitem,k,r
 write (*,*) “fItemSelected = “,this.h^.p^.fItemSelected
 write (*,*) “fDisplayString = 
 “,this.h^.p^.fDisplayString.sptr^
 
 top    = this.h^.p^.fdocwindow.wp^.portrect.top
 bottom = this.h^.p^.fdocwindow.wp^.portrect.bottom
 left   = this.h^.p^.fdocwindow.wp^.portrect.left
 right  = this.h^.p^.fdocwindow.wp^.portrect.right
 write (*,*) “doc window = “,top,left,bottom,right
 return
 end
Listing 2: Changes to the .cp and .h files from the V6#1 example

File MacTutorApp.make:

OBJECTS = TApplication.cp.o TDocument.cp.o 
 MacTutorApp.cp.o MacTutorDoc.cp.o 
 MacTutorGrow.cp.o FtnCall.f.o
HEADERS = MacTutorApp.h MacTutorDoc.h 
 MacTutorGrow.h

TApplication.cp.o ƒ TApplication.cp TApplication.h
  CPlus  TApplication.cp
TDocument.cp.o ƒ TDocument.cp TDocument.h
  CPlus  TDocument.cp
MacTutorApp.cp.o ƒ MacTutorApp.make 
 {HEADERS} MacTutorApp.cp
  CPlus  MacTutorApp.cp
MacTutorDoc.cp.o ƒ MacTutorApp.make 
 {HEADERS} MacTutorDoc.cp
  CPlus  MacTutorDoc.cp
MacTutorGrow.cp.o ƒ MacTutorApp.make 
 {HEADERS} MacTutorGrow.cp
  CPlus  MacTutorGrow.cp
FtnCall.f.o ƒ MacTutorApp.make FtnCall.f
  Fortran -mc68020 -mc68881 -opt=3 -bkg=0 FtnCall.f

MacTutorApp ƒƒ MacTutorApp.make {OBJECTS}
 Link -w -t APPL -c JLMT 
 “{CLibraries}”CRuntime.o 
 {OBJECTS} 
 “{Libraries}”Interface.o 
 “{CLibraries}”StdCLib.o 
 “{CLibraries}”CSANELib.o 
 “{CLibraries}”Math.o 
 “{CLibraries}”CInterface.o 
 “{CLibraries}”CPlusLib.o 
 #”{CLibraries}”Complex.o 
 “{FLibraries}FORTRANLib.o” 
 -o MacTutorApp

MacTutorApp ƒƒ MacTutorApp.make MacTutorApp.r
 Rez MacTutorApp.r -append -o MacTutorApp

File MacTutorApp.h:

class TMacTutorApp : public TApplication {
public:
 TMacTutorApp(void); // Our constructor
 ~TMacTutorApp(void);
 // need a destructor to call EXITFORTRAN

private:
 // routines from TApplication we are overriding
 long HeapNeeded(void);
 unsigned long SleepVal(void);
 void AdjustMenus(void);
 void DoMenuCommand
 (short menuID, short menuItem);

 // routines for our own devious purposes
 void DoNew(void);
 void Terminate(void);
};

File MacTutorDoc.h:

class TMacTutorDocument : public TDocument {
  protected:
 short fItemSelected;
 // string corresponding to menu item selected
 StringPtr fDisplayString;

 void DrawWindow(void);

  public:
 TMacTutorDocument(short resID, StringPtr s);
 ~TMacTutorDocument(void); 
 // routine to access private variables
 void SetDisplayString (StringPtr s) {fDisplayString = s;}
 short GetItemSelected(void) {return fItemSelected;}
 void SetItemSelected(short item) {fItemSelected = item;}

 // methods from TDocument we override
 void DoUpdate(void);
 
 // Fortran calling;
 pascal void FtnCall(short *menuitem, long k, float *r);
};

File MacTutorApp.cp:

pascal void initFortran();
pascal void exitFortran();

// Methods for our application class
TMacTutorApp::TMacTutorApp(void)
{
 Handle menuBar;

 initFortran(); // initialize Fortran runtime system
 
 // read menus into menu bar
 menuBar = GetNewMBar(rMenuBar);
 // install menus
 SetMenuBar(menuBar);
 DisposHandle(menuBar);
 // add DA names to Apple menu
 AddResMenu(GetMHandle(mApple), ‘DRVR’);
 DrawMenuBar();

 // create empty mouse region
 fMouseRgn = NewRgn();
 // create a single empty document
 DoNew();
}

TMacTutorApp::~TMacTutorApp(void)
{
 exitFortran(); // exit Fortran runtime system
}

void TMacTutorApp::DoMenuCommand
 (short menuID, short menuItem)
{
 short  itemHit;
 Str255 daName;
 short  daRefNum;
 float  x;// for testing the Fortran call
 WindowPtrwindow;
 TMacTutorDocument* fMacTutorCurDoc =
 (TMacTutorDocument*) fCurDoc;

 window = FrontWindow();
 switch ( menuID ) {
 case mApple:
 switch ( menuItem ) {
 case iAbout:    // About box
 itemHit = Alert(rAboutAlert, nil);
 break;
 default: // DAs etc.
 GetItem(GetMHandle(mApple), menuItem, daName);
 daRefNum = OpenDeskAcc(daName);
 break;
   }
 break;
 case mFile:
 switch ( menuItem ) {
 case iNew:
 DoNew();
 break;
 case iClose:
 if (fMacTutorCurDoc != nil) {
 fDocList->RemoveDoc(fMacTutorCurDoc);
 delete fMacTutorCurDoc;
   }
 else CloseDeskAcc(((WindowPeek) 
 fWhichWindow)->windowKind);
 break;
 case iQuit:
 Terminate();
 break;
   }
 break;
 case mEdit: // SystemEdit for DA editing & MultiFinder 
 if ( !SystemEdit(menuItem-1) ) {
 switch ( menuItem ) {
 case iCut:
 break;
 case iCopy:
 break;
 case iPaste:
 break;
 case iClear:
 break;
    }
   }
 break;
 case myMenu:
 if (fMacTutorCurDoc != nil) {
 switch ( menuItem ) {
 case item1:
 fMacTutorCurDoc->
 SetDisplayString(“\pC++”);
 break;
 case item2:
 fMacTutorCurDoc->
 SetDisplayString(“\pSample”);
 break;
 case item3:
 fMacTutorCurDoc->
 SetDisplayString(“\pApplication”);
 break;
 case item5:
 fMacTutorCurDoc->SetDisplayString(“\pHave Fun”);
 x = 4.567;
 fMacTutorCurDoc->FtnCall(&menuItem,3456,&x);
 break;
    }
 fMacTutorCurDoc->SetItemSelected(menuItem);
 InvalRect(&(window->portRect));
 fMacTutorCurDoc->DoUpdate();
 }
 break;
   }
 HiliteMenu(0);
} // DoMenuCommand


 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.