IronPython DLR; passing parameters to compiled code?

僤鯓⒐⒋嵵緔 提交于 2019-12-02 03:23:21

You can either evaluate expression in Python and return its result (1) or assign value to some variable in scope and later pick it (2):

    var py = Python.CreateEngine();

    // 1
    var value = py.Execute("1+1");
    Console.WriteLine(value);

    // 2
    var scriptScope = py.CreateScope();
    py.Execute("a = 1 + 1", scriptScope);
    var value2 = scriptScope.GetVariable("a");
    Console.WriteLine(value2);

You definitely don't have to print it. I'd expect there to be a way of just evaluating an expression, but if not there are alternatives.

For example, in my dynamic graphing demo I create a function, using the python:

def f(x):
    return x * x

and then get f out of the script scope like this:

Func<double, double> function;
if (!scope.TryGetVariable<Func<double, double>>("f", out function))
{
    // Error handling here
}
double step = (maxInputX - minInputX) / 100;
for (int i = 0; i < 101; i++)
{
    values[i] = function(minInputX + step * i);
}

You could do something similar if you want to evaluate the expression multiple times, or just assign the result to a variable if you only need to evaluate it once.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!