Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.



Java and Groovy are both "pass-by-value" languages.  That is, if you pass a value to a method and the method modifies it, you don't see a change in the calling scope.   

COM, on the other hand, supports both "pass-by-value" (or "byval") and "pass-by-reference" (or "byref").  When you call a method that accepts a "pass-by-reference" parameter, the method can modify the parameter value, and this will be reflected in the calling scope. 

Byref argument passing was always a favorite of C/C++ programmers, who often use the result of a method to pass exception information.  It was the default way to pass values in versions of Visual Basic through 6.  With the advent of modern try/catch exception handling, modifying values inside a method is generally considered bad programming practice.  Visual Basic (and COM) still supports byref, but byval is now defined as the default setting.  You should not have to deal with byref parameters often. That doesn't mean it will never happen, though. 

It shouldn't surprise you that Scriptom that Scriptom supports passing parameters by-reference, just in case you need it.   


The other way that values are passed by reference is through an explicit method call you makecalls.  This one is a little more complicated, but only a little.  Scriptom takes care of most of the scary details for you.I order to pass a value by-reference, you first have to wrap it in a VariantByref object

How Does it Work?

The basic concept is that you place the value in a wrapper object, pass the wrapper to the method, and finally get the new value back from the wrapper when the method returns.  Scriptom's wrapper object is VariantByref (org.codehaus.groovy.scriptom.VariantByref), like this:

One cool feature is that Scriptom allows you to just pass a String or an Integer or whatever type the method requires, if you don't care about getting back the changed value.  Most of the time, even when a parameter is defined as byref, you don't really care about seeing the changed value.  So you can ignore all of this. 

Okay, so let's assume that you do care.  The changed value matters to you. Otherwise you would have stopped reading in the last paragraph, right?  Consider the following VB6 object. It simply takes a byref String and modifies it.

Code Block

Option Explicit

Public Sub StringByrefDemo(ByRef A As String)
    A = A & " VB6 was here!"
End Sub

The following example illustrates how to call the VB DLL so that the modified String is not lost.

Code Block

  def testObj = new ActiveXObject("MyDemo.PassByrefDemo");

  VariantByref svalue = new VariantByref("This is Groovy!");
  assert svalue.value == "This is Groovy! VB6 was here!";

That is really all there is to it.  Again, you shouldn't have to use this feature very often.  But when the API is designed around byref parameters, this can be a lifesaver!