如何在c++中计算应该接受Tcl_Obj的Tcl表达式

How to eval a Tcl expression that should take a Tcl_Obj in C++

本文关键字:Tcl Obj 表达式 该接受 c++ 计算      更新时间:2023-10-16

在c++代码中,我有一个(swig生成的)Tcl_Obj*和一个表示简单Tcl表达式的字符串,如:return [[obj get_a] + [obj get_b]]。这看起来很傻,但我是Tcl的新手,我不明白如何把这两件事放在一起,调用Tcl解释器来用我的Tcl_Obj*计算我的表达式:

double eval(Tcl_Interp *interp, Tcl_Obj *obj, const char * cmd) 
{
  //substiture obj in cmd and call the interpreter?
  return Tcl_GetResult(interp); //with proper checks and so on...
}

我是否缺少执行此操作的正确命令?很多谢谢!

你有一个Tcl_Obj *从某个地方,你想评估它作为一个表达式,并得到一个double的结果?使用Tcl_ExprDoubleObj .

Tcl_Obj *theExpressionObj = ...; // OK, maybe an argument...
double resultValue;
int resultCode;
// Need to increase the reference count of a Tcl_Obj when you evaluate it
// whether as a Tcl script or a Tcl expression
Tcl_IncrRefCount(theExpressionObj);
resultCode = Tcl_ExprLongObj(interp, theExpressionObj, &resultValue);
// Drop the reference; _may_ deallocate or might not, but you shouldn't
// have to care (but don't use theExpressionObj after this, OK?)
Tcl_DecrRefCount(theExpressionObj);
// Need to check for an error here
if (resultCode != TCL_OK) {
    // Oh no!
    cerr << "Oh no! " << Tcl_GetResult(interp) << endl;
    // You need to handle what happens when stuff goes wrong;
    // resultValue will *not* have been written do at this point
} else {
    // resultValue has what you want now
    return resultValue;
}

Tcl是一个完全的C库,所以没有RAII包装器,但是使用一个(可能与智能指针结合)来管理Tcl_Obj *引用是很有意义的。