VS 2008 中的 VB6 AddressOf 和回调

VB6 AddressOf and Callbacks in VS 2008

嘿,我正在尝试通过其自动 VB6 代码转换器将一些 VB6 代码转换为 VS 2008。大多数都很好,但有一些需要改进。

说的是这段代码:

InitializeGrCap = GrCapInitialize(AddressOf GrCapStatusEventHandler)

GrCapInitialize 是这样的:

Public Declare Function GrCapInitialize Lib "GrFinger.dll" Alias "_GrCapInitialize@4" (ByVal StatusEventHandler As Integer) As Integer

GrCapStatusEventHandler是:

Public Sub GrCapStatusEventHandler(ByVal pidSensor As Integer, ByVal eventRaised As Integer)
    While fireStatus = True
        System.Windows.Forms.Application.DoEvents()
    End While

    myPIdSensor = pidSensor
    myEventRaised = eventRaised     
    fireStatus = True

    While fireStatus = True
        System.Windows.Forms.Application.DoEvents()
    End While
End Sub

我不确定如何重写它以解决以下问题:

Error 44 'AddressOf' expression cannot be converted to 'Integer' because 'Integer' is not a delegate type.

第二个说的是这段代码:

GrCapStartCapture(myIdSensor, AddressOf GrCapFingerEventHandler, AddressOf GrCapImageEventHandler)

再一次,AddressOf ... 是这个错误:

GrCapFingerEventHandler:

Public Sub GrCapFingerEventHandler(ByVal pidSensor As Integer, ByVal eventRaised As Integer)
    While fireFinger = True
        System.Windows.Forms.Application.DoEvents()
    End While

    myPIdSensor = pidSensor
    myEventRaised = eventRaised
    fireFinger = True

    While fireFinger = True
        System.Windows.Forms.Application.DoEvents()
    End While
End Sub

GrCapImageEventHandler

Public Sub GrCapImageEventHandler(ByVal pidSensor As Integer, ByVal width As Integer, ByVal height As Integer, ByVal pRawImage As Integer, ByVal res As Integer)
    While fireImage = True
        System.Windows.Forms.Application.DoEvents()
    End While

    myPIdSensor = pidSensor
    myWidth = width
    myHeight = height
    myRes = res
    myRawImage = pRawImage
    fireImage = True

    While fireImage = True
        System.Windows.Forms.Application.DoEvents()
    End While
End Sub

同样,错误是:

Error 44 'AddressOf' expression cannot be converted to 'Integer' because 'Integer' is not a delegate type.

任何人都可以帮助我将这 2 个代码区域转换为 .net 吗?

在 VB6 中,您传递给非托管函数的 Integer 将是一个函数指针。 VB.NET 不做函数指针。 .NET 使用委托代替,委托是引用方法的对象。这意味着您需要一个具有与托管方法匹配的签名的委托类型,然后您可以将非托管函数的参数声明为该类型,并在调用该函数时传递该类型的实例。您可以声明自己的委托类型,例如

Public Delegate Sub GrCapStatusCallback(ByVal pidSensor As Integer, ByVal eventRaised As Integer)

声明您的外部函数使用该类型:

Public Declare Function GrCapInitialize Lib "GrFinger.dll" Alias "_GrCapInitialize@4" (ByVal StatusEventHandler As GrCapStatusCallback) As Integer

然后您的调用应该按原样工作,或者您可以显式创建一个委托实例:

InitializeGrCap = GrCapInitialize(New GrCapStatusCallback(AddressOf GrCapStatusEventHandler))

或者,您可以使用现有的 ActionFunc 委托,它们分别用于 SubsFunctions,可以支持 0 到 16 个参数:

Public Declare Function GrCapInitialize Lib "GrFinger.dll" Alias "_GrCapInitialize@4" (ByVal StatusEventHandler As Action(Of Integer, Integer)) As Integer