4

如何通过 API 在我的应用程序中使用Cling来解释 C++ 代码?

我希望它能够提供类似终端的交互方式,而无需编译/运行可执行文件。假设我有 hello world 程序:

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

我希望有 API 来执行char* = (program code)和获取char *output = "Hello world!". 谢谢。

PS。类似于 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);
}
}
4

2 回答 2

4

终于有了更好的答案:示例代码!见https://github.com/root-project/cling/blob/master/tools/demo/cling-demo.cpp

你的问题的答案是:不。cling 通过编译和解释代码获取代码并返回 C++ 值或对象。这不是“字符串输入/字符串输出”之类的东西。有 perl ;-) 这就是代码输入,值输出的样子:

// 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';

为迟到的回复道歉!

于 2017-08-14T17:18:24.767 回答
1

通常这样做的方式是: [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

API 记录在:http ://cling.web.cern.ch/cling/doxygen/classcling_1_1Interpreter.html

当然,您也可以在 cling 的运行时创建自己的“嵌套”解释器。(请参阅上面的 doxygen 链接)

我希望它可以帮助并回答问题,您可以在 test/ 文件夹下找到更多使用示例。瓦西尔

于 2014-08-03T13:57:47.470 回答