TweetFollow Us on Twitter

XCMD ANSI Library
Volume Number:6
Issue Number:6
Column Tag:Programmer's Forum

XCMD ANSI Library

By Gerry H. Kenner, David Burggraaf, Salt Lake City, UT

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

XCMD ANSI Library

[Gerry Kenner is a conservative senior citizen who has been working with computers and writing scientific papers since 1962 when the era first began. David Burggraaf is a newcomer to the field who got his first computer (a Sinclair) in 1980 and hasn’t stopped being excited since. Suffice it to say that most of the ideas and all of the work involved in this project were done by David.]

With their fixed methods of entering, retrieving and manipulating data, code resource packages appear to be the ideal system of object oriented programming. In this case, the object is the code resource. The popularity of this concept is shown by the use of code resources under different names by 4th Dimension™(external objects), Excel™ (DDLs) and Hypercard™ (XCMDs and XFCNs). Further, pioneer systems for using code resources in standalone programs are becoming available, the first example being Serius89™ but other programs are not far behind.

A problem with this type of programming is that the libraries must be replicated whenever they are used in different code resources. Further, when doing code resources at least some compilers link in all functions in a library and not just the ones being used. This is in contrast to the smart linking which occurs when standalone applications are generated. Experience has shown us that the size of most code resources can be reduced by 50% while some can be reduced by as much as 70% or more if the library routines are removed.

This paper reports on a method for installing the libraries and a jump table to access them as a separate code resources and then using a simple series of calls to access them from other code resources (Hypercard XCMDs in this case).

The Project

The project consisted of putting all the library functions in two code resources of type “LIB “ called CodeLib and FCodeLib. Two code resources were used because the dispatch routines for functions which return arguments longer than 32 bits are different from the cases where the return value will fit in register D0. Included in each library is the code of the library functions and a dispatch routine (main()) to provide access to them. The “LIB “ type resources are loaded into Hypercard or stacks using ResEdit.

The .h file

The CodeLib.h file includes the necessary definitions and macros for setting up the libraries in XCMD projects. Included are the list of index variables for each function call (i.e., CLatoi, CLatol, etc.), macro definitions for redefining return parameters and library function call names (#define atoi(str) ((**idispatch) (CLatoi,(char*)(str))), and typedef void (**Vfunch) (CodeLib,...);, etc.) and the macro calls which are added to the XCMD project for incorporating the above material in source code.

Perhaps the best method for understanding the contents of this file is to follow the compilation and execution of the main routine of the XCMD following the addition of the special library code. First of all, the contents of CodeLib.h are read in. In addition to declaring the macros and index variables, this file defines the handles VFunch, IFunch, etc and declares extern global variables of these types (dispatch, idispatch, etc). When executed the macro CODELIB legitimitizes the extern declaration of these variables by declaring them within the XCMD.

LOADCODELIB() is a function which appears as follows when unfolded.

/* 1 */

LOADCODELIB()
if (!initCodeLib())
 return;
else
 HLock(dispatch);
if (!initFCodeLib())
 HUnlock(dispatch);
 return;
else
 HLock(ddispatch);

Its function is to determine whether the libraries are present, get handles to them and then lock the handles so the libraries won’t move. Otherwise it returns with nothing being done. The task of getting the handles is done by initCodeLib() and initFCodeLib. The initCodeLib macro is expanded to show how this is done.

/* 2 */

initCodeLib()
fdispatch = (Ffunch)GetResource(‘LIB ‘, 18000);
pdispatch = (Pfunch)fdispatch;
cdispatch = (Cfunch)pdispatch;
ldispatch = (Lfunch)cdispatch;
idispatch = (Ifunch)ldispatch;
dispatch = (Vfunch)idispatch;

Note that all the handles point to the same address.

With the above code in place, execution of a code line such as

/* 3 */

 TempInt = atoi(TempStr);

will result in the following at compilation time.

/* 4 */

 TempInt = ((**idispatch)(CLatoi, (char*)TempStr)));

When executed, this code will pass the address of idispatch, the value of the index CLatoi and the contents of TempStr to the library code resource.

A Special Case

An exception to the above ease of use are function calls such as sprintf which pass variable numbers of arguments. In these cases, the definitions in the CodeLib.h file serve as templates for inserting the code manually. For instance, the definition of sprintf(s,f) is ((**idispatch)(CLsprintf, (s), (f), ...)). When a statement such as sprintf(TempStr, “Good Day”) is encountered the programmer must replace it manually with ((**idispatch) (CLsprintf, TempStr, “Good Day”) using the definition as a guide.

CodeLibDispatch.c

This file shares the CodeLib.h file except it does not include the NOCODELIB definitions for redefining the library function call names. Addressing the library functions is taken care of by declaring the following code before the main routine is called.

/* 5 */

typedef void (*Function)(void);
FunctionfuncTable[ROUTINES + 1]

where the value of ROUTINES was declared in CodeLib.h. Values are assigned to the funcTable variable within the main routine as follows.

/* 6 */

funcTable[CLdispatchErr]=dispatchErr;
funcTable[CLatoi]=(Function)atoi;
funcTable[CLatol]=(Function)atol;
funcTable[CLsprintf]=(Function)sprintf;
funcTable[CLsrand]=(Function)srand;
funcTable[CLstrcpy]=(Function)strcpy;

It would be nice if these could be declared statically, but we have not been able to figure out a method for doing it.

There are two segments of assembly language code. The first segment replaces the calls RememberA4() and SetUpA4() which are not used because they shift things around on the stack. This code stores the current value of A4 and replaces it with the address of the main routine which is stored in A0 when the code is called. The second assembly language segment is a glue routine for configuring the stack before jumping to the desired library function.

/* 7 */

 asm  {
 move.l (a7)+, returnAddr;/*save return address*/
 move.w (a7)+, a1; /*remove index*/
 lea funcTable, a0;/*do jump to indexed subroutine*/
 jsr ([0,a0,a1.w*4],0);
 move.w a1, -(a7); /*restore stack and return*/
 move.l returnAddr, -(a7);
 move.l oldA4, a4; /*restore a4  */
 }

It removes the return address and saves it before doing a jsr to the requested funcTable entry after which it is put back on the stack. The index value is also removed from the stack, placed in a1 for use as an offset and then replaced on the stack at the end of the call. The last line of code restores the old value of a4.

General

Note that there are six dispatch types although only four are used in this code. The remaining two are for functions which return floats and structures. Further functions can be added to by using the formats given. We have included the code of a sample Hypercard XCMD which uses the libraries or of a Hypercard stack to exercise the XCMD. Other examples are left as an exercise for the reader.

This project is written with THINK C. Similar code would be difficult though possible to implement in Pascal. An important point to note if you are using calls which use floating point arithmetic or call the printf type functions is that the standard ANSI-A4 library does not include floating point functions nor math functions. The math functions are gained by adding math.c to the ANSI-A4 library project. Floating point capabilities are added by opening the ansi-config.h file which is found in the source code of the ANSI-A4 project and commenting out the line #define _NOFLOATING_ and then recompiling the project under a different name such as ANSI-A4(f). Another point to remember is that other functions such as qsort and atof are also not part of the ANSI-A4 project and must be added if they are to be used.

If you have any questions David can be reached on internet at BURGGRAAF @ cc.utah.edu.

Installation Instructions:

1. Install the Library code resource wherever it is needed, i.e., as a code resource in your Hypercard stack.

2. Include the “CodeLib.h” header file before any of the functions in the code library are called.

3. Enter the line

CODELIB;

before any function in the library is called. It must be typed outside of any function. It is a preprocessor declaration of the necessary global variables.

4. If they are not already part of your code put in the instructions RememberA0, SetUpA4 and RestoreA4, so that the above global variables can be used.

5. In the main function, at the beginning type the line.

LOADCODELIB();

This should be the first function call other than functions which setup registers for global variable access. (i.e., SetupA4()).

6. In the main function, at the end enter the line.

UNLOADCODELIB();

7. If present, remove any duplicate libraries which are present in your project.

8. Build the project.

Listing:  CodeLib.h

#ifndef _CODE_LIB_
#define _CODE_LIB_
typedef enum
 {
 CLdispatchErr=0,
 CLatoi,
 CLatol,
 CLsprintf,
 CLsrand,
 CLstrcpy,
 CLsqrt=1 /*Double/struct lib */
 } CodeLib;

#define ROUTINES 5
#define FROUTINES  1

#ifndef NOCODELIBDEF
#define atoi(str) ((**idispatch)(CLatoi,(char *)(str)))
#define atol(str) ((**ldispatch)(CLatol,(char *)(str)))
#define sprintf(s,f) ((**idispatch)(CLsprintf,(s),(f),...))
#define srand(s) ((**dispatch)(CLsrand,(unsigned)(s)))
#define strcpy(s1,s2) ((char *)((**pdispatch)(CLstrcpy,(char*)(s1),(char 
*)(s2))))
#define sqrt(d) ((**ddispatch)(CLsqrt, (double)(d)))
#endif NOCODELIBDEF

typedef void (**Vfunch)(CodeLib,...);
typedef int (**Ifunch)(CodeLib,...);
typedef long (**Lfunch)(CodeLib,...);
typedef char (**Cfunch)(CodeLib,...);
typedef float (**Ffunch)(CodeLib,...);
typedef double (**Dfunch)(CodeLib,...);
typedef void *(**Pfunch)(CodeLib,...);

#define CODELIB Vfunch dispatch;Ifunch idispatch;Lfunch ldispatch;Cfunch 
cdispatch;Ffunch fdispatch;Dfunch ddispatch;Pfunch pdispatch;
#ifndef NOTLLIB
#define initCodeLib() (dispatch=(Vfunch)(idispatch=(Ifunch)(ldispatch=(Lfunch)(cdispatch=( 
Cfunch)(pdispatch=(Pfunch)(fdispatch=(Ffunch)GetResource(‘LIB ‘, 18000)))))))
#else
#define initcodeLib() 1
#endif CODELIB

#ifndef NOFLOATLIB
#define initFCodeLib() (ddispatch=(Dfunch)GetResource(‘LIB ‘, 18001))
#else
#define initFCodeLib() 1
#endif NOFLOATLIB

#define LOADCODELIB() {if (!initCodeLib()) return;else HLock(dispatch);if 
(!initFCodeLib()) {HUnlock(dispatch);return;}else HLock(ddispatch);}
#define UNLOADCODELIB() {HUnlock(dispatch);HUnlock(ddispatch);}

extern Vfunch dispatch;
extern Ifunch idispatch;
extern Lfunch ldispatch;
extern Cfunch cdispatch;
extern Ffunch fdispatch;
extern Dfunch ddispatch;
extern Pfunch pdispatch;
#endif
Listing:  CodeLibDispatch.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define NOCODELIBDEF
#include “CodeLib.h”

typedef void (*Function)(void);

long returnAddr, oldA4;
int funcIndex;
void dispatchErr(void);
Function funcTable[ROUTINES+1];
 
void main(void)
 { /* CodeLib routine*/
 asm  {
 move.l a4, a1;  /*setup a4 */
 move.l a0, a4;
 move.l a1, oldA4;
 };
 funcTable[CLdispatchErr]=dispatchErr;
 funcTable[CLatoi]=(Function)atoi;
 funcTable[CLatol]=(Function)atol;
 funcTable[CLsprintf]=(Function)sprintf;
 funcTable[CLsrand]=(Function)srand;
 funcTable[CLstrcpy]=(Function)strcpy;
 asm  {
 move.l (a7)+, returnAddr;/*save return address*/
 move.w (a7)+, a1; /*remove index  */
 lea funcTable, a0;/*do jump to indexed subroutine*/
 jsr ([0,a0,a1.w*4],0);
 move.w a1, -(a7); /*restore stack and return*/
 move.l returnAddr, -(a7);
 move.l oldA4, a4; /*restore a4  */
 }
 UnloadA4Seg(0L);
 } /* Main*/

void dispatchErr(void)
 {
 SysBeep(5);
 }
Listing:  FCodeLibDispatch.c

#include <math.h>

#define NOCODELIBDEF
#include “CodeLib.h”

typedef void (*Function)(void);

long returnAddr, oldA4, returnStruct;
int funcIndex;
void dispatchErr(void);
Function funcTable[FROUTINES+1];
 
void main(void)
 { /*CodeLib routine*/
 asm  {
 move.l a4, a1;  /*setup a4 */
 move.l a0, a4;
 move.l a1, oldA4;
 };
 funcTable[CLdispatchErr]=dispatchErr;
 funcTable[CLsqrt]=(Function)sqrt;
 asm  {
 move.l (a7)+, returnAddr;/*save return address*/
 move.l (a7)+, returnStruct;/*save return StructPtr*/
 move.w (a7)+, a1; /*remove index  */
 move.l returnStruct, -(a7);/*put return StructPtr*/
 lea funcTable, a0;/*do jump to indexed subroutine*/
 jsr ([0,a0,a1.w*4],0);
 move.l (a7)+, returnStruct;/*get return structPtr*/
 move.w a1, -(a7); /*restore stack and return*/
 move.l returnStruct, -(a7);
 move.l returnAddr, -(a7);
 move.l oldA4, a4; /*restore a4  */
 }
 UnloadA4Seg(0L);
 } /* Main*/

void dispatchErr(void)
 {
 SysBeep(5);
 }

Listing: testCodeLib.c

#include “CodeLib.h”
#include “HyperXCmd.h”
#include “SetUpA4.h”

CODELIB;

pascal void main(XCmdBlockPtr paramPtr)
{
 int    TempInt1, TempInt2;
 unsigned int  Seed;
 long   TempLong;
 StringHandle  TempHdl;
 double TempDouble1, TempDouble2;
 Ptr    TempPtr;
 Str255 TempStr;
 
 RememberA0();
 SetUpA4();
 LOADCODELIB();
 TempHdl = (StringHandle)NewHandle(256);
 TempPtr = *(paramPtr->params[0]);
 TempInt1 = atoi((char*)TempPtr);
 TempPtr = *(paramPtr->params[1]);
 TempLong = atol((char*)TempPtr);
 TempInt2 = (int)TempLong;
 TempInt1 = TempInt1 * TempInt2;
 TempDouble2 = (double)TempInt1;
 TempDouble1 = sqrt(TempDouble2);
 Seed = (unsigned int)TempDouble1;
 srand(Seed);
 (**idispatch)(CLsprintf,TempStr, “The square root of %d is %.2g.”,
 TempInt1, TempDouble1);
 strcpy(*TempHdl, TempStr);
 paramPtr->returnValue = (Handle)TempHdl;
 
 UNLOADCODELIB();
 RestoreA4();
}

 

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.