Use another language to call a function: Difference between revisions

Content added Content deleted
(Added COBOL (GnuCOBOL in particular))
(add Mercury)
Line 979: Line 979:
clean:
clean:
rm -f $(TARGET) *.o query.c</lang>
rm -f $(TARGET) *.o query.c</lang>

=={{header|Mercury}}==

The code as written is horrible for Mercury, so some additional C is added as a shim that actually calls the Mercury predicate. Although no changes are required to the C code in this simple example, in a larger project, with modules that need initialization, there are [https://mercurylang.org/information/doc-latest/mercury_user_guide/Using-mmc.html some additional compilation steps] needed to get that initialization code in.

<lang Mercury>:- module query.
:- interface.

:- pred query(string::in, string::out) is det.

:- implementation.

query(_, "Hello, world!").

:- pragma foreign_export("C", query(in, out), "query").

:- pragma foreign_decl("C",
"
#include <string.h>
int Query (char * Data, size_t * Length);
").
:- pragma foreign_code("C",
"
int Query (char *Data, size_t *Length) {
MR_String input, result;
MR_allocate_aligned_string_msg(input, *Length, MR_ALLOC_ID);
memmove(input, Data, *Length);
query(input, &result);
*Length = strlen(result);
memmove(Data, result, *Length);
return 1;
}
").</lang>

Building with the unchanged C in useanother.c:

<pre>$ mmc -c query
$ gcc -Wall -c useanother.c
$ ml -o useanother useanother.o query.o</pre>

{{out}}
<pre>Hello, world!</pre>


=={{header|Nim}}==
=={{header|Nim}}==