26-Aug-2009

Passing COBOL strings to C

Here is a simple example of passing strings defined in a COBOL program and manipulating them with a C function. The big trick to know here is that fixed length string descriptors are the way to go to move your strings around.

COBOL allows you to pass variables to functions by value, by reference, and by descriptor. The last one is of interest here.

Here's a C function that copies the input string to a NULL terminated C format string, prints out the original string, then removes trailing whitespace from the C string and prints that out:


#include <stdio.h>
#include <stdlib.h>
#include <ssdef.h>
#include <string.h>
#include <descrip.h>
#include <assert.h>
#include <ctype.h>

extern int copy_and_print (const struct dsc$descriptor_s const *in_d) {

    char *p = NULL;
    int i;

    assert (in_d != NULL);
    assert (in_d->dsc$a_pointer != NULL);

    if (in_d->dsc$w_length >= 1) {
        p = malloc (in_d->dsc$w_length + 1);
        if (p == NULL) {
            fprintf (stderr, "Could not allocate mem!\n");
            return SS$_INSFMEM;
        }
        strncpy (p, in_d->dsc$a_pointer, in_d->dsc$w_length);
        printf ("Original string is \"%s\"\n", p);
        for (i = strlen (p) - 1; i > 0; i--) {
            if (!isspace (p[i])) {
                p[++i] = '\0';
                break;
            }
        }
        printf ("Modified string is \"%s\"\n", p);
        free (p);
    }
    return SS$_NORMAL;
}

And here's a COBOL program to call the C function:


identification division.
program-id. test-c-call.
environment division.
data division.
working-storage section.
01 test_string pic x(45).
01 ret_status pic s9(09) comp.

procedure division.
0-begin.
    move "Test string 1 2 3" to test_string.
    call "copy_and_print" using by descriptor test_string
                          giving ret_status.
    if ret_status is failure
        call "lib$signal" using by value ret_status.

0-end.
    stop run.

Posted at August 26, 2009 9:57 AM
Tag Set:

Comments are closed