CodeFusionMobile CodeFusionMobile - 1 year ago 68 Question

Can I pass subset of an array to function in VB.NET?

I have a simple VB.NET form that acts as an interface to a control library with a public API.

One of the API calls takes an array of UIntegers ByRef:

Public Function Get_Values(source_id As Byte, first_value_address As Byte, number_of_values As Byte, ByRef valuesOut As UInteger()) As Integer

After the call, valuesOut will hold a list of values
long from
starting at

There is a hardware-driven limitation that the maximum number of values returned is 15 regardless of requested length. I need to get 28 values into an array from my VB.NET code.

Is it possible to send only part of an array variable to the function similar to the following C code?

uint[28] values;
Get_Values(0, 0, 15, values); // Get first part
Get_Values(0, 15, 13, &values[15]); // Get second part of data

Answer Source

No, what you're specifically asking for is not possible. Unlike C/C++-style arrays (which, simplified are just blocks of memory equal to sizeof(Type) * n, where n is the number of elements), .NET arrays cannot be referred to or offset by pointer arithmetic*. As a result, if the public API does not provide you with a way to indicate an offset in the array, then you're going to have to pass intermediate arrays to the function and reassemble them yourself once you've finished.

You could, however, wrap the call in your own version of the function:

public int GetValues(byte source_id, byte first_value_address, byte number_of_values, uint[] buffer, int offset)
    uint[] temp = new uint[number_of_values];

    int retValue = GetValues(source_id, first_value_address, number_of_values, temp);

    Array.Copy(temp, 0, buffer, offset, number_of_values);

    return retValue;

It should also be noted that ByVal and ByRef represent calling conventions, not whether or not the type is a value type. Unless you have a specific reason to (and here it appears that you do not), you don't need to specify ByRef on your array argument. The only type ByRef is required is when the function will change the actual value of the variable and you want that reflected in the calling code. The way that you're calling it, it appears that you allocate the array, pass it to the function, then use its contents. The only time the function would be modifying the variable's value is if it set it equal to a different array instance; simply changing the array values does not require ByRef in order for the calling code to see the results.

*Unless you actually use unsafe code and do pointer-based arrays yourself, but that's outside the scope of your question