简体   繁体   中英

Tcl C++ API - how to type safe convert a void pointer

I am using Tcl_CreateObjCommand(interp, cmdName, proc, clientData, deleteProc) in my code and passing in a DerivedClass pointer to the clientData parameter. In the callback function, I want to type safe convert (dynamic_cast) the clientData back to the DerivedClass pointer, but the gcc compiler is complaining " source is not a class to pointer ". This is because the clientData is a type of void pointer. In this use case, how would developers usually handle this issue when using Tcl API?

int main()
{
  ...
  Tcl_CreateObjCommand(interp, cmdName, myCallback, myDerivedClassPointer, (Tcl_CmdDeleteProc *)NULL);
}

myCallback(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj* const objv[])
{
  // I want to do something like this, so when the pointer is not a DerivedClassPointer type, throw an exception.
  DerivedClass* foo = dynamic_cast<DerivedClass*>(clientData);  
  if(!foo) throw exception, type conversion fail
}

As @PeterWood said: this is impossible. Furthermore, it is a bug that any invalid pointers got passed to Tcl_CreateObjCommand in the first place.

The correct way (again as @PeterWood states) is to ensure that the ClientData you receive is always valid. The best way to do this is with a template function that checks (at compile-time) that the types are correct.

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