我正在制作一个在c#中使用Python脚本(IronPython)的软件。 代码是:
using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
...
...
private void RunScript()
{
ScriptEngine engine;
ScriptRuntime runtime;
ScriptSource source = null;
ScriptScope scope;
MemoryStream ms = new MemoryStream();
try
{
engine = Python.CreateEngine();
runtime = engine.Runtime;
runtime.IO.SetOutput(ms, Encoding.ASCII);
}
catch (Exception ex)
{
pythonResult.AppendText("Initialization IronPython: " + ex.Message);
return;
}
try
{
source = engine.CreateScriptSourceFromString(CodeTextBox.Text, SourceCodeKind.AutoDetect);
scope = runtime.CreateScope();
float[,] array2D = new float[10, 10];
scope.SetVariable("var2", array2D);
CompiledCode compil = source.Compile();
compil.Execute(scope);
byte[] arr_byte = ms.ToArray();
string text = Encoding.ASCII.GetString(arr_byte);
pythonResult.AppendText(text);
}
catch (Exception ex)
{
pythonResult.AppendText("Code error: " + ex.Message + "\n");
return;
}
}
当我去解释代码时:
for i in range(1, 10):
for j in range(1, 10):
var2[i,j] = 15.20
我收到以下错误:由于源不是原始类型,或者无法完成转换,因此无法从源类型扩展到目标类型。
我注意到在以下情况下编译不会返回错误:
for i in range(1, 10):
for j in range(1, 10):
var2[i,j] = integer number (example var2[i,j] = 15)
为什么会出现此错误?
有没有一种方法可以将float值分配给var2而不会出现错误?
感谢您的帮助