gpt4 book ai didi

c# - 从 C# Ironpython 调用 .dll 函数

转载 作者:行者123 更新时间:2023-12-01 04:29:07 25 4
gpt4 key购买 nike

使用 Ironpython,我从 .py 文件创建了一个 .dll。它具有我想要调用以在 C# 中使用的类和相应函数。我创建了 .dll,以便可以向用户隐藏源代码。

这是我尝试过的:

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

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

此外,我想立即导入整个脚本,这样我就可以在任何时候调用任何内容[而不是“模拟”类]。

最佳答案

很多事情都可能出错,所以我将向您展示有效的完整示例。让我们以我在一些示例中获取的 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

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

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

现在我们有了 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();
}
}

关于c# - 从 C# Ironpython 调用 .dll 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32639893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com