[IronPython] Question on instantiating a .NET class in Python and pass the instantiated object back to C#

Samuel Tjokrosoesilo samuelt at gmail.com
Thu Jan 22 17:59:28 CET 2009


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
DLRProto1_Extensions.Test03.CastTestObject
    Unable to cast object of type
'DLRProto1_Extensions.Test03.CastTestObject' to type
'DLRProto1_Extensions.Test03.CastTestObject'.

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()
        {
            cnt++;
        }
    }

# Python script
import clr
clr.AddReferenceToFile("DLRProto1_Extensions.dll")
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");
CompileAndExecute(script);

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.

Samuel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20090122/e2da7468/attachment.html>


More information about the Ironpython-users mailing list