[英]How to eval a Tcl expression that should take a Tcl_Obj in C++
In a C++ code I have a (swig generated) Tcl_Obj*
and a string representing a simple Tcl expression like: return [[obj get_a] + [obj get_b]]
. 在C ++代码中,我有一个(生成的Tcl_Obj*
) Tcl_Obj*
和一个表示简单Tcl表达式的字符串,例如: return [[obj get_a] + [obj get_b]]
。 This looks silly, but I'm a novice in Tcl and I cannot understand how to put the two things together invoking the Tcl interpreter to have my expression evaluated with my Tcl_Obj*
: 这看起来很愚蠢,但是我是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...
}
Am I missing the right command that does this? 我是否错过了执行此操作的正确命令? Many thanks! 非常感谢!
You've got a Tcl_Obj *
from somewhere and you want to evaluate it as an expression and get a double
result? 您在某个地方有一个Tcl_Obj *
,您想将其作为一个表达式求值并得到double
结果? Use Tcl_ExprDoubleObj
. 使用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's a thoroughly C library, so there's no RAII wrappers, but it would make a good deal of sense to use one (possibly in combination with smart pointers) to manage the Tcl_Obj *
references for you. Tcl是一个完全C的库,因此没有RAII包装器,但是使用一个(可能与智能指针结合)为您管理Tcl_Obj *
引用是很有意义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.