如何评估应该在C ++中使用Tcl_Obj的Tcl表达式

时间:2014-08-04 12:44:44

标签: c++ tcl

在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...
}

我错过了正确的命令吗?非常感谢!

1 个答案:

答案 0 :(得分:1)

您从某个地方获得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 *会很有意义。给你的参考资料。