Updated 2015-03-23 01:57:54 by APN

NRE enabled C commands edit

Rationale

HaO 2014-01-29: (to be removed) I started this page due to lack of information how to handle NRE for commands implemented in C. I would be glad, if this page could be populated by people having more knowledge about the issue. The following information comes from this clt communication from Miguel Sofer and Donal Fellows:

Intro

I have some commands in a dll which are typically created in the Dllname_Init using:
Tcl_CreateObjCommand(Interp, "cmd", cmdProc, NULL, NULL);

I want to use them with tcl8.6 and I am thinking if it is wise/necessary to modify them to be NRE enabled.

Thus, the upper has to be replaced by:
Tcl_NRCreateCommand(Interp, "cmd", cmdProc, cmdNREProc, NULL, NULL);

Then there is an example on: [1] but I am really lost there.

Thus my questions:

Q1) Is NRE-enableing for C commands a good idea?

If yes, under which circumstances ?

Answer by Miguel Sofer

It is only a good idea if:

  1. the command is likely to cause a script (or proc, or lambda, or oo method) evaluation (except via traces, those are "innocuous")
  2. you want to allow the evaluated scripts to yield

If either of those two conditions are not met, you are much better off NOT NRE-enabling your commands - you'd just be paying the cost with zero benefits.

Note that 8.6 properly runs all 8.5 C-extensions (assuming they do not use internal headers, in which case it's a "maybe").

Q2) Compatibility

I suppose a NRE enabled dll is not usable with tcl 8.5.x. Is there a way to make a dll working on tcl 8.5 and 8.6 nre enabled

Answer by Miguel Sofer

Yes. Compile using stubs against 8.6's tcl.h, and switch at runtime between 8.5 or 8.6 code depending on (for instance) the existence of the command yield.

Q3) Is there a programming example

I am sorry, the wiki example did not help me understanding what to do. Is there any way.

Answer by Miguel Sofer

Plenty of those in the 8.6 sources. I suggest starting with something simple, for instance catch. Compare the 8.5 and 8.6 implementations in tclCmdAH.c

Q4) Is it worthwile to NRE enable Event handler

Answer moved on [2].

2015-03-23: APN Although not documented as such, Tcl_NREvalObjv require the objv parameter to be dynamically allocated, *not* on the stack. The following comes from Miguel on the chat:

Indeed, dyn alloc is required. One good strategy is to use a tcl list (unshared, so that it can't shimmer!) to store the objv, push a callback to decrRefCount it, then call Tcl_NREvalObjv with the list elements as objv. Need better docs for that ... or even a new api to automate that. In the core most of those live in the Tcl stack ... which would also be the case if your twapi command is called from normal Tcl code... but if YOU are in charge, you have to take care of the important detail: not only must objv be accessible until the command finishes runnind, the contents must have a live refCount for the duration too