Skip to content

Instantly share code, notes, and snippets.

@jemc
Last active August 29, 2015 14:09
Show Gist options
  • Save jemc/683b00fb56d182f0fda5 to your computer and use it in GitHub Desktop.
Save jemc/683b00fb56d182f0fda5 to your computer and use it in GitHub Desktop.
Shell bindings for C functions - an example
#include <my_library.h>
int
main (int argc, char *argv[])
{
// Capture stdout file descriptor and position
int orig_stdout_fd;
fpos_t orig_stdout_pos;
fflush (stdout);
dup2 (fileno (stdout), orig_stdout_fd);
fgetpos (stdout, &orig_stdout_pos);
// Redirect what would normally go to stdout to go to stderr
dup2 (fileno (stderr), fileno (stdout));
// Run the function and get the result
int result = my_library_function (1, 2, 3);
// Restore stdout file descriptor and position
fflush (stdout);
dup2 (orig_stdout_fd, fileno (stdout));
fsetpos (stdout, &orig_stdout_pos);
close (orig_stdout_fd);
// Serialize result and send to stdout
fprintf (stdout, "%i", result);
fflush (stdout);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment