Reputation: 5465
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]]
. 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*
:
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!
Upvotes: 0
Views: 478
Reputation: 137627
You've got a Tcl_Obj *
from somewhere and you want to evaluate it as an expression and get a double
result? Use 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.
Upvotes: 1