C# DLL cannot affect value of a number passed by reference from a VB6 application

大憨熊 提交于 2019-12-28 02:17:17

问题


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.

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++; }
}

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.


回答1:


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.



来源:https://stackoverflow.com/questions/8070033/c-sharp-dll-cannot-affect-value-of-a-number-passed-by-reference-from-a-vb6-appli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!