I did some testing of @digEmAll code. First I have to say that it works correctly and does what I asked in the question. But I was worried that you should call
string expr = "functionOfMyModule()"; var result = engine.Execute(expr, scope);
every time you want to evaluate a custom expression. My concern was that the code was not precompiled and had to be re-processed at each run, which could seriously affect the performance of my application (such expressions could be called hundreds of thousands, if not millions of times, so every millisecond is counted).
I tried another solution: just pasting a custom expression at the end of the Python module (I'm not saying this works in all situations!):
def simpleFunc(x): return x + 2;
Then I had to compile this code:
ScriptSource source = engine.CreateScriptSourceFromString(myCode); CompiledCode compiledCode = source.Compile();
... create a scope and run it:
ScriptScope scope = engine.CreateScope(); scope.SetVariable ("x", 10); int result = compiledCode.Execute<int>(scope);
Now I have executed both solutions (digEmAll and my own) on the same code fragment and the same expression 10,000 times, and here are the results:
- engine.Execute (expr, scope): 0.29 ms / run
- compiledCode.Execute (scope): 0.01 ms / run
So, I think that I will try to use my own solution if the code insert is not inserted.
source share