B4R Question Inline C and B4R vars

Cableguy

Expert
Licensed User
Longtime User
Hi Guys

I'm trying to use a piece of C code I found:

B4X:
//VARIABLES AND DEFINES HERE - NEEDED BY THE WS2812 DRIVER CODE
#define numberOfLEDs 40// total number of RGB LEDs
byte RGB[120];//take your number of LEDs and multiply by 3

The #define numberOfLeds 40 line I was able to convert to #define numberOfLeds b4r_ws2812b::_nleds
But been trying everything I could remember to turn the byte RGB[120] into something that can be declared inside the B4R code without having to touch the C Code Block
This array length depends on the Number of Leds, passed in the first line, multiplied by 3, in this case, 40*3=120.

I almost always get an error complaining that the size of the array was not set to an integer constant...
B4X:
b4r_ws2812b.cpp:16: error: array bound isnot an integer constant before ']' token
byte RGB[b4r_ws2812b::_ledarraysize];//take your number of LEDs and multiply by 3

Is there anyway this array can be defined inside the B4R part of the code?
 

wonder

Expert
Licensed User
Longtime User
I don't know if it helps, but this is my B4A NinjaCore library C code for creating and disposing a dynamic native array.

Note that, if you access the array directly, element 0 will always hold the array size.

B4X:
/*Creates a new native array
You must DISPOSE this object once you don't need it anymore*/
uintptr_t NativeArrayCreateNew(int size)
{
    int *workingArray = nullptr;
    workingArray = (int*)malloc(sizeof(int) * (size + 1));
    workingArray[0] = size;
    int i;
    for (i = 1; i < size + 1; ++i) {
        workingArray[i] = 0;
    }
    return (uintptr_t)workingArray;
}

//Assigns the given value to the given array index
void NativeArraySetElement(uintptr_t arrayAddress, int position, int value)
{
    int *workingArray = (int*)arrayAddress;
    workingArray[position + 1] = value;
}

//Obtains the value stored at the given index
int NativeArrayGetElement(uintptr_t arrayAddress, int position)
{
    int *workingArray = (int*)arrayAddress;
    return workingArray[position + 1];
}

//Obtains the array size
int NativeArrayGetSize(uintptr_t arrayAddress)
{
    int *workingArray = (int*)arrayAddress;
    return workingArray[0];
}

//Resets the array content
void NativeArrayReset(uintptr_t arrayAddress)
{
    int *workingArray = (int*)arrayAddress;
    int i;
    for (i = 1; i < workingArray[0] + 1; ++i) {
        workingArray[i] = 0;
    }
}

//Disposes the native array
void NativeArrayDispose(uintptr_t arrayAddress)
{
    int *workingArray = (int*)arrayAddress;
    free(workingArray);
    workingArray = nullptr;
}

B4A Usage:
B4X:
'Dim myArray(10) As Int
Dim myArray = xxx.NativeArrayCreateNew(10) As Long 'Type *MUST* be Long

'myArray(0) = 32767
xxx.NativeArraySetElement(myArray, 0, 32767)

'Log(myArray.Lenght)
Log(xxx.NativeArrayGetSize(myArray))

'Dispose method - No B4A equivalent
xxx.NativeArrayDispose(myArray)
 
Last edited:
Upvote 0
Top