Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1094541
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T23:59:11+00:00 2026-05-16T23:59:11+00:00

This is an offshoot question that’s related to another I asked here . I’m

  • 0

This is an offshoot question that’s related to another I asked here. I’m splitting it off because it’s really a sub-question:

I’m having difficulties casting an object of type dynamic to another (known) static type.

I have an ironPython script that is doing this:

import clr
clr.AddReference("System")
from System import *

def GetBclUri():
    return Uri("http://google.com")

note that it’s simply newing up a BCL System.Uri type and returning it. So I know the static type of the returned object.

now over in C# land, I’m newing up the script hosting stuff and calling this getter to return the Uri object:

dynamic uri = scriptEngine.GetBclUri();
System.Uri u = uri as System.Uri; // casts the dynamic to static fine

Works no problem. I now can use the strongly typed Uri object as if it was originally instantiated statically.

however….

Now I want to define my own C# class that will be newed up in dynamic-land just like I did with the Uri. My simple C# class:

namespace Entity
{
    public class TestPy // stupid simple test class of my own
    {
        public string DoSomething(string something)
        {
            return something;
        }
    }
}

Now in Python, new up an object of this type and return it:

sys.path.append(r'C:..path here...')
clr.AddReferenceToFile("entity.dll")
import Entity.TestPy

def GetTest():
    return Entity.TestPy(); // the C# class

then in C# call the getter:

dynamic test = scriptEngine.GetTest();
Entity.TestPy t = test  as Entity.TestPy; // t==null!!!

here, the cast does not work. Note that the ‘test’ object (dynamic) is valid–I can call the DoSomething()–it just won’t cast to the known static type

string s = test.DoSomething("asdf"); // dynamic object works fine

so I’m perplexed. the BCL type System.Uri will cast from a dynamic type to the correct static one, but my own type won’t. There’s obviously something I’m not getting about this…

—

Update: I did a bunch of tests to make sure my assembly refs are all lining up correctly. I changed the referenced assembly ver number then looked at the dynamic objects GetType() info in C#–it is the correct version number, but it still will not cast back to the known static type.

I then created another class in my console app to check to see I would get the same result, which turned out positive: I can get a dynamic reference in C# to a static type instantiated in my Python script, but it will not cast back to the known static type correctly.

—

even more info:

Anton suggests below that the AppDomain assembly binding context is the likely culprit. After doing some tests I think it very likely is. . . but I can’t figure out how to resolve it! I was unaware of assembly binding contexts so thanks to Anton I’ve become more educated on assembly resolution and the subtle bugs that crop up there.

So I watched the assembly resolution process by putting a handler on the event in C# prior to starting the script engine. That allowed me to see the python engine start up and the runtime start to resolve assemblies:

private static Type pType = null; // this will be the python type ref

// prior to script engine starting, start monitoring assembly resolution
AppDomain.CurrentDomain.AssemblyResolve 
            += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

… and the handler sets the var pType to the Type that python is loading:

static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{

    if (args.LoadedAssembly.FullName == 
        "Entity, Version=1.0.0.1, Culture=neutral, PublicKeyToken=null")
    {
        // when the script engine loads the entity assembly, get a reference
        // to that type so we can use it to cast to later.
        // This Type ref magically carries with it (invisibly as far as I can 
        // tell) the assembly binding context
        pType = args.LoadedAssembly.GetType("Entity.TestPy");
    }
}

So while the type used by python is the same on in C#, I’m thinking (as proposed by Anton) that the different binding contexts mean that to the runtime, the two types (the one in the ‘load binding context’ and the ‘loadfrom binding context) are different–so you can’t cast on to the other.

So now that I have hold of the Type (along with it’s binding context) loaded by Python, lo and behold in C# I can cast the dynamic object to this static type and it works:

dynamic test = scriptEngine.GetTest();
var pythonBoundContextObject = 
       Convert.ChangeType(test, pType); // pType = python bound

string wow = pythonBoundContextObject .DoSomething("success");

But, sigh, this doesn’t totally fix the problem, because the var pythonBoundContextObject while of the correct type, still carries the taint of the wrong assembly binding context. This means that I can’t pass this to other parts of my code because we still have this bizzare type mismatch where the invisible specter of binding context stops me cold.

// class that takes type TestPy in the ctor... 
public class Foo
{
    TestPy tp;

    public Foo(TestPy t)
    {
        this.tp = t;
    }
}

// can't pass the pythonBoundContextObject (from above): wrong binding context
Foo f = new Foo(pythonBoundContextObject); // all aboard the fail boat

So the resolution is going to have to be on the Python side: getting the script to load in the right assembly binding context.

in Python, if I do this:

# in my python script
AppDomain.CurrentDomain.Load(
    "Entity, Version=1.0.0.1, Culture=neutral, PublicKeyToken=null");

the runtime can’t resolve my type:

import Entity.TestPy #fails
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T23:59:11+00:00Added an answer on May 16, 2026 at 11:59 pm

    Here’s an answer from the IronPython team which covers the same problem:

    C# / IronPython Interop with shared C# Class Library

    (Lifted from http://lists.ironpython.com/pipermail/users-ironpython.com/2010-September/013717.html )

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is an offshoot of this question . How do I use a Login
This might seem like a stupid question I admit. But I'm in a small
This is a difficult and open-ended question I know, but I thought I'd throw
This is my first post here and I wanted to get some input from
This is a self-explanatory question: Why does this thing bubble into my try catch's
This is a bit of a long shot, but if anyone can figure it
This is starting to vex me. I recently decided to clear out my FTP,
This is kinda oddball, but I was poking around with the GNU assembler today
This past summer I was developing a basic ASP.NET/SQL Server CRUD app, and unit
This error just started popping up all over our site. Permission denied to call

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.