How to invoke C#/.NET namespace in IronPython? - c#

I'm looking to replicate the following in IronPython and searching has so far been fruitless and/or disappointing.
namespace Groceries
{
public class ChocolateMilk : Milk
{
// Other stuff here
}
}
The idea would be that the compiled Python DLL will be loaded into a C# program through System.Reflection.Assembly.Load and a GetType("Groceries.ChocolateMilk") on the loaded DLL would not return null.
The most recent answer I was able to find was in 2008 and said that it was impossible without using the Hosting API - http://lists.ironpython.com/pipermail/users-ironpython.com/2008-October/008684.html.
Any suggestions on how to accomplish this would be greatly appreciated. Any conclusions that this is currently impossible to do via IronPython will also be appreciated, but less so.

I'm a bit confused on what you're asking here. Are you trying to instantiate that C# code in your IronPython modules? Or do you have the equivalent classes written in IronPython and you want to instantiate them in your C# code?
Based on the link you posted, I suppose you're going for the latter and have IronPython classes that you want instantiated in your C# code. The answer is, you cannot directly instantiate them. When you compile IronPython code to an assembly, you cannot use the types defined there with your regular .NET code since there is not a one-to-one mapping between IronPython classes and .NET classes. You would have to host the assembly in your C# project and instantiate it that way.
Consider this module, Groceries.py compiled to Groceries.dll residing in the working directory:
class Milk(object):
def __repr__(self):
return 'Milk()'
class ChocolateMilk(Milk):
def __repr__(self):
return 'ChocolateMilk()'
To host the module in your C# code:
using System;
using IronPython.Hosting;
using System.IO;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var engine = Python.CreateEngine();
var groceriesPath = Path.GetFullPath(#"Groceries.dll");
var groceriesAsm = Assembly.LoadFile(groceriesPath);
engine.Runtime.LoadAssembly(groceriesAsm);
dynamic groceries = engine.ImportModule("Groceries");
dynamic milk = groceries.ChocolateMilk();
Console.WriteLine(milk.__repr__()); // "ChocolateMilk()"
}
}
Otherwise to go the other way and create an instance of your .NET type in your IronPython code (as your title suggests). You'd need to add the path to your assembly, reference it, then you could instantiate it as needed.
# add to path
import sys
sys.path.append(r'C:\path\to\assembly\dir')
# reference the assembly
import clr
clr.AddReferenceToFile(r'Groceries.dll')
from Groceries import *
chocolate = ChocolateMilk()
print(chocolate)

Related

Retrieve <Version> tag written in csproj file from dll [duplicate]

I am trying to get the executing assembly version in C# 3.0 using the following code:
var assemblyFullName = Assembly.GetExecutingAssembly().FullName;
var version = assemblyFullName .Split(',')[1].Split('=')[1];
Is there another proper way of doing so?
Two options... regardless of application type you can always invoke:
Assembly.GetExecutingAssembly().GetName().Version
If a Windows Forms application, you can always access via application if looking specifically for product version.
Application.ProductVersion
Using GetExecutingAssembly for an assembly reference is not always an option. As such, I personally find it useful to create a static helper class in projects where I may need to reference the underlying assembly or assembly version:
// A sample assembly reference class that would exist in the `Core` project.
public static class CoreAssembly
{
public static readonly Assembly Reference = typeof(CoreAssembly).Assembly;
public static readonly Version Version = Reference.GetName().Version;
}
Then I can cleanly reference CoreAssembly.Version in my code as required.
In MSDN, Assembly.GetExecutingAssembly Method, is remark about method "getexecutingassembly", that for performance reasons, you should call this method only when you do not know at design time what assembly is currently executing.
The recommended way to retrieve an Assembly object that represents the current assembly is to use the Type.Assembly property of a type found in the assembly.
The following example illustrates:
using System;
using System.Reflection;
public class Example
{
public static void Main()
{
Console.WriteLine("The version of the currently executing assembly is: {0}",
typeof(Example).Assembly.GetName().Version);
}
}
/* This example produces output similar to the following:
The version of the currently executing assembly is: 1.1.0.0
Of course this is very similar to the answer with helper class "public static class CoreAssembly", but, if you know at least one type of executing assembly, it isn't mandatory to create a helper class, and it saves your time.
using System.Reflection;
{
string version = Assembly.GetEntryAssembly().GetName().Version.ToString();
}
Remarks from MSDN http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getentryassembly%28v=vs.110%29.aspx:
The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly method from the C# component returns null, because the entry point for the process was unmanaged code rather than a managed assembly.
Product Version may be preferred if you're using versioning via GitVersion or other versioning software.
To get this from within your class library you can call System.Diagnostics.FileVersionInfo.ProductVersion:
using System.Diagnostics;
using System.Reflection;
//...
var assemblyLocation = Assembly.GetExecutingAssembly().Location;
var productVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).ProductVersion
This should do:
Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName aName = assem.GetName();
return aName.Version.ToString();
I finally settled on typeof(MyClass).GetTypeInfo().Assembly.GetName().Version for a netstandard1.6 app. All of the other proposed answers presented a partial solution. This is the only thing that got me exactly what I needed.
Sourced from a combination of places:
https://msdn.microsoft.com/en-us/library/x4cw969y(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/2exyydhb(v=vs.110).aspx

C# creating a wrapper namespace?

In C#, how can I import all classes from one namespace into another namespace such that these classes are directly accessible from the second namespace?
I'm essentially attempting to rename a namespace in an externally visible manner.
Since code is worth a thousand words, given a DLL with the following namespace:
// Externally written DLL I have no control over.
namespace A
{
class ClassA {...}
}
I'd like to be able to create another DLL along the lines of:
// My DLL
namespace Wrapper
{
using A;
}
So that I can use it like:
// Final C# program.
using Wrapper;
var a = ClassA();
In python, I could accomplish what I want with import *:
# external.py
class ClassA:
...
# mymodule.py
from external import *
# final_program.py
import mymodule
a = mymodule.ClassA()
Disclaimer
I know this is a terrible idea, but I'm unfortunately being constrained by external requirements. The short version is that I have an external DLL that needs to interface with a proprietary system (EnScript, if you're curious). This proprietary system has restrictions on the naming of namespaces that the external DLL of course violates. Thus, I'm attempting to use the wrapper DLL to expose a namespace that is considered valid.
Related Questions
Talks about using in C# vs wildcard imports in java/python. Does not address issue of accessing from second namespace:
Import all subclasses like Java but in C#
C# equivalent to wildcard imports in Java
Namespaces in C# vs imports in Java and Python
Question about including classes in namespace. Issue was use of separate projects and so not applicable to this question:
How To Include Classes From Another Namespace In Assembly Instead of Writing Them Into A Separate DLL File?
You can't move a type to a different namespace (other than physically moving the code). The .NET type system uses the full namespace to uniquely identify the type.
But you can create an alias to mask the original namespace.
Let's say you have a class MyProject.Foo.Bar.Xyzzy.MyClass, and you are tired of typing MyProject.Foo.bar.Xyzzy. You can add a Using directive at the top of the code file like this:
Using DifferentNamespace = MyProject.Foo.Bar.Xyzzy;
Once you have done this, you can refer to the class with just
var c = new DifferentNamespace.MyClass();
You can even use this to include a different namespace in the current default namespace. This will compile:
namespace Example.Classes
{
class MyClass
{
}
}
namespace Example
{
using Example = Example.Classes;
class Test
{
static void Test1()
{
var c = new Example.MyClass(); //Not Example.Classes.MyClass
}
}
}
But unfortunately you have to leave the alias there; i.e., this won't compile:
namespace Example.Classes
{
class MyClass
{
}
}
namespace Example
{
using Example = Example.Classes;
class Test
{
static void Test1()
{
var c = new MyClass(); //Error
}
}
}

IronPython get to internal class from C# dll

I'm using IronPython for fetching inner classes from C# dll.
for example:
namespace Platform.CardHost {
internal class ExtensionManager : IExtensionManager, IDisposable {
//... other code
IronPython Code
import clr
clr.AddReference('Platform.CardHost')
import Platform.CardHost.ExtensionManager
# raise ImportError: No module named ExtensionManager
# if it add to ref
clr.AddReference('Platform.CardHost.ExtensionManager')
# raise Error
# IOError: System.IO.IOException: Could not add reference to assembly
# Platform.CardHost.ExtensionManager
How can I import ExtensionManager? Or is this not possible?
So like I already wrote:
make ExtensionManager public if you want to access it from somewhere else than your assembly.
The definition of internalis
The type or member can be accessed by any code in the same assembly, but not from another assembly.
what you could do, to make it only available for another assembly is, to make it visible for a friend assembly:
using System.Runtime.CompilerServices;
using System;
[assembly:InternalsVisibleTo("my_friend_assembly")]
internal class ExtensionManager : IExtensionManager, IDisposable
{
}
else, I don't see any reason why making it internal but trying to access it from another assembly/your ironpython-script. Yeah, for friend assemblies, there are reasons, for sure.
for your new update: "I can't change class":
so maybe, the guy who wrote that class doesn't want you to import the class from elsewhere? That's the use of internal,protected,private and public.
Imho, it would be really bad to define in C# a class as internal, so you can't import it from C#, but IronPython still lets you import it.
for sure, you could try getting the code from the assembly, change it and make it again to a new assembly, like you wrote. But that's a lot of work and possibly in the end, it won't work.
Thanks to Matthias Burger for a fact that prompted the idea.
i try to decompile dll. because the file were large after he disassemble, it can't assemble without problem.
I wrote to the guy, he say me use C# interface ICardHost.
here how i use it, maybe for someone who meet similar problem.
clr.AddReference('Platform.CardHost')
from Platform import CardHost
from Platform.CardHost import ICardHost
host = CardHost.CardHost.CreateInstance(session)
# ExtensionManager is internal class but it available by interface
# here how to use C# interface
em = ICardHost.ExtensionManager.__get__(host)
as it in C#
// cardHost
public sealed class CardHost : Component, ICardHost
// ICardHost
public interface ICardHost {
IExtensionManager ExtensionManager { get; }

How to create at runtime a .NET exe file assembly from already compiled classes

I need to create executable file assembly at runtime. My main goal is to compile types from the actual Project (.dll) performing compilation task, without using strings keeping the code that needs to be compiled to the output exe file. Maintaining those strings during code development/refactoring would be a nightmare. As shown in the example below, when I refactor class CodeToCompile, I also need to remember to change string codeToCompile in RuntimeCompiler.Compile() method:
using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
namespace RuntimeCompiler
{
public class Compiler
{
public void Compile()
{
string codeToCompile =
#"public class CodeToCompile
{
public static void Main(string[] args)
{
Console.ReadLine();
}
}";
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
CompilerParameters parameters = new CompilerParameters
{
GenerateExecutable = true,
OutputAssembly = "Generated.exe"
};
CompilerResults results = icc.CompileAssemblyFromSource(parameters, codeToCompile);
}
}
public class CodeToCompile
{
public static void Main(string[] args)
{
Console.ReadLine();
}
}
}
What I would like to achive is changing the string with code that needs to be compiled to reference of the type that needs to be compiled into .exe assembly.
string codeToCompile = "..."; //CodeToCompile source code
CompilerResults results = icc.CompileAssemblyFromSource(parameters, codeToCompile);
CompilerResults results = icc.CompileAssemblyFromSource(parameters, typeof(CodeToCompile));
Any ideas what would be the best way to achieve this?
I have easily found information how to dynamically compile C# code from string using System.CodeDom.Compiler namespace, as shown above. Thus any method to get a runtime object uncompiled code as a string would do the job. My research in this direction did not give me solution and I strongly doubt that it is possible to do in an easy way.
My second idea is to use mechanism to "move" compiled type from the running assembly to a newly created one, but unfortunately I also haven't found any solution to do this task.
...without using strings keeping the code that needs to be compiled to output exe file. Maintaining those strings during code development/refactoring would be a nightmare...
My advice here is to look into .NET Globalization
Globalization involves designing and developing a world-ready app that supports localized interfaces and regional data for users in multiple cultures...The handling of characters and strings is a central focus of globalization, because each culture or region may use different characters and character sets and sort them differently. More...
An alternative to CodeDom.Compiler is .NET's Reflection Emit:
...the System.Reflection.Emit namespace that allow a compiler or tool to emit metadata and Microsoft intermediate language (MSIL) at run time and optionally generate a portable executable (PE) file on disk. Script engines and compilers are the primary users of this namespace. More...

Build Python scripts and call methods from C#

Is there any way to make this scenario work?
There is a Python script. It is built into a DLL by running this script with IronPython:
import clr
clr.CompileModules("CompiledScript.dll", "script.py")
The goal is to call this DLL's methods from C# code. .NET Reflector shows there is one class in the DLL - DLRCashedCode and the methods we are interested in are private static methods of this class.
For example, there is a function in the script:
def scriptMethod(self, text):
...
Its representation in the DLL is:
private static object scriptMethod(Closure closure1, PythonFunction $function, object self, object text)
{
...
}
Closure and PythonFunction are IronPython classes (from Microsoft.Scripting.dll and IronPython.dll).
So far so good. Is it possible this method to be called by C# code? The idea of using reflection like
Type t = typeof(DLRCachedCode);
string methodName = "scriptMethod";
MethodInfo method = t.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static);
object[] parameters = new object[] { "param1", "param2" }; // the "params problem"
method.Invoke(null, parameters);
seems harder because of setting the method's parameters. If they are (any how) initialized correctly, could we expect the method to work smoothly?
Is there a better way to call this methods from C#? For various different reasons we prefer to have the script built as a .NET assembly and not to call the script itself.
Sort of. You cannot access the Python methods directly from C# code. Unless you are playing with C# 4.0 and the dynamic keyword or you are very, very special ;). However, you can compile an IronPython class to a DLL and then use IronPython hosting in C# to access the methods (this is for IronPython 2.6 and .NET 2.0).
Create a C# program like this:
using System;
using System.IO;
using System.Reflection;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
// we get access to Action and Func on .Net 2.0 through Microsoft.Scripting.Utils
using Microsoft.Scripting.Utils;
namespace TestCallIronPython
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
ScriptEngine pyEngine = Python.CreateEngine();
Assembly myclass = Assembly.LoadFile(Path.GetFullPath("MyClass.dll"));
pyEngine.Runtime.LoadAssembly(myclass);
ScriptScope pyScope = pyEngine.Runtime.ImportModule("MyClass");
// Get the Python Class
object MyClass = pyEngine.Operations.Invoke(pyScope.GetVariable("MyClass"));
// Invoke a method of the class
pyEngine.Operations.InvokeMember(MyClass, "somemethod", new object[0]);
// create a callable function to 'somemethod'
Action SomeMethod2 = pyEngine.Operations.GetMember<Action>(MyClass, "somemethod");
SomeMethod2();
// create a callable function to 'isodd'
Func<int, bool> IsOdd = pyEngine.Operations.GetMember<Func<int, bool>>(MyClass, "isodd");
Console.WriteLine(IsOdd(1).ToString());
Console.WriteLine(IsOdd(2).ToString());
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
Make a trivial Python class like this:
class MyClass:
def __init__(self):
print "I'm in a compiled class (I hope)"
def somemethod(self):
print "in some method"
def isodd(self, n):
return 1 == n % 2
Compile it (I use SharpDevelop) but the clr.CompileModules method should also work. Then shove the compiled MyClass.dll into the directory where the compiled C# program lives and run it. You should get this as the result:
Hello World!
I'm in a compiled class (I hope)
in some method
in some method
True
False
Press any key to continue . . .
This incorporates Jeff's more direct solution that eliminates having to create and compile a small Python 'stub' and also shows how you can create C# function calls that access the methods in the Python class.
The clr.CompileModules is purely a load-time optimization - it doesn't make the scripts directly available to a static languge like C#. You'll need to host the IronPython runtime, and then you can load the DLL into the runtime and use IronPython's hosting interfaces to access it.

Categories

Resources