2013-04-29 83 views
1

我有字典在Ironpython脚本中定义,我想从我的C# 代码访问此字典。有人可以提供示例代码来实现我的要求。来自C的访问Ironpython字典#

对不起,我没有提到我的代码问题陈述。

import clr 
clr.AddReference("System.Core") 
import System 
clr.ImportExtensions(System.Linq) 
from System.Collections.Generic import Dictionary,List 

def check(self): 
    dict1 = Dictionary[str,str] 
    dict1["a"] = "aa" 
    dict2 = Dictionary[str,str] 
    dict2["b"] = "bb" 
    self[0] = dict1 
# self.Add(dict1) 
    return self 

C#

var runtime = Python.CreateRuntime(); 
dynamic test = runtime.UseFile("Test.py"); 


var myDictList = new List<Dictionary<string, string>>(); 
var myDL = new List<Dictionary<string, string>>(); 
myDL = test.check(myDictList); 

我的目标是在python的字典顺序操作(添加,从列表中删除),并发送回C#在那里我可以进一步使用它。 我想要的是要么在Python或C#中创建一个字典的列表,并在(Python和C#)这两个地方使用它。 我该怎么做。

+0

为您的努力提供代码会让其他人更好地帮助您 – Ramunas 2013-04-29 13:08:40

回答

4

这工作:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using Microsoft.Scripting.Hosting; 
using Microsoft.Scripting.Utils; 
using Microsoft.Scripting.Runtime; 
using IronPython; 
using IronPython.Hosting; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      ScriptEngine pyEngine = Python.CreateEngine(); 
      ScriptScope pyScope = pyEngine.CreateScope(); 
      ScriptSource pyScript = pyEngine.CreateScriptSourceFromString("d = {'a':1,'b':2,'c':3}"); 
      CompiledCode pyCompiled = pyScript.Compile(); 
      pyCompiled.Execute(pyScope); 
      IronPython.Runtime.PythonDictionary d = pyScope.GetVariable("d"); 
      Console.WriteLine(d.get("a")); 
      Console.Read(); 
     } 
    } 
} 

应该给你的第一个值的键 'A'。希望这会让你走。 可能有一个或两个包含太多。

+0

@VigneshVino您可以为我的更新评论提供答案 – user703686 2013-05-02 05:07:05

+0

Python字典和C#字典只能分享他们的名字。例如,你不能在C#中使用混合类型。使用IronPython.Runtime.PythonDictionary作为数据类型有什么问题?您可以使用'pyScope.SetVariable'来设置数据以及您可以获取数据。 – 2013-05-02 07:44:36

+0

在python中,我正在编写一个解析器,它将文件路径作为输入并创建解析项目的字典列表。然后我想在C#中使用解析数据。所以我不认为pyScope.SetVariable或pyScope.GetVariable会帮助我,因为在C#中,我不会修改任何我正在使用解析的内容。 – user703686 2013-05-07 06:46:02

0
def check(self): 
    dict1 = Dictionary[str,str]() 
    dict1["a"] = "aa" 
    dict2 = Dictionary[str,str]() 
    dict2["b"] = "bb" 
    self[0] = dict1 
    # self.Add(dict1) 
    return self 

注意()。