开发者

How to let a user to create a function? [ library ? ]

Is there any free library to let a user easily build a C mathematical expressio开发者_Go百科n, which can be used like any other function? I mean c expression/function which could be as quick as 'inline' mathematical expression and could be used many times in program. I think I can be done in C somehow, but does anybody can tell if it could be real if it have to be a CUDA dveice function?


There are a few options. I assume you want something that the user can "call" several times, like this:

void *s = make_func("2 * x + 7");
...
printf("%lf\n", call_func(s, 3.0)); // prints 13
...
printf("%lf\n", call_func(s, 5.0)); // prints 17
...
free_func(s);

One option is to implement this as a recursive structure holding function pointers and constants. Something like:

enum item_type { VAR, CONST, FUNC };

struct var {
  enum item_type;
  int id;
};

struct constant {
  enum item_type;
  double value;
};

struct func {
  enum item_type;
  double (*func)(double, double);
  enum item_type *a, *b;
};

Then make_func would parse the above string into something like:

(struct func *){ FUNC, &plus,
  (struct func *){ FUNC, &times,
    (struct constant *){ CONST, 2 },
    (struct var *){ VAR, 'x' } }
  (struct constant *){ CONST, 7 } }

If you can understand that - the enum type_item in the struct func is used to point to the next node in the tree (or rather, the first element of that node, which is the enum), and the enum is what our code uses to find out what the item type is. Then, when we use the call(void *, ...) function, it counts how many variables there are - this is how many extra arguments the call function should have been passed - then replaces the variables with the values we've called it with, then does the calculations.

The other option (which will probably be considerably faster and easier to extend) is to use something like libjit to do most of that work for you. I've never used it, but a JIT compiler gives you some basic building blocks (like add, multiply, etc. "instructions") that you can string together as you need them, and it compiles them down to actual assembly code (so no going through a constructed syntax tree calling function pointers like we had to before) so that when you call it it's as fast and dynamic as possible.

I don't know libjit's API, but it looks easily capable of doing what you seem to need. The make_func and free_func could all be pretty much the same as they are above (you might have to alter your calls to call_func) and would basically construct, use, and destroy a JIT object based on how it parses the user's string. The same as above, really, but you wouldn't need to define the syntax tree, data types, etc. yourself.

Hope that is somewhat helpful.


libtcc (from TCC) can be used as a very small and fast JIT; see libtcc_test.cc for sample usage.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜