Last active
August 29, 2015 14:09
-
-
Save jemc/683b00fb56d182f0fda5 to your computer and use it in GitHub Desktop.
Shell bindings for C functions - an example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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