从C#Ironpython调用.dll函数

时间:2021-11-07 09:04:50

Using Ironpython, I created a .dll from a .py file. It has classes and respective functions that I want to call to be used in c#. I created the .dll so that I can hide the source from the user.

使用Ironpython,我从.py文件创建了一个.dll。它有类和各自的函数,我想调用它们在c#中使用。我创建了.dll,以便我可以隐藏用户的来源。

Here is what I have tried:

这是我尝试过的:

    ScriptEngine engine = Python.CreateEngine();
    scope = engine.CreateScope();
    engine.Runtime.LoadAssembly(Assembly.LoadFile(fullPath2DLL));
    scope = engine.ImportModule("Simulation");

However, it cannot find "Simulation".

但是,它找不到“模拟”。

Also, I want to import the whole script at once so I can call whatever, whenever [Rather than the class 'Simulation'].

此外,我想一次导入整个脚本,所以我可以调用任何东西,而不是[类'模拟']。

1 个解决方案

#1


2  

Many things could go wrong, so I'll just show you complete example which works. Let's take this python code that I grabbed in some example:

很多事情都可能出错,所以我只会告诉你完整的例子。让我们看一下我在一些例子中抓取的python代码:

MyGlobal = 5

class Customer(object):
"""A customer of ABC Bank with a checking account. Customers have the
following properties:

Attributes:
    name: A string representing the customer's name.
    balance: A float tracking the current balance of the customer's account.
"""

def __init__(self, name, balance=0.0):
    """Return a Customer object whose name is *name* and starting
    balance is *balance*."""
    self.name = name
    self.balance = balance

def withdraw(self, amount):
    """Return the balance remaining after withdrawing *amount*
    dollars."""
    if amount > self.balance:
        raise RuntimeError('Amount greater than available balance.')
    self.balance -= amount
    return self.balance

def deposit(self, amount):
    """Return the balance remaining after depositing *amount*
    dollars."""
    self.balance += amount
    return self.balance

Now let's open ipy and compile that into dll with:

现在让我们打开ipy并将其编译成dll:

>>> import clr
>>> clr.CompileModules("path_to.dll", "path_to.py");

Now we have dll. As you see python code contains class definition, and our goal is to create instance of that class in C# and call some methods.

现在我们有了dll。如您所见,python代码包含类定义,我们的目标是在C#中创建该类的实例并调用一些方法。

 public class Program {
    private static void Main(string[] args) {
        ScriptEngine engine = Python.CreateEngine();            
        engine.Runtime.LoadAssembly(Assembly.LoadFile(@"path_to.dll"));
        // note how scope is created. 
        // "test" is just the name of python file from which dll was compiled. 
        // "test.py" > module named "test"
        var scope = engine.Runtime.ImportModule("test");
        // fetching global is as easy as this
        int g = scope.GetVariable("MyGlobal");
        // writes 5
        Console.WriteLine(g);
        // how class type is grabbed
        var customerType = scope.GetVariable("Customer");
        // how class is created using constructor with name (note dynamic keyword also)
        dynamic customer = engine.Operations.CreateInstance(customerType, "Customer Name");
        // calling method on dynamic object
        var balance = customer.deposit(10.0m);
        // this outputs 10, as it should
        Console.WriteLine(balance);
        Console.ReadKey();
    }
}

#1


2  

Many things could go wrong, so I'll just show you complete example which works. Let's take this python code that I grabbed in some example:

很多事情都可能出错,所以我只会告诉你完整的例子。让我们看一下我在一些例子中抓取的python代码:

MyGlobal = 5

class Customer(object):
"""A customer of ABC Bank with a checking account. Customers have the
following properties:

Attributes:
    name: A string representing the customer's name.
    balance: A float tracking the current balance of the customer's account.
"""

def __init__(self, name, balance=0.0):
    """Return a Customer object whose name is *name* and starting
    balance is *balance*."""
    self.name = name
    self.balance = balance

def withdraw(self, amount):
    """Return the balance remaining after withdrawing *amount*
    dollars."""
    if amount > self.balance:
        raise RuntimeError('Amount greater than available balance.')
    self.balance -= amount
    return self.balance

def deposit(self, amount):
    """Return the balance remaining after depositing *amount*
    dollars."""
    self.balance += amount
    return self.balance

Now let's open ipy and compile that into dll with:

现在让我们打开ipy并将其编译成dll:

>>> import clr
>>> clr.CompileModules("path_to.dll", "path_to.py");

Now we have dll. As you see python code contains class definition, and our goal is to create instance of that class in C# and call some methods.

现在我们有了dll。如您所见,python代码包含类定义,我们的目标是在C#中创建该类的实例并调用一些方法。

 public class Program {
    private static void Main(string[] args) {
        ScriptEngine engine = Python.CreateEngine();            
        engine.Runtime.LoadAssembly(Assembly.LoadFile(@"path_to.dll"));
        // note how scope is created. 
        // "test" is just the name of python file from which dll was compiled. 
        // "test.py" > module named "test"
        var scope = engine.Runtime.ImportModule("test");
        // fetching global is as easy as this
        int g = scope.GetVariable("MyGlobal");
        // writes 5
        Console.WriteLine(g);
        // how class type is grabbed
        var customerType = scope.GetVariable("Customer");
        // how class is created using constructor with name (note dynamic keyword also)
        dynamic customer = engine.Operations.CreateInstance(customerType, "Customer Name");
        // calling method on dynamic object
        var balance = customer.deposit(10.0m);
        // this outputs 10, as it should
        Console.WriteLine(balance);
        Console.ReadKey();
    }
}