2013-04-29 39 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 

注意()。