# The Ghostscript Interpreter Application Programming Interface (API)

Contact Us
Download
The Ghostscript Interpreter Application Programming Interface (API)

## Table of contents

- What is the Ghostscript Interpreter API?
- Exported functions

- `gsapi_revision`
- `gsapi_new_instance`
- `gsapi_delete_instance`
- `gsapi_set_stdio`
- `gsapi_set_poll`
- `gsapi_set_display_callback`
- `gsapi_set_arg_encoding`
- `gsapi_run_string_begin`
- `gsapi_run_string_continue`
- `gsapi_run_string_end`
- `gsapi_run_string_with_length`
- `gsapi_run_string`
- `gsapi_init_with_args`
- `gsapi_run_*`
- `gsapi_exit`
- `gsapi_add_fs`
- `gsapi_remove_fs`
- Return codes

- Example usage
- Standard input and output
- Display device

For other information, see the Ghostscript overview.

WARNING: The API described in this document is subject to changes in future releases, possibly ones that are not backward compatible with what is described here.

## What is the Ghostscript Interpreter API?

The Ghostscript interpreter can be built as a dynamic link library (DLL) on Microsoft Windows, as a shared object on the Linux, Unix and MacOS X platforms. With some changes, it could be built as a static library. This document describes the Application Programming Interface (API) for the Ghostscript interpreter library. This should not be confused with the Ghostscript library which provides a graphics library but not the interpreter.

This supercedes the old DLL interface.

To provide the interface described in the usage documentation, a smaller independent executable loads the DLL/shared object. This executable must provide all the interaction with the windowing system, including image windows and, if necessary, a text window.

The Ghostscript interpreter library's name and characteristics differ for each platform:

- The Win32 DLL `gsdll32.dll` can be used by multiple programs simultaneously, but only once within each process.
- The OS/2 DLL `gsdll2.dll` has MULTIPLE NONSHARED data segments and can be called by multiple programs simultaneously.
- The Linux shared object `libgs.so` can be used by multiple programs simultaneously.

The source for the executable is in `dw`*.* (Windows), `dp`*.* (OS/2) and `dx`*.* (Linux/Unix). See these source files for examples of how to use the DLL.

The source file `dxmainc.c` can also serve as an example of how to use the shared library component on MacOS X, providing the same command-line tool it does on any linux, bsd or similar operating system.

At this stage, Ghostscript does not support multiple instances of the interpreter within a single process.

## Exported functions

The functions exported by the DLL/shared object are described in the header file `iapi.h` and are summarised below. Omitted from the summary are the calling convention (e.g. __stdcall), details of return values and error handling.

- `int gsapi_revision (gsapi_revision_t *pr, int len);`
- `int gsapi_new_instance (void **pinstance, void *caller_handle);`
- `void gsapi_delete_instance (void *instance);`
- `int gsapi_set_stdio (void *instance, int(*stdin_fn)(void *caller_handle, char *buf, int len), int(*stdout_fn)(void *caller_handle, const char *str, int len), int(*stderr_fn)(void *caller_handle, const char *str, int len));`
- `int gsapi_set_poll (void *instance, int(*poll_fn)(void *caller_handle));`
- `int gsapi_set_display_callback (void *instance, display_callback *callback);`
- `int gsapi_set_arg_encoding (void *instance, int encoding);`
- `int gsapi_init_with_args (void *instance, int argc, char **argv);`
- `int gsapi_run_string_begin (void *instance, int user_errors, int *pexit_code);`
- `int gsapi_run_string_continue (void *instance, const char *str, unsigned int length, int user_errors, int *pexit_code);`
- `int gsapi_run_string_end (void *instance, int user_errors, int *pexit_code);`
- `int gsapi_run_string_with_length (void *instance, const char *str, unsigned int length, int user_errors, int *pexit_code);`
- `int gsapi_run_string (void *instance, const char *str, int user_errors, int *pexit_code);`
- `int gsapi_run_file (void *instance, const char *file_name, int user_errors, int *pexit_code);`
- `int gsapi_exit (void *instance);`
- `int gsapi_add_fs (void *instance, gsapi_fs_t *fs, void *secret);`
- `void gsapi_remove_fs (void *instance, gsapi_fs_t *fs, void *secret);`

### `gsapi_revision()`

> This function returns the revision numbers and strings of the Ghostscript interpreter library; you should call it before any other interpreter library functions to make sure that the correct version of the Ghostscript interpreter has been loaded.

> >     typedef struct gsapi_revision_s {
> >         const char *product;
> >         const char *copyright;
> >         long revision;
> >         long revisiondate;
> >     } gsapi_revision_t;
> >     gsapi_revision_t r;

> >     if (gsapi_revision(&r, sizeof(r)) == 0) {
> >         if (r.revision < 650)
> >            printf("Need at least Ghostscript 6.50");
> >     }
> >     else {
> >         printf("revision structure size is incorrect");
> >     }

### `gsapi_new_instance()`

> Create a new instance of Ghostscript. This instance is passed to most other gsapi functions. The caller_handle will be provided to callback functions. Unless Ghostscript has been compiled with the GS_THREADSAFE define, only one instance at a time is supported.

> Historically, Ghostscript has only supported a single instance; any attempt to create more than one at a time would result in gsapi_new_instance returning an error. Experimental work has been done to lift this restriction; if Ghostscript is compiled with the GS_THREADSAFE define then multiple concurrent instances are permitted.

> While the core Ghostscript devices are believed to be thread safe now, certain devices are known not to be (particularly the contrib devices). The makefiles currently make no attempt to exclude these from builds. If you enable GS_THREADSAFE then you should check to ensure that you do not rely on such devices (check for global variable use).

> The first parameter, is a pointer to an opaque pointer ("`void **`"). The opaque pointer ("`void *`") must be initialised to `NULL` before the call to `gsapi_new_instance()`. See Example 1.

### `gsapi_delete_instance()`

> Destroy an instance of Ghostscript. Before you call this, Ghostscript must have finished. If Ghostscript has been initialised, you must call `gsapi_exit` before `gsapi_delete_instance`.

### `gsapi_set_stdio()`

> Set the callback functions for stdio The stdin callback function should return the number of characters read, 0 for EOF, or -1 for error. The stdout and stderr callback functions should return the number of characters written.

### `gsapi_set_poll()`

> Set the callback function for polling. This function will only be called if the Ghostscript interpreter was compiled with `CHECK_INTERRUPTS` as described in `gpcheck.h`.

> The polling function should return zero if all is well, and return negative if it wants ghostscript to abort. This is often used for checking for a user cancel. This can also be used for handling window events or cooperative multitasking.

> The polling function is called very frequently during interpretation and rendering so it must be fast. If the function is slow, then using a counter to return 0 immediately some number of times can be used to reduce the performance impact.

### `gsapi_set_display_callback()`

> Set the callback structure for the display device. If the display device is used, this must be called after `gsapi_new_instance()` and before `gsapi_init_with_args()`. See `gdevdsp.h` for more details.

### `gsapi_set_arg_encoding()`

> Set the encoding used for the interpretation of all subsequent args supplied via the gsapi interface on this instance. By default we expect args to be in encoding 0 (the 'local' encoding for this OS). On Windows this means "the currently selected codepage". On Linux this typically means utf8. This means that omitting to call this function will leave Ghostscript running exactly as it always has. Please note that use of the 'local' encoding is now deprecated and should be avoided in new code. This must be called after `gsapi_new_instance()` and before `gsapi_init_with_args()`.

### `gsapi_init_with_args()`

> Initialise the interpreter. This calls `gs_main_init_with_args()` in `imainarg.c`. See below for return codes. The arguments are the same as the "C" main function: argv[0] is ignored and the user supplied arguments are argv[1] to argv[argc-1].

### `gsapi_run_*()`

> The `gsapi_run_*` functions are like `gs_main_run_*` except that the error_object is omitted. If these functions return <= -100, either quit or a fatal error has occured. You must call `gsapi_exit()` next. The only exception is `gsapi_run_string_continue()` which will return `gs_error_NeedInput` if all is well. See below for return codes.

> The address passed in `pexit_code` will be used to return the exit code for the interpreter in case of a quit or fatal error. The `user_errors` argument is normally set to zero to indicate that errors should be handled through the normal mechanisms within the interpreted code. If set to a negative value, the functions will return an error code directly to the caller, bypassing the interpreted language. The interpreted language's error handler is bypassed, regardless of `user_errors` parameter, for the `gs_error_interrupt` generated when the polling callback returns a negative value. A positive `user_errors` is treated the same as zero.

> There is a 64 KB length limit on any buffer submitted to a `gsapi_run_*` function for processing. If you have more than 65535 bytes of input then you must split it into smaller pieces and submit each in a separate `gsapi_run_string_continue()` call.

### `gsapi_exit()`

> Exit the interpreter. This must be called on shutdown if `gsapi_init_with_args()` has been called, and just before `gsapi_delete_instance()`.

### `gsapi_add_fs()`

> Adds a new 'Filing System' to the interpreter. This enables callers to implement their own filing systems. The system starts with just the conventional 'file' handlers installed, to allow access to the local filing system. Whenever files are to be opened from the interpreter, the file paths are offered around each registered filing system in turn (from most recently registered to oldest), until either an error is given, or the file is opened successfully.

> Details of the `gsapi_fs_t` are given below.

### `gsapi_remove_fs()`

> Remove a previously registered 'Filing System' from the interpreter. Both the function pointers within the `gs_fs_t` and the secret value must match exactly.

### Return codes

The `gsapi_init_with_args`, `gsapi_run_*` and `gsapi_exit` functions return an integer code.

Return Codes from gsapi_*()
CODE | STATUS
--- | ---
0 | No errors
gs_error_Quit | "`quit`" has been executed. This is not an error. `gsapi_exit()` must be called next.
gs_error_interrupt | The polling callback function returned a negative value, requesting Ghostscript to abort.
gs_error_NeedInput | More input is needed by `gsapi_run_string_continue()`. This is not an error.
gs_error_Info | "`gs -h`" has been executed. This is not an error. `gsapi_exit()` must be called next.
< 0 | Error
<= gs_error_Fatal | Fatal error. `gsapi_exit()` must be called next.

The `gsapi_run_*()` functions do not flush stdio. If you want to see output from Ghostscript you must do this explicitly as shown in the example below.

When executing a string with `gsapi_run_string_*()`, `currentfile` is the input from the string. Reading from `%stdin` uses the stdin callback.

### gsapi_fs_t

Each 'filing system' within gs is a structure of function pointers; each function pointer gives a handler from taking a different named resource (a file, a pipe, a printer, a scratch file etc) and attempts to open it.

    typedef struct
    {
        int (*open_file)(const gs_memory_t *mem,
                               void        *secret,
                         const char        *fname,
                         const char        *mode,
                               gp_file    **file);
        int (*open_pipe)(const gs_memory_t *mem,
                               void        *secret,
                         const char        *fname,
                               char        *rfname, /* 4096 bytes */
                         const char        *mode,
                               gp_file    **file);
        int (*open_scratch)(const gs_memory_t *mem,
                                  void        *secret,
                            const char        *prefix,
                                  char        *rfname, /* 4096 bytes */
                            const char        *mode,
                                  int          rm,
                                  gp_file    **file);
        int (*open_printer)(const gs_memory_t *mem,
                                  void        *secret,
                                  char        *fname, /* 4096 bytes */
                                  int          binary,
                                  gp_file    **file);
        int (*open_handle)(const gs_memory_t *mem,
                                 void        *secret,
                                 char        *fname, /* 4096 bytes */
                           const char        *mode,
                                 gp_file    **file);
    } gsapi_fs_t;

If the filename (always given in utf-8 format) is recognised as being one that the filing system handles (perhaps by the prefix used), then it should open the file, fill in the `gp_file` pointer and return 0.

If the filename is not-recognised as being one that the filing system handles, then returning 0 will cause the filename to be offered to other registered filing systems.

If an error is returned (perhaps gs_error_invalidfileaccess), then no other filing system will be allowed to try to open the file. This provides a mechanism whereby a caller to gsapi can completely control access to all files accessed via `gp_fopen` at runtime.

Note, that while most file access within ghostscript will be redirected via these functions, stdio will not; see the existing mechanisms within Ghostscript for intercepting/replacing this.

- The `open_file` function pointer will be called when something (most often a call to `gp_fopen`) attempts to open a file.
- The `open_pipe` function pointer will be called when something (most often a call to `gp_popen`) attempts to open a pipe. `rfname` points to a 4K buffer in which the actual name of the opened pipe should be returned.
- The `open_scratch` function pointer will be called when something (most often a call to `gp_open_scratch_file` or `gp_open_scratch_file_rm`) attempts to open a temporary file. `rfname` points to a 4K buffer in which the actual name of the opened pipe should be returned. If `rm` is true, then the file should be set to delete itself when all handles to it are closed.
- The `open_printer` function pointer will be called when something (most often a call to `gp_open_printer`) attempts to open a stream to a printer. If `binary` is true, then the stream should be opened as binary; most streams will be binary by default - this has historical meaning on OS/2.
- The `open_handle` function pointer will be called when something (most often a call via the postscript `%handle%` IO device) attempts to open a Windows handle. This entry point will never be called on non-Windows builds.

Any of these which are left as NULL will never be called; a filing system with all of the entries left as NULL is therefore pointless.

The most complex part of the implementation of these functions is the creation of a `gp_file` instance to return. There are some helper functions for this, best explained by example.

Let us consider a hypothetical filing system that encrypts data as it is written, and decrypts it as it is read back. As each file is read and written the encryption/decryption routines will need to use some state, carried between calls to the filing system. We therefore might define a new type 'derived' from `gp_file` as follows:

    typedef struct
    {
       gp_file base;
       /* State private to the implementation of this file for encryption/decryption */
       /* For example: */
       int foo;
       char *bar;
    } gp_file_crypt;

An implementation of `gs_fs_t` for our 'crypt' filing system might then look like this:

    gsapi_fs_t gs_fs_crypt =
    {
        crypt_open_file,
        NULL,            /* open_pipe */
        NULL,            /* open_scratch */
        NULL,            /* open_printer */
        NULL             /* open_handle */
    };

In the above definition, we define a single handler, to cope with the opening of our input/output files. If we wanted to encrypt/decrypt other files too (perhaps the temporary files we produce) we'd need to define additional handlers (such as `open_scratch`).

Our handler might look as follows:

    int crypt_open_file(const gs_memory_t  *mem,
                              void         *secret,
                        const char         *filename,
                        const char         *mode,
                              gp_file     **file)
    {
        gp_file_crypt crypt;

        /* Ignore any filename not starting with "crypt://" */
        if (strncmp(filename, "crypt://", 8) != 0)
            return 0;

        /* Allocate us an instance (and fill in the non-crypt-specific
         * internals) */
        crypt = (gp_file_crypt *)gp_file_alloc(mem, &crypt_ops, sizeof(*crypt), "gp_file_crypt");
        if (crypt == NULL)
            return gs_error_VMerror; /* Allocation failed */

        /* Setup the crypt-specific state */
        crypt->foo = 1;
        crypt->bar = gs_alloc_bytes(mem->non_gc_memory, 256, "bar");
        /* If allocations fail, we need to clean up before exiting */
        if (crypt->bar) {
            gp_file_dealloc(crypt);
    	return gs_error_VMerror;
        }

        /* Return the new instance */
        *file = &crypt.base;
        return 0;
    }

The crucial part of this function is the definition of `crypt_ops`, an instance of the `gp_file_ops_t` type; a table of function pointers that implement the actual operations required.

    typedef struct {
        int          (*close)(gp_file *);
        int          (*getc)(gp_file *);
        int          (*putc)(gp_file *, int);
        int          (*read)(gp_file *, size_t size, unsigned int count, void *buf);
        int          (*write)(gp_file *, size_t size, unsigned int count, const void *buf);
        int          (*seek)(gp_file *, gs_offset_t offset, int whence);
        gs_offset_t  (*tell)(gp_file *);
        int          (*eof)(gp_file *);
        gp_file     *(*dup)(gp_file *, const char *mode);
        int          (*seekable)(gp_file *);
        int          (*pread)(gp_file *, size_t count, gs_offset_t offset, void *buf);
        int          (*pwrite)(gp_file *, size_t count, gs_offset_t offset, const void *buf);
        int          (*is_char_buffered)(gp_file *file);
        void         (*fflush)(gp_file *file);
        int          (*ferror)(gp_file *file);
        FILE        *(*get_file)(gp_file *file);
        void         (*clearerr)(gp_file *file);
        gp_file     *(*reopen)(gp_file *f, const char *fname, const char *mode);
    } gp_file_ops_t;

These functions generally follow the same patterns as the posix functions that match them, and so in many cases we will describe these with references to such. Whenever these routines are called, they will be passed a `gp_file` pointer. This pointer will have originated from the `crypt_open_file` call, and so can safely be cast back to a `gp_file_crypt` pointer to allow private data to be accessed.

`close(gp_file *)`
  close the given file; free any storage in the crypt specific parts of `gp_file_crypt`, but not the gp_file_crypt structure itself.
`int getc(gp_file *)`
  Get a single character from the file, returning it as an int (or -1 for EOF). Behaves like `fgetc(FILE *)`.
`int putc(gp_file *, int)`
  Put a single character to the file, returning the character on success, or EOF (and setting the error indicator) on error. Behaves like `fgetc(FILE *)`.
`int read(gp_file *, size_t size, unsigned int count, void *buf)`
  Reads count entries of size bytes the file into buf, returning the number of entries read. Behaves like `fread(FILE *, size, count, buf)`.
`int write(gp_file *, size_t size, unsigned int count, const void *buf)`
  Writes count entries of size bytes from buf into the file, returning the number of entries written. Behaves like `fwrite(FILE *, size, count, buf)`.
`int seek(gp_file *, gs_offset_t offset, int whence)`
  Seeks within the file. Behaves like `fseek(FILE *, offset, whence)`.
`gs_offset_t tell(gp_file *)`
  Returns the current offset within the file. Behaves like `ftell(FILE *)`.
`int eof(gp_file *)`
  Returns 1 if we are at the end of the file, 0 otherwise. Behaves like `feof(FILE *)`.
`gp_file * dup(gp_file *, const char *mode)`
  Optional function, only used if clist files are to be stored in this filing system. Behaves like `fdup(FILE *)`. Leave NULL if not implemented.
`int seekable(gp_file *)`
  Returns 1 if the file is seekable, 0 otherwise. Certain output devices will only work with seekable files.
`int pread(gp_file *, size_t count, gs_offset_t offset, void *buf)`
  Optional function, only used if clist files are to be stored in this filing system. Behaves like an atomic `fseek(FILE *, offset, 0)` and `fread(FILE *, 1, count, buf)`. Akin to `pread`.
`int pwrite(gp_file *, size_t count, gs_offset_t offset, const void *buf)`
  Optional function, only used if clist files are to be stored in this filing system. Behaves like an atomic `fseek(FILE *, offset, 0)` and `fwrite(FILE *, 1, count, buf)`. Akin to `pwrite`.
`int is_char_buffered(gp_file *file)`
  Returns 1 if the file is character buffered, 0 otherwise. Used for handling reading from terminals. Very unlikely to be used, so returning 0 all the time should be safe. Leave NULL to indicate "always 0".
`void fflush(gp_file *file)`
  Ensures that any buffered data is written to the file. Behaves like `fflush(FILE *)`. Leave NULL to indicate that no flushing is ever required.
`int ferror(gp_file *file)`
  Returns non-zero if there has been an error, or 0 otherwise. Behaves like `ferror(FILE *)`.
`FILE * get_file(gp_file *file)`
  Optional: Gets the FILE * pointer that backs this file. Required for a few devices that insist on working with FILE *'s direct. Generally safe to leave this set to NULL, and those devices will fail gracefully.
`void clearerr(gp_file *file)`
  Clear the error and EOF values for a file. Behaves like `clearerror(FILE *)`.
`gp_file * reopen(gp_file *f, const char *fname, const char *mode)`
  Optional function, only used if the `gp_file` came from an `open_scratch` call; can be left as NULL if the `open_scratch` pointer is set to NULL. Reopen a stream with a different mode. Behaves like `freopen(fname, mode, FILE *)`.

## Example Usage

To try out the following examples in a development environment like Microsoft's developer tools or Metrowerks Codewarrior, create a new project, save the example source code as a `.c` file and add it, along with the Ghostscript dll or shared library. You will also need to make sure the Ghostscript headers are available, either by adding their location (the `src` directory in the Ghostscript source distribution) to the project's search path, or by copying ierrors.h and iapi.h into the same directory as the example source.

### Example 1

    /* Example of using GS DLL as a ps2pdf converter.  */

    #if defined(_WIN32) && !defined(_Windows)
    # define _Windows
    #endif
    #ifdef _Windows
    /* add this source to a project with gsdll32.dll, or compile it directly with:
     *   cl -D_Windows -Isrc -Febin\ps2pdf.exe ps2pdf.c bin\gsdll32.lib
     */
    # include <windows.h>
    # define GSDLLEXPORT __declspec(dllimport)
    #endif

    #include "ierrors.h"
    #include "iapi.h"

    void *minst = NULL;

    int main(int argc, char *argv[])
    {
        int code, code1;
        const char * gsargv[7];
        int gsargc;
        gsargv[0] = "";
        gsargv[1] = "-dNOPAUSE";
        gsargv[2] = "-dBATCH";
        gsargv[3] = "-dSAFER";
        gsargv[4] = "-sDEVICE=pdfwrite";
        gsargv[5] = "-sOutputFile=out.pdf";
        gsargv[6] = "input.ps";
        gsargc=7;

        code = gsapi_new_instance(&minst, NULL);
        if (code < 0)
        return 1;
        code = gsapi_set_arg_encoding(minst, GS_ARG_ENCODING_UTF8);
        if (code == 0)
            code = gsapi_init_with_args(minst, gsargc, gsargv);
        code1 = gsapi_exit(minst);
        if ((code == 0) || (code == gs_error_Quit))
        code = code1;

        gsapi_delete_instance(minst);

        if ((code == 0) || (code == gs_error_Quit))
        return 0;
        return 1;
    }

### Example 2

    /* Similar to command line gs */

    #if defined(_WIN32) && !defined(_Windows)
    # define _Windows
    #endif
    #ifdef _Windows
    /* Compile directly with:
     *   cl -D_Windows -Isrc -Febin\gstest.exe gstest.c bin\gsdll32.lib
     */
    # include <windows.h>
    # define GSDLLEXPORT __declspec(dllimport)
    #endif
    #include <stdio.h>
    #include "ierrors.h"
    #include "iapi.h"

    /* stdio functions */
    static int GSDLLCALL
    gsdll_stdin(void *instance, char *buf, int len)
    {
        int ch;
        int count = 0;
        while (count < len) {
        ch = fgetc(stdin);
        if (ch == EOF)
            return 0;
        *buf++ = ch;
        count++;
        if (ch == '\n')
            break;
        }
        return count;
    }

    static int GSDLLCALL
    gsdll_stdout(void *instance, const char *str, int len)
    {
        fwrite(str, 1, len, stdout);
        fflush(stdout);
        return len;
    }

    static int GSDLLCALL
    gsdll_stderr(void *instance, const char *str, int len)
    {
        fwrite(str, 1, len, stderr);
        fflush(stderr);
        return len;
    }

    void *minst = NULL;
    const char start_string[] = "systemdict /start get exec\n";

    int main(int argc, char *argv[])
    {
        int code, code1;
        int exit_code;

        code = gsapi_new_instance(&minst, NULL);
        if (code < 0)
        return 1;
        gsapi_set_stdio(minst, gsdll_stdin, gsdll_stdout, gsdll_stderr);
        code = gsapi_set_arg_encoding(minst, GS_ARG_ENCODING_UTF8);
        if (code == 0)
            code = gsapi_init_with_args(minst, argc, argv);
        if (code == 0)
        code = gsapi_run_string(minst, start_string, 0, &exit_code);
        code1 = gsapi_exit(minst);
        if ((code == 0) || (code == gs_error_Quit))
        code = code1;

        gsapi_delete_instance(minst);

        if ((code == 0) || (code == gs_error_Quit))
        return 0;
        return 1;
    }

### Example 3

Replace main() in either of the above with the following code, showing how you can feed Ghostscript piecemeal:

    const char *command = "1 2 add == flush\n";

    int main(int argc, char *argv[])
    {
        int code, code1;
        int exit_code;

        code = gsapi_new_instance(&minst, NULL);
        if (code < 0)
        return 1;
        code = gsapi_set_arg_encoding(minst, GS_ARG_ENCODING_UTF8);
        if (code == 0)
            code = gsapi_init_with_args(minst, argc, argv);

        if (code == 0) {
        gsapi_run_string_begin(minst, 0, &exit_code);
        gsapi_run_string_continue(minst, command, strlen(command), 0, &exit_code);
        gsapi_run_string_continue(minst, "qu", 2, 0, &exit_code);
        gsapi_run_string_continue(minst, "it", 2, 0, &exit_code);
        gsapi_run_string_end(minst, 0, &exit_code);
        }

        code1 = gsapi_exit(minst);
        if ((code == 0) || (code == gs_error_Quit))
        code = code1;

        gsapi_delete_instance(minst);

        if ((code == 0) || (code == gs_error_Quit))
        return 0;
        return 1;
    }

### Example 4

When feeding Ghostscript piecemeal buffers, one can use the normal operators to configure things and invoke library routines. For example, to parse a PDF file one could say:

        code = gsapi_run_string(minst, "(example.pdf) .runlibfile", 0, &exit_code);

and Ghostscript would open and process the file named "example.pdf" as if it had been passed as an argument to `gsapi_init_with_args()`.

## Multiple threads

The Ghostscript library should have been compiled with a thread safe run time library. Synchronisation of threads is entirely up to the caller. The exported `gsapi_*()` functions must be called from one thread only.

## Standard input and output

When using the Ghostscript interpreter library interface, you have a choice of two standard input/output methods.

- If you do nothing, the "C" stdio will be used.
- If you use `gsapi_set_stdio()`, all stdio will be redirected to the callback functions you provide. This would be used in a graphical user interface environment where stdio is not available, or where you wish to process Ghostscript input or output.

The callback functions are described in `iapi.h`.

## Display device

The `display` device is available for use with the Ghostscript interpreter library. This is described in the file `gdevdsp.h`. This device provides you with access to the raster output of Ghostscript. It is your responsibility to copy this raster to a display window or printer.

To use this device, you must provide a callback structure with addresses of a number of callback functions. The address of the callback structure is provided using `gsapi_set_display_callback()`. This must be called after `gsapi_new_instance()` and before `gsapi_init_with_args()`.

The callbacks are for device open, close, resize, sync, page, memory allocation and updating. Each callback function contains a handle can be set using

> -sDisplayHandle=1234

Where "1234" is a string. The API was changed to use a string rather than an integer/long value when support for 64 bit systems arrived. A display "handle" is often a pointer, and since these command line options have to survive being processed by Postscript machinery, and Postscript only permits 32 bit number values, a different representation was required. Hence changing the value to a string, so that 64 bit values can be supported. The string formats allowed are:

> `1234` - implicit base 10

> `10#1234` - explicit base 10

> `16#04d2` - explicit base 16

The "number string" is parsed by the display device to retrieve the number value, and is then assigned to the void pointer parameter "pHandle" in the display device structure. Thus, for a trivial example, passing `-sDisplayHandle=0` will result in the first parameter passed to your display device callbacks being: `(void *)0`.

The previous API, using a number value:

> -dDisplayHandle=1234

is still supported on 32 bit systems, but will cause a "typecheck" error on 64 bit systems, and is considered deprecated. It should not be used in new code.

The device raster format can be configured using

> -dDisplayFormat=NNNN

Options include

- native, gray, RGB, CMYK or separation color spaces.
- alpha byte (ignored).
- 1 to 16 bits/component.
- bigendian (RGB) or littleendian (BGR) order.
- top first or bottom first raster.
- 16 bits/pixel with 555 or 565 bitfields.

The format values are described in `gdevdsp.h`. The format is flexible enough to support common Windows, OS/2, Linux and Mac raster formats. To select the display device with a Windows 24-bit RGB raster:

        char **nargv;
        char arg1[64];
        char arg2[64];
        char arg3[64];
        code = gsapi_new_instance(&minst, NULL);
        gsapi_set_stdio(minst, gsdll_stdin, gsdll_stdout, gsdll_stderr);
        code = gsapi_set_display_callback(minst, &display_callback);
        sprintf(arg1, "-sDEVICE=display");
        sprintf(arg2, "-dDisplayHandle=%d", 0);
        sprintf(arg3, "-dDisplayFormat=%d",
            DISPLAY_COLORS_RGB | DISPLAY_ALPHA_NONE | DISPLAY_DEPTH_8 |
            DISPLAY_LITTLEENDIAN | DISPLAY_BOTTOMFIRST);
        nargv = (char **)malloc((argc + 4) * sizeof(char *));
        nargv[0] = argv[0];
        nargv[1] = arg1;
        nargv[2] = arg2;
        nargv[3] = arg3;
        memcpy(nargv + 4, argv + 1, argc * sizeof(char *));
        argc += 3;
        code = gsapi_init_with_args(minst, argc, nargv);

The display device provides you with the address and size of the raster using the `display_size()` callback. You are then responsible for displaying this raster. Some examples are in `dwmain.c` (Windows), `dpmain.c` (OS/2) and `dxmain.c` (X11/Linux), and `dmmain.c` (MacOS Classic or Carbon).

On some platforms, the calling convention for the display device callbacks in `gdevdsp.h` is not the same as the exported `gsapi_*()` functions in `iapi.h`.

Copyright © 2000-2019 Artifex Software, Inc. All rights reserved.

This software is provided AS-IS with no warranty, either express or implied.

This software is distributed under license and may not be copied, modified or distributed except as expressly authorized under the terms of that license. Refer to licensing information at http://www.artifex.com/ or contact Artifex Software, Inc., 1305 Grant Avenue - Suite 200, Novato, CA 94945, U.S.A., +1(415)492-9861, for further information.

Ghostscript version 9.23, 21 March 2018