处理vb.n中IronPython中抛出的事件

2024-05-15 19:32:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用IronPython尝试连接到我的vb.net版程序。在

我试图找到一些途径让事件在两者之间传播(不确定这是否可能)

我所做的是创建一个通用的DLL,我的程序(vb.net)引用它以及IronPython脚本,然后在我的vb.net代码中执行python。在

IronPython中,这可能吗?我找不到任何方法在它们之间传递类型A的对象,或者通过事件让它们链接起来。在


Tags: 对象方法代码程序脚本类型net链接
2条回答

IronPython扩展使用System.Reflection。它自动导入可用的类型和方法。在

您可以在DLL类库中公开您的类型。在

构建DLL后,可以在“IronPython”中导入它

import clr    
clr.AddReferenceToFileAndPath(r"C:\SomeFolder\SomeClassLibrary.dll")

还可以动态加载DLL和导入命名空间:

^{pr2}$

在库中公开您的事件:

Public Class SomeClass

    Public Event SomeEvent ....

然后可以在“IronPython”中使用它们

def SomeHandleHandler(*args):
    pass

Foo.SomeEvent += SomeHandleHandler

要执行相反的操作并使用IronPython触发事件,只需在Vb.Net代码。在

以下是工作代码:

在MyIpyClass.vb课堂文库

Public Class MyIpyClass
    Public Event MyEvent()

    Public Sub New()
        AddHandler MyEvent, HandleMyEvent()
    End Sub

    Private Function HandleMyEvent() as MyEventEventHandler
        Console.WriteLine("Raised My Event")
        Return Nothing
    End Function


    Public Sub RaiseMyEvent()
        RaiseEvent MyEvent()
    End Sub

End Class

IronPython代码:

import clr
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
clr.AddReferenceToFileAndPath("C:\\MyDllPath\\MyClassLibary.dll")
import MyClassLibary
from System.Windows.Forms import *
from System.Drawing import *


def mevent(*args): print("Event From IPY") # create IPython event hander for MyIpyClass.MyEvent

m = MyClassLibary.MyIpyClass() # create new instance of my class
m.MyEvent += mevent # Add IPythong Handler
m.RaiseMyEvent() # For Simplicity, Call MyIpyClass.MyEvent.RaiseEvent to raise the event



f = Form() # Create a Form to handle some events from System.Windows.Forms
f.Text = "My Form"

#defne a form click handler to print out the event args
def click(*args): print args
f.Click += click  

b = Button() # Create a button and add it to the form
b.Text = "GO"
b.Name = "GO"
b.Location = Point(10,10)

#create a button click handler that prints hellow word
def click(f, a):
    print("hello world")

#assign the button click handler
b.Click += click

#add the button to the form
f.Controls.Add(b)

#call Form.ShowDialog() - Show() blocks and will hang the form.
f.ShowDialog()

处理异常的一般方法是VB.net版程序应该对IronPython有一个引用/依赖关系。异常被抛出调用堆栈,直到它们被处理。您描述的体系结构表明它们是对等的,彼此之间没有直接的依赖关系,因此处理这些异常在Catch块中无法正常工作。在

我认为这种方法有效的唯一方法是,如果您可以在IronPython中处理异常,方法是将异常发送到公共DLL中的一个方法,该方法将异常作为事件参数的一部分引发事件,就像您可以获得UnhandledException事件一样

AddHandler My.Application.UnhandledException, AddressOf Foo

这将允许您的VB代码响应IronPython应用程序中发生的事情。在

相关问题 更多 >