[IronPython] Question on instantiating a .NET class in Python and pass the instantiated object back to C#
curt at hagenlocher.org
Thu Jan 22 18:18:49 CET 2009
The error "unable to cast object of type X to type X" is generally the
result of an assembly loader issue. If you're using the hosting interface
and want to get a reference to the hosting assembly, don't use
"clr.AddReferenceToFile" -- you'll end up with the same assembly loaded
twice. I think "clr.AddReference" might be okay, but the best choice is for
the hosting C# code to inject itself directly into the ScriptRuntime by
saying something like this:
On Thu, Jan 22, 2009 at 8:59 AM, Samuel Tjokrosoesilo <samuelt at gmail.com>wrote:
> Forgive me if this has been asked before. I already went through the
> archive and could not find any answer to this.
> Basically, the idea is to be able to define a class in C#.
> Then in Python, make a reference to the C# library and instantiate an
> object based on this class.
> Then as requested by C# through IronPython, this object reference is then
> passed back to be used/manipulated in C#.
> The error/issue I'm having is the casting of the object (passed from
> Python) to the C# class. (last part of the code below)
> Funny thing is that when I put a breakpoint on Visual Studio, I'm able to
> cast these objects in the Watch Window, but only when the code actually runs
> it fails with exception as below:
> Microsoft.Scripting.ArgumentTypeException: Expected
> DLRProto1_Extensions.Test03.CastTestObject, got
> Unable to cast object of type
> 'DLRProto1_Extensions.Test03.CastTestObject' to type
> I won't include the initialization of the engine and scope as they have
> been taken care by the base class.
> // C# library
> public class CastTestObject
> private int cnt;
> private int limit;
> public CastTestObject()
> cnt = 0;
> limit = 1000;
> public void IncrementCount()
> # Python script
> import clr
> from DLRProto1_Extensions.Test03 import CastTestObject
> cto = CastTestObject()
> print cto
> def returnTestObject():
> cto2 = CastTestObject()
> return cto2
> // C# code manipulation below
> string script = ReadScript("Scenarios\\test03.py");
> CastTestObject ctoObject;
> // does not work, but works in Watch Window in Debug Mode
> ctoObject = ScrScope.GetVariable<CastTestObject>("cto");
> // cast does not work, but works in Watch Window in Debug Mode
> object cObject = ScrEngine.Execute("returnTestObject()", ScrScope);
> ctoObject = (CastTestObject) cObject; //fails here with the exception above
> Any help is greatly appreciated.
> Thank you.
> Users mailing list
> Users at lists.ironpython.com
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Ironpython-users