I have a Tcl code that is being sourced from a C application using:
Tcl_Eval(tcl_interp, "source nmsp.tcl")
Everything runs fine.
However, the namespace scope isn’t preserved. For example, the following file:
#!/bin/sh
# namespace evaluation
namespace eval bob {
namespace eval joe {
proc proc1 {} {}
}
proc proc2 {} {
puts "proc2"
}
proc ::proc3 {} {
puts "proc3"
}
proc joe::proc4 {} {
puts "proc4"
}
}
puts "Namespace calling [info procs ::bob\::*]"
when run by itself will produce this output:
Namespace calling ::bob::proc2
But when sourcing from Tcl_Eval will not print anything. In fact, the proc2 procedure can be called by itself fine without any namespace designation.
Anyone knows what may be causing it? I really like the encapsulation that namespaces provide.
Seems fine to me.
I created the following Tcl extension to perform your Tcl_Eval:
Being on windows, I compiled this using:
and then created a test_namespace.tcl file with the content you posted above. Running this produces the following:
and further introspection shows things are as I would expect from that script:
You probably are doing something weird in your C code first if this is really not working for you.
Update
The above example is for extending tcl with a compiled package. Apparently the OP is embedding Tcl into some other application. A trivial example of doing this is provided here which also runs the same command to the same effect as above. In reality when embedding Tcl into an application the code should use the tclAppInit.c file and provide its own Tcl_AppInit function. By running the usual Tcl_Main you get the full capabilities for processing events (needed for fileevents or after commands) and the interactive shell. An example of that follows the trivial version:
Running the above:
A better embedding scheme that uses tclAppInit to extend a stock Tcl interpreter:
Building and running this also produces the same output as previous versions: