[m-users.] Foreign language interface
Volker Wysk
post at volker-wysk.de
Wed Sep 14 03:28:56 AEST 2022
Hi!
This is the first time I've done something non-trivial with the FLI. It
looks good, but I'm not sure if I've done it right. My foreign predicate
reads the process' environment and returns it as a list of strings:
:- pragma foreign_decl("C", "#include <unistd.h>").
:- pragma foreign_decl("C", "#include <string.h>").
:- pragma foreign_proc("C",
get_environment_0(List::out, In::di, Out::uo),
[ will_not_call_mercury,
promise_pure
],
"
List = MR_list_empty();
for (char ** str = __environ;
*str;
str++) {
void * copy = MR_GC_malloc(strlen(*str) + 1);
strcpy(copy, *str);
List = MR_list_cons(copy, List);
}
Out = In;
").
:- pred get_environment_0(list(string)::out, io::di, io::uo) is det.
I assume:
- The foreign predicate is pure, because it is an IO action.
- The strings in the returned list will be garbage collected.
- It is necessary to copy them over to Mercury land, like I did. If
pointers into the process' environment were handed over to Mercury, they
would possibly get garbage collected, what can't work.
Happy hacking,
Volker
More information about the users
mailing list