Tricking B4A and Java to do byref. How about that!

Neither B4A nor Java support byref arguments nativily. Or do they?

By using this simple trick, you can mimic byref by exploiting their hidden pointer potential.

In Java:

private void Test() {
   //declare the byref value as an array with size 1
   String[] value = new String[1];
   //passing an array is not passing the whole array, but a pointer
   ByrefTest(value);
   //Et voila! the changed value
   System.out.print(value[0]);
}

private void ByrefTest(String rValue[]) {
   // using the pointer, B4A fills the string with our value
   rValue[0] = "Changed in the function!";
}

In B4A:

Sub Activity_Create(FirstTime As Boolean)
   ' dim the byref value as an array with size 1
   Dim value(1) As String
   ' passing an array is not passing the whole array, but a pointer
   ByrefTest(Value)
   ' Et voila! the changed value
   Msgbox( value(0), "")
End Sub

Sub ByrefTest(rValue() As String)
   ' using the pointer, B4A fills the string with our value
   rValue(0) = "Changed in the function!"
End Sub

This will come in handy when I convert some AForge.NET c# code to java, I’m sure!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s