B4R Tutorial Inline C / C++

As in the other B4X tools you can embed C or C++ code in the project.

Example:
B4X:
Sub Process_Globals
   Public Serial1 As Serial
   Private Result, N1, N2 As Int 'ignore
End Sub

Private Sub AppStart
   Serial1.Initialize(115200)
   Log("AppStart")
   N1 = 10
   N2 = 20
   RunNative("Add", Null)
   Log("Result: ", Result)
End Sub

#if C
void Add (B4R::Object* o) {
   //lower case variables
   b4r_main::_result = b4r_main::_n1 + b4r_main::_n2;
}
#End if
The native method signature must be as written above. It can optionally return a B4R::Object*.
In most cases it is simpler to work with global variables.

Note that the global variable names are lower cased and the name includes the current module in the following format b4r_<current module lower case>.

You can add #include commands as demonstrated in the next example.

In this example we will use an external library named Narcoleptic. With this library we can put the board in deep sleep to preserve battery.
The library is available here: https://github.com/chrisfeltman/Arduino/tree/master/libraries/Narcoleptic

You need to download the h and cpp files and put them under arduino\libraries\Narcoleptic.
B4X:
Private Sub AppStart
   Serial1.Initialize(115200)
   Log("AppStart")
   Log(Millis)
   RunNative("Delay", 5000)
   Log("after: ", Millis, " (the internal timer was not updated during the sleep)")
End Sub

#if C
#include <Narcoleptic.h>
void Delay (B4R::Object* o) {
   Narcoleptic.delay(o->toULong());
}
#End if
 

derez

Expert
Licensed User
Longtime User
Erel (or someone else ?)
Although I have managed to write some inline C functions in the past, I still find it hard (as I do not control the language).
Can you please write a tutorial showing how to write the inline part ? (with/without parameters, how the b4r parameters should look like etc.)
Maybe just put several examples of all kinds of functions.
I'm sure it will help many users.
Thanks.
 

Peter Simpson

Expert
Licensed User
Longtime User
You can add any code you like with the inline C feature. For full libraries it is simpler to create a wrapper with the standard h and c files.

Hmm it's simpler to wrap if you can already code in C/C++. I've tried it twice by following your in depth 'B4R Library Wrapping Hints' file, man is it a complete nightmare lol ;)

When I get more proficient in C/C++ I'll give it another go, but there's not enough time in the day for me...
 
Top