简体   繁体   中英

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]] . 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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM