C Library and ALGOL Client Program

The following pair of examples illustrate the ability of an ALGOL calling program to indirectly access character data in a C library.

The following C library exports a procedure named WRITELINE. This procedure accepts a parameter that is a pointer to a string of characters. The procedure writes the string to a file named TEST.

#include <stdio.h>
#include <stdlib.h>
FILE * pf;

asm WRITELINE(char * pc) {
        fputs(pc, pf);
        fputc('\n',pf);
}

void cleanup(void) {
        /* called after main exits, i.e., after thaw */
        fputs(“all done\n”, pf);
        fclose(pf);
} 

main() {
        pf = fopen(“TEST”, “w”);
        atexit(cleanup);

}

The C library is called by the following ALGOL client program:

BEGIN
LIBRARY CLIB(LIBACCESS = BYTITLE, TITLE=“OBJECT/STREAM/C.”);
INTEGER PROCEDURE MALLOC(BYTES);
   VALUE                 BYTES;
   INTEGER               BYTES;
   LIBRARY CLIB;
INTEGER PROCEDURE FREE(CPTR);
   VALUE               CPTR;
   INTEGER             CPTR;
   LIBRARY CLIB;
INTEGER PROCEDURE HEAPTOPTR(CPTR, APTR);
   VALUE                    CPTR     ;
   INTEGER                  CPTR     ;
   POINTER                        APTR;
   LIBRARY CLIB;
INTEGER PROCEDURE WRITELINE(CPTR);
   VALUE                    CPTR;
   INTEGER                  CPTR;
   LIBRARY CLIB;

PROCEDURE XFER(S);
   VALUE       S;
   STRING      S;
BEGIN
   POINTER APTR;
   INTEGER CPTR;
   CPTR:=MALLOC (LENGTH(S) + 1);
   HEAPTOPTR(CPTR, APTR);
   REPLACE APTR BY S, 48 “00”;
   WRITELINE(CPTR);
   FREE     (CPTR);
END XFER;

XFER(“HELLO WORLD”);
XFER(“THIS IS AN EXAMPLE”);

END.

In addition to importing WRITELINE from the C library, this program also imports the procedures MALLOC, HEAPTOPTR, and FREE. These procedures are implicitly created by the #include <stdlib.h> statement in the C library, and are referred to in C as __malloc_t, __heap_to_ptr_t, and __free_t.

The ALGOL program includes the XFER procedure, which accepts a string parameter and writes it to the file TEST by making appropriate calls on the C library. First, XFER invokes the MALLOC procedure, which allocates memory space for the string. MALLOC returns an integer, CPTR, which indicates the position of the string in memory.

CPTR can be used as a pointer only within the C library itself. To write data into the memory area allocated by MALLOC, the ALGOL program must first assign an ALGOL-style pointer to that memory location. The program does this with the call on HEAPTOPTR. The ALGOL program then uses the REPLACE statement to write the string to the area allocated for it.

The ALGOL program then invokes the WRITELINE procedure, passing CPTR as a parameter. The WRITELINE procedure in the C library uses CPTR to locate the string that is to be written to the file.