[英]C# DLL cannot affect value of a number passed by reference from a VB6 application
I have a legacy VB6 application that calls a VB6 DLL, and I am trying to port the VB6 DLL to C# without yet touching the main VB6 application code. 我有一个调用VB6 DLL的遗留VB6应用程序,我试图将VB6 DLL移植到C#而不触及主VB6应用程序代码。 The old VB6 DLL had one interface that received a VB6 long (32-bit integer) by reference, and updated the value. 旧的VB6 DLL有一个接口通过引用接收VB6长(32位整数),并更新了该值。 In the C# DLL I have written, the updated value is never seen by the main VB6 application. 在我编写的C#DLL中,主VB6应用程序从未看到更新的值。 It acts as though what was really marshalled to the C# DLL was a reference to a copy of the original data, not a reference to the original data. 它就像真正编组到C#DLL的内容一样,是对原始数据副本的引用,而不是对原始数据的引用。 I can successfully pass arrays by reference, and update them, but single values aren't behaving. 我可以通过引用成功传递数组,并更新它们,但单个值不行。
The C# DLL code looks something like this: C#DLL代码看起来像这样:
[ComVisible(true)]
public interface IInteropDLL
{
void Increment(ref Int32 num);
}
[ComVisible(true)]
public class InteropDLL : IInteropDLL
{
public void Increment(ref Int32 num) { num++; }
}
The calling VB6 code looks something like this: 调用VB6代码看起来像这样:
Private dll As IInteropDLL
Private Sub Form_Load()
Set dll = New InteropDLL
End Sub
Private Sub TestLongReference()
Dim num As Long
num = 1
dll.Increment( num )
Debug.Print num ' prints 1, not 2. Why?
End Sub
What am I doing wrong? 我究竟做错了什么? What would I have to do to fix it? 我需要做些什么来解决它? Thanks in advance. 提前致谢。
dll.Increment( num )
Because you are using parentheses, the value is forcibly passed by value, not by reference (the compiler creates a temporary copy and passes that by reference). 因为您正在使用括号,所以值会被值强制传递,而不是通过引用传递(编译器会创建一个临时副本并通过引用传递它 )。
Remove the parentheses: 删除括号:
dll.Increment num
EDIT: A more complete explanation by MarkJ . 编辑: MarkJ的 更完整的解释 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.