Use another language to call a function: Difference between revisions

Added COBOL (GnuCOBOL in particular)
(Scala solution added)
(Added COBOL (GnuCOBOL in particular))
Line 176:
$ ./main
Here am I</lang>
 
=={{header|COBOL}}==
{{works with|GnuCOBOL|2.0+}}
 
GnuCOBOL uses C intermediates and blends well with C programming. GnuCOBOL is also a fixed length data item language, so this Query routine has to set some limits on passed in external value lengths. 8K in this example, defined using OCCURS DEPENDING ON the input Length.
 
Instead of C being the master builder, cobc is used to combine the .c source and .cob source into the executable simplifying the tectonic for this example (cobc can generate and use .o object code, but that is all hidden here). GnuCOBOL also requires a COBOL runtime system, implicitly initialized with the -fimplicit-init compiler switch here. This emits code to ensure libcob is properly setup for calling from foreign languages (that would otherwise have to call cob_init() before invoking COBOL modules). The source code in the task description was saved to disk as <code>call-query.c</code>, and the listing below was saved as <code>query.cob</code> (with the internal subprogram named <code>Query</code>). A special <code>call-convention</code> is also used so the GnuCOBOL module does not make any assumptions about how the Query module is invoked (normal COBOL programs set some control fields in the libcob runtime space when calling modules, which won't be set when called from a foreign C ABI program). GnuCOBOL also sets <code>RETURN-CODE</code> to zero unless told otherwise (or some error occurs).
 
<lang cobol> identification division.
program-id. Query.
 
environment division.
configuration section.
special-names.
call-convention 0 is extern.
 
repository.
function all intrinsic.
 
data division.
working-storage section.
01 query-result.
05 filler value "Here I am".
 
linkage section.
01 data-reference.
05 data-buffer pic x occurs 0 to 8192 times
depending on length-reference.
01 length-reference usage binary-long.
 
procedure division extern using data-reference length-reference.
 
if length(query-result) less than or equal to length-reference
and length-reference less than 8193 then
move query-result to data-reference
move length(query-result) to length-reference
move 1 to return-code
end-if
 
goback.
end program Query.</lang>
 
{{out}}
<pre>
prompt$ cobc -x -fimplicit-init call-query.c query.cob
prompt$ ./call-query
Here I am</pre>
 
=={{header|D}}==
Anonymous user