Problem:
If a C function returns a pointer on a String ( char *) or an array of pointers (char **) how do I proceed to get the values of pointers and array of pointers in a COBOL program?
Resolution:
The demonstration is attached and contains:
A COBOL program named callretPtr.cbl
A C program named retPtr.c
A script docl.bat file to be run on Windows environment (with Net Express and the C compiler on-line)
To compile and link and run the code
A script docl.sh to be run on UNIX
To compile and link and run the code
Pasted is the STDOUT of the demo run:
CallretPtr
*--> C: retPtr: Bonjour
*--> COBOL: Bonjour
*--> C: retPtrTB: Bonjour Hello Bonjourno
*--> COBOL: 1: Bonjour
*--> COBOL: 2: Hello
*--> COBOL: 3: Bonjourno
The code is quite short:
callretPtr.cbl:
working-storage section.
01 Str pic x(10) value z"Bonjour".
01 StrLength pic s9(9) comp-5.
01 ptrStr pointer value null.
01 i pic 9.
78 hCobol value "*--> COBOL: ".
linkage section.
01 lkStr pic x any length.
01 lkPtrTB.
02 lkPtr pointer occurs 3.
procedure division.
call "retPtr" using Str
returning ptrStr
if ptrStr not = null
set address of lkStr to ptrStr
call "strlen" using lkStr
returning StrLength
display hCobol lkStr(1:StrLength)
end-if
call "retPtrTB" using Str
returning ptrStr
if ptrStr not = null
set address of lkPtrTB to ptrStr
perform varying i from 1 by 1 until i > 3
move lkPtr(i) to ptrStr
set address of lkStr to ptrStr
if address of lkStr not = null
call "strlen" using lkStr
returning StrLength
display hCobol i ": " lkStr(1:StrLength)
end-if
end-perform
end-if
STOP RUN.
retPtr.c
#include <stdio.h>
char * strTB[3] = {0,0,0}; /* Global variable*/
char * hC = "*--> C: ";
char * retPtr(char * str)
{
printf("%s retPtr: %s\\n",hC,str);
return str;
}
char ** retPtrTB(char * str)
{
strTB[0] = str;
strTB[1] = "Hello";
strTB[2] = "Bonjourno";
printf ("%s retPtrTB: %s %s %s \\n",hC, strTB[0],strTB[1],strTB[2] );
return strTB;
}
mainC()
{
char ** ptr;
printf("%s main %s\\n",hC,retPtr("Bonjour"));
ptr = retPtrTB("Bonjour");
printf("%s main: %s %s %s \\n",hC, *ptr,*(ptr 1),*(ptr 2));
exit(0);
}