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

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.