Access a python class from C#

Hey there,

I’m gradually rewriting a Python plugin into C# code. Eventually everything will be native, but for the time being I’d like to find a way of accessing custom Python classes from C#.

Python class goes in as GenericParameter and is referenced in a static GH_ObjectWrapper python variable. I can see all the content in the compiler, but its Value field is not accessible.

Any ideas on how to drill into it?

Once you get the first Value from the GH_ObjectWrapper (which you should be able to access) you might try casting it to a dynamic, and then drilling into its properties from there.
so something like:

GH_ObjectWrapper wrapper = python;
dynamic pythonObject = wrapper.Value;
var geometry = pythonObject.geometry;

etc

not 100% sure this will work without knowing more about your particular case, but it’s worth a try.

2 Likes

Awesome @andheum!
The trick was to cast it to a dynamic, previously I was trying to cast to object and kept getting an error, that my object doesn’t contain a definition for ‘geometry’.

Thanks to your help, I can now access all the geometry within my python class directly from another C# component.

    protected override void SolveInstance(IGH_DataAccess DA)
    {
        DA.GetData(0, ref python);

        List<GeometryBase> outputGeo = new List<GeometryBase>();

        dynamic pythonObject = python.Value;

        foreach (var element in pythonObject.geometry["People"][0])
        {
            outputGeo.Add(element);
        }

        DA.SetDataList(0, outputGeo);
    }
1 Like