From: glen herrmannsfeldt on
Uno <merrilljensen(a)> wrote:
> I would like to call a c function using the iso_c_binding. I thought I
> had a template for this in a place that I could readily access, but
> apparently, I don't.

> I have Mr&C and the Fortran 2003 Handbook as references.

> The idea is that I'm asking my OS a simple question like uname. To be
> returned from the C part is a char * and an integer that exceeds the
> necessary size of a buffer to hold it.

> The C part wouldn't look a whole lot different from this:

> #include <stdlib.h>
> #include <stdio.h>
> #include <string.h>

> int main(void)
> {
> FILE *stream;
> char *sys;
> sys = malloc(100);
> stream = popen("/bin/uname -snm", "r");
> fscanf( stream, "%31[^\n]", sys );
> printf("sys is %s\n", sys);
> pclose(stream);
> return 0;
> }

> // gcc -D_GNU_SOURCE -std=c99 -Wall -Wextra r1.c -o out

> , except that main is no longer there.

> So, with this as an example, I'm looking for an interface that can
> return the char * sys, as well as the 100, if that were big enough to
> accomodate uname, which it seems to be by orders of magnitude.

I presume this is an example, as calling the uname function
(which most likely is what the uname command does) is easier.

I would use fgets(), which allows for a length, and will store
up to N-1 characters of source, followed by a '\0' into the
supplied array. If a whole line fits, the terminating '\n' is
stored, which you can remove.

> How do I do this?

stream = popen("/bin/uname -snm", "r");
fgets(sys,len,stream); /* len is the allocated length */
if(n>=0 && sys[n]=='\n') sys[n]=0;
else (do something here)

printf("n is %d, and sys is %s\n", n, sys);

That gives you the length, as read, and also a check that it
has a reasonable length.

-- glen