问题
I'm trying to access .Net(C#) enums in IronPython, lets say we have
Test.dll
// Contains Several Enums
enum TestType{..}
enum TestQuality{..}
....
....
enum TestStatus{..}
//Similarly Multiple functions
public void StartTest(TestType testType, TestQuality testQuality){..}
....
....
public TestStatus GetTestStatus(){..}
and now if I try to call the above functions, I need to choose the appropriate enum parameters and so far what I did is this,
Iron Python [vs2012]
import clr
clr.AddReference('Test.dll')
from TestDll import *
test = Test()
# Initiate Enums
enumTestType = TestType
enumTestQuality = TestQuality
....
....
enumTestStatus = TestStatus
#Call Functions
test.StartTest(enumTestType.Basic, enumTestQuality.High)
....
....
# goes on
now the above IronPython code works fine, the only odd bit here is that I need to initiate all the enums(Intellisence doesnt work here) before I use them with the functions, this will become more difficult when there are more enums to use. whereas in C# environment(vs2012) we dont have to initiate but we can use them straight away when calling functions.
Is there a better way of dealing this in IronPython?
Please correct me if I'm wrong, thanks!
回答1:
Assuming the enums are contained within your Test
class you can either use them fully qualified
test.StartTest(Test.TestType.Basic, Test.TestQuality.High)
or by importing
from TestDll.Test import TestQuality, TestType
test.StartTest(TestType.Basic, TestQuality.High)
If the enums are in the same namespace as the Test
class they should be usable without additional imports:
test.StartTest(TestType.Basic, TestQuality.High)
回答2:
I had the same problem, but I fixed it in another way: using ScriptRuntime.LoadAssembly
.
Prerequisites:
VS2013
C# app executable, plus the Test.dll assembly. IronPython is hosted by the C# app.
Test.dll: (note that all is within the TestDll namespace)
namespace TestDll { // Contains Several Enums enum TestType{..} enum TestQuality{..} .... .... enum TestStatus{..} //Similarly Multiple functions public void StartTest(TestType testType, TestQuality testQuality){..} .... .... public TestStatus GetTestStatus(){..} }
I simply created the IronPython engine this way:
eng = Python.CreateEngine();
eng.Runtime.LoadAssembly(Assembly.GetAssembly(typeof(TestType))); // This allows "from TestDLL import *" in Python scripts
and then, execute the script with the usual
string pysrc = ...; // omitted, taken from the python script below
ScriptSource source = eng.CreateScriptSourceFromString(pysrc);
ScriptScope scope = eng.CreateScope();
source.Execute(scope);
This allowed me to write this Python code and execute it within the C# app: (note that I'm using the enum names directly)
from TestDll import *
test = Test()
#Call Functions
test.StartTest(TestType.Basic, TestQuality.High)
....
....
# goes on
来源:https://stackoverflow.com/questions/27017429/accessing-net-enums-in-iron-python