【发布时间】:2018-02-03 13:19:45
【问题描述】:
我创建了一个从 VBA 调用的进程外 COM 服务器 (C++)。
由于未知原因,当我多次调用它时(在同一个 sub 中至少两次),我只能使用 Dim xx As New xxx 调用它。
当我尝试使用 Dim xxx As xxx 然后 Set xx = new xxx 调用它时,我的 com 服务器会引发冲突读取异常,并且 VBA 返回错误代码 800706BE。
以下代码确实有效(伪代码 - 我删除了不相关的部分)。请注意,'Main' sub 调用 'aux' 函数,并且 Sub 和 'aux' 函数都调用我的 COM 服务器(两个不同的类)。
Function aux() As Double()
Dim com As New COMServer.classe2
Dim Returns() As Double
Returns = com.Method2 'actual call to the COM Server
aux = Returns
End Function
Sub Main()
Dim Resultat() As Double
Dim com1 As New COMServer.classe1
Dim Returns() As Double
Returns = aux ' call Function aux
Resultat = com1.Method1(Returns) 'actual call to the COM Server
End Sub
以下不起作用:
Function aux() As Double()
Dim com As COMServer.classe2
Set com = New COMServer.classe2
Dim Returns() As Double
Returns = com.Method2 'actual call to the COM Server
aux = Returns
End Function
Sub Main()
Dim Resultat() As Double
Dim com1 As COMServer.classe1
Set com1 = New COMServer.classe1
Dim Returns() As Double
Returns = aux ' call Function aux
Resultat = com1.Method1(Returns) 'a violation reading (c++) Exception is thrown here
End Sub
有人能解释一下为什么我的代码只在第一种情况下有效吗?
还要注意,如果我只在 sub 中调用服务器一次(不调用 aux),那么两种方法( Dim as New 和 Dim/Set )都可以工作。
编辑
我注意到在案例 1(有效的案例)中:我的服务器连续两次自动启动和停止(在 Windows 任务管理器中看到)。
而在第二种情况下(错误的情况):我的服务器仅启动一次 - 没有停止并引发错误。
现在我刚刚通过以下方式修改了第二种情况,异常消失了:
Sub Main()
Dim Resultat() As Double
Dim Returns() As Double
Returns = aux ' call Function aux
Dim com1 As COMServer.classe1
Set com1 = New COMServer.classe1
Resultat = com1.Method1(Returns) 'no more Exception
End Sub
唯一的区别是我在调用它之前设置了我的服务器(而不是在调用我的“辅助”函数之前对其进行初始化)。 这对某人有意义吗?
【问题讨论】: