Cling API available?

732 Views Asked by At

How to use Cling in my app via API to interpret C++ code?

I expect it to provide terminal-like way of interaction without need to compile/run executable. Let's say i have hello world program:

void main() {
    cout << "Hello world!" << endl;
}

I expect to have API to execute char* = (program code) and get char *output = "Hello world!". Thanks.

PS. Something similar to ch interpeter example:

/* File: embedch.c */
#include <stdio.h>
#include <embedch.h>
char *code = "\
   int func(double x, int *a) { \
      printf(\"x = %f\\n\", x); \
      printf(\"a[1] in func=%d\\n\", a[1]);\
      a[1] = 20; \
      return 30; \
   }";
int main () {
   ChInterp_t interp;
   double x = 10;
   int a[] = {1, 2, 3, 4, 5}, retval;
   Ch_Initialize(&interp, NULL);
   Ch_AppendRunScript(interp,code);
   Ch_CallFuncByName(interp, "func", &retval, x, a);
   printf("a[1] in main=%d\n", a[1]);
   printf("retval = %d\n", retval);
   Ch_End(interp);
}
}
2

There are 2 best solutions below

0
On

Usually the way one does it is: [cling$] #include "cling/Interpreter/Interpreter.h" [cling$] const char* someCode = "int i = 123;" [cling$] gCling->declare(someCode); [cling$] i // You will have i declared: (int) 123

The API is documented in: http://cling.web.cern.ch/cling/doxygen/classcling_1_1Interpreter.html

Of course you can create your own 'nested' interpreter in cling's runtime too. (See the doxygen link above)

I hope it helps and answers the question, more usage examples you can find under the test/ folder. Vassil

1
On

There is finally a better answer: example code! See https://github.com/root-project/cling/blob/master/tools/demo/cling-demo.cpp

And the answer to your question is: no. cling takes code and returns C++ values or objects, across compiled and interpreted code. It's not a "string in / string out" kinda thing. There's perl for that ;-) This is what code in, value out looks like:

// We could use a header, too...
interp.declare("int aGlobal;\n");

cling::Value res; // Will hold the result of the expression evaluation.
interp.process("aGlobal;", &res);
std::cout << "aGlobal is " << res.getAs<long long>() << '\n';

Apologies for the late reply!