contents.gifindex.gifprev1.gifnext1.gif

C.2 Direct Method

When you use the direct method of calling C routines, you pass parameters directly to the C function according to the CALL statement that invokes the function. Use the BY VALUE phrase of the CALL statement to pass numeric parameters in a way that is compatible with C calling conventions. Use the BY REFERENCE phrase to pass address parameters.

When a C function is called by the direct method, its return value is placed in the special register RETURN-CODE.

It's important to note that the direct method makes it easy to generate memory access violations. This is because it is easy to omit a BY REFERENCE or BY VALUE phrase or to forget to terminate strings properly with a null value (as required by C).

To use the direct method, add the name of the C function to be called to DIRECTTABLE in the file "direct.c". There are three columns in the table:

gt490000.gif In the first column, place the name you want to use in the COBOL CALL statement. Use all upper-case, and place the name in quotes.

gt490000.gif In the second column, place the address of the routine to be called. (You can accomplish this by specifying "FUNC" followed by the exact name of the routine as declared in C. "FUNC" is a macro that generates the appropriate cast of the routine name.)

gt490000.gif In the third column, place the return type of the function. This may be one of these seven types:

C_int

C_unsigned

C_short

C_char

C_long

C_pointer

C_void

For example, to call the C function "open" directly, you would include the following code in the file direct.c:

extern int open();
struct  DIRECTTABLE LIBDIRECT[] = {
       { "OPEN",  FUNC open,  C_int },
       {NULL,    NULL,       0 }
       };

After you make the change to "direct.c", be sure to re-link the runtime system.

To use the "open" function in COBOL, you might do something like this:

77   FILE-NAME PIC  X(20)
77   FILE-HANDLE    SIGNED-INT

MOVE "myfile" to FILE-NAME.
INSPECT FILE-NAME REPLACING TRAILING SPACES
   BY LOW-VALUES.
CALL "OPEN" USING BY REFERENCE FILE-NAME, VALUE 0.
MOVE RETURN-CODE TO FILE-HANDLE.

Note that strings passed to C routines should have LOW-VALUE terminators. Variables that are not passed by address should have the BY VALUE qualifier in COBOL and should be COMP-5 or one of the C data types.

In the example above, FILE-NAME cannot be more than 19 characters, because the 20th, or last, character must be the string terminator.

Up to 12 parameters may be passed via the direct method. If you need to pass more than 12, call Acucorp Technical Support and request the routine "callc.c". The comments within the code explain how to use the "callc.c" routine.

External C variables can also be linked with COBOL EXTERNAL data items.