I'm working on part of a C program where a user inputs a network filter string (think Wireshark). A filter string like, for example
(s->field_a == 1 || s->field_c <= 10) && ! (s->field_c % 2)
Is entered by the user and pasted into a function in a temporary file, which is compiled as a shared lib and loaded wit dlopen. The function simply evaluates the string.
Now, the type of "s" struct is defined in some .h file, let's say struct.h.
Obviously struct.h won't be available for the runtime compilation. I can just paste its content to a string and fprintf
it, but then I'd have to re-paste it whenever I change the header.
I could write a script that'd do it during building, but maybe there's a better option.
Is there a way to "paste" the content of the file as a string using e.g. the preprocessor?
Some code to illustrate what I'm trying to do:
struct.h:
struct example_struct
{
int field_a;
int field_b;
int field_c;
};
main.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#include "struct.h"
int main(int argc, char *argv[]) {
struct example_struct s;
char filter_string[] = "(s->field_a == 1 || s->field_c <= 10) && ! (s->field_c % 2)"; // what the user can input
FILE *f = fopen("/tmp/prog.c","w");
// here I'd like to insert contents of struct.h into f
fprintf(f, "int filter(struct example_struct * s) {\n");
fprintf(f, "return (%s);}\n", filter_string);
fclose(f);
system("gcc /tmp/prog.c -o /tmp/prog.so -shared -fPIC");
// load and use function...
}
Edit: I don't need an actual representation as a char[], it can be a string literal.
I'm trying not to use xxd
or some other tool before building the program, I can do that fine by inserting the text with a python script or whatever. I'm just curious if a "pure" solution is possible.