将 VB 函数回调作为参数传递给 .NET

Pass VB Function callback as parameter to .NET

部分 Visual Basic 程序正在移至 .NET dll。

参数调用可以传递成功,一切正常运行

如何在长时间的 运行ning 异步任务后传递 VB6 的回调函数供 .NET 调用?

在 .NET 中

Public Delegate Function VBCallBackFunc() As Integer

Public Function DoSomething(a As String, b As String, c As String, _
parent As IntPtr, Optional ByVal CallbackAddr As VBCallBackFunc = Nothing) As Boolean Implements _DotNetLib.DoSomething

VB6

result = DotNetLib.DoSomething(strA, strB, strC, Me.hwnd, AddressOf DotNetCallback)

Public Function DotNetCallback() As Long
    MsgBox ("Callback")
End Function

在 VB 的对象浏览器中:

Function DoSomething(strA As String, strB As String, strC As String,
 parent As Long, [CallbackAddr As VBCallBackFunc]) As Boolean

Member of DotNetLib

但是它说 "Invalid use of AddressOf operator" ???

关于使用事件的评论是一个不错的选择,但我更倾向于使用接口,所以这里有一个解决方案。

(徒手写代码,需要语法检查,名称可以清理,仅供说明)

在 .NET 中:

为回调创建 COM 公开接口:

Public Interface IVBCallBack
   Public Function VBCallBackFunc() As Integer
End Interface

改变你的 DoSomething 是这样的:

Public Function DoSomething(a As String, b As String, c As String, parent As IntPtr, ByVal CallbackAddr As IVBCallBack) As Boolean

在 VB6 中:

result = DotNetLib.DoSomething(strA, strB, strC, Me.hwnd, Me)

(您需要 class、控件或表单 Implements IVBCallBack

Public Function IVBCallBack_VBCallBackFunc() As Long
    MsgBox ("Callback")
End Function

确保在 .NET 端有一个方法来清理和释放所有引用,因为 .NET 持有对 VB6 对象的引用。

还有一点要注意。不要在除主 UI 线程以外的任何线程上回调 VB6!