glenn jackman
glenn jackman

Reputation: 246817

Can TclOO objects be shared/aliases between interpreters?

I'm implementing DSL processing. I'm using a safe interpreter to source the input file.

As part of the processing, I'm building an object.

something like:

set interp [interp create -safe]
interp expose $interp source
interp eval $interp {
    oo::class create Graph { # ...
    }

    # add domain-specific commands here
    proc graph {definition} {
        global graph
        $graph add $definition
    }
    # and so on

    set graph [Graph new]
}
interp eval $interp source $graphFile

Is there a mechanism to alias the $graph object into the main interpreter?

Upvotes: 2

Views: 150

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137577

Aliases are commands, not objects. However, for calling (as opposed to modifying definitions or making subclasses, etc.) you can set an alias that points to the object in the other interpreter:

oo::class create Example {
    variable count
    method bar {} { return "this is [self] in the method bar, call [incr count]" }
}
Example create foo

interp create xyz
interp alias xyz foo {} foo

xyz eval {
    puts [foo bar]
}
# this is ::foo in the method bar, call 1

Individual methods can also go across interpreters (with some limitations) if you forward the method call to an alias that crosses the interpreter boundary. This allows for all sorts of shenanigans.

oo::class create Example {
    variable count
    method bar {caller} { return "this is $caller in the method bar, call [incr count]" }
}
Example create foo

interp create xyz
interp alias xyz _magic_cmd_ {} foo bar
interp eval xyz {
    oo::class create Example {
        forward bar _magic_cmd_ pqr
    }
    Example create grill
    grill bar
}
# this is pqr in the method bar, call 1

Upvotes: 3

glenn jackman
glenn jackman

Reputation: 246817

What I ended up with:

oo::class create Graph { # ...
}
set graph [Graph new]

set interp [interp create -safe]

interp expose $interp source
interp alias $interp graphObj {} $graph

interp eval $interp {
    # add domain-specific commands here
    proc graph {definition} {
        graphObj add $definition
    }
    # and so on
}

interp eval $interp source $graphFile

puts [$graph someMethod]

Upvotes: 1

Related Questions