C# DLL 不能影响从 VB6 应用程序通过引用传递的数字的值

C# DLL cannot affect value of a number passed by reference from a VB6 application(C# DLL 不能影响从 VB6 应用程序通过引用传递的数字的值)

本文介绍了C# DLL 不能影响从 VB6 应用程序通过引用传递的数字的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用 VB6 DLL 的旧版 VB6 应用程序,我正在尝试将 VB6 DLL 移植到 C#,而尚未触及主要的 VB6 应用程序代码.旧的 VB6 DLL 有一个通过引用接收 VB6 long(32 位整数)的接口,并更新了值.在我编写的 C# DLL 中,主 VB6 应用程序从未看到更新的值.就好像真正编组到 C# DLL 的是对原始数据副本的引用,而不是对原始数据的引用.我可以通过引用成功传递数组并更新它们,但单个值没有表现.

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. The old VB6 DLL had one interface that received a VB6 long (32-bit integer) by reference, and updated the value. In the C# DLL I have written, the updated value is never seen by the main VB6 application. 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. I can successfully pass arrays by reference, and update them, but single values aren't behaving.

C# DLL 代码如下所示:

The C# DLL code looks something like this:

[ComVisible(true)]
public interface IInteropDLL
{
   void Increment(ref Int32 num);
}
[ComVisible(true)]
public class InteropDLL : IInteropDLL
{
    public void Increment(ref Int32 num) { num++; }
}

调用的 VB6 代码如下所示:

The calling VB6 code looks something like this:

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 )

因为你使用了括号,所以值被强制按值传递,而不是通过引用(编译器创建一个临时副本并通过引用传递that).

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).

去掉括号:

dll.Increment num

<小时>

更完整的解释 by 马克J.

这篇关于C# DLL 不能影响从 VB6 应用程序通过引用传递的数字的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C# DLL 不能影响从 VB6 应用程序通过引用传递的数字的值

基础教程推荐