C/C++ Question [SOLVED] How to return Double from Event in CPP Library

rwblinn

Well-Known Member
Licensed User
Longtime User
[SOLVED] See B4R Library rHCSR04.

This might be a trival question, but could not find a solution on how to return a Double from an Event in a CPP lib (named rHCSR04e).

Build a solution using an Array, but not sure if thats is the right way, i.e.
Private Sub DistanceChanged(Data() As Double)
vs
Private Sub DistanceChanged(Distance As Double) <-- Seeking for this solution

B4R Example using Array

B4X:
Sub Process_Globals
    Public Serial1 As Serial
    Public DistanceSensor As HCSR04e
    Private TriggerPinNr As Byte = 13
    Private EchoPinNr As Byte  = 12
    Private DISTANCECHANGEDBY As Double = 2.0
End Sub

Private Sub AppStart
    Serial1.Initialize(115200)
    DistanceSensor.Initialize("DistanceChanged", DISTANCECHANGEDBY, TriggerPinNr, EchoPinNr)
End Sub

' Handle distance changes >= DISTANCECHANGEDBY value
Private Sub DistanceChanged(Data() As Double)
    Dim l As Double = Data(0)
    Log("DistanceChanged Data: ", l)
End Sub

CPP Lib Snippets h and cpp
Thinking about instead
typedef void (*SubByteArray)(Array* darray) ;
use
typedef void (*SubDouble)(Double* ddouble) ; <-- Is this possible?

Code using Array
B4X:
namespace B4R{
    //~shortname: HCSR04e
    typedef void (*SubByteArray)(Array* darray) ;
    class B4RHCSR04{
        private:
            SubByteArray DistanceChangedSub;
        public:
            void Initialize(SubByteArray DistanceChangedSub, double DistanceChangedBy, Byte TriggerPin, Byte EchoPin);

B4X:
const UInt cp = B4R::StackMemory::cp;
ArrayDouble* arr = CreateStackMemoryObject(ArrayDouble);
double dat[1];
dat[0]    = me->distanceprev;
arr->data = dat;
arr->length = 1;
me->DistanceChangedSub(arr);
B4R::StackMemory::cp = cp;
 
Last edited:

rwblinn

Well-Known Member
Licensed User
Longtime User
Thanks, but how to apply to:

B4X:
const UInt cp = B4R::StackMemory::cp;
ArrayDouble* arr = CreateStackMemoryObject(ArrayDouble);
double dat[1];
dat[0]    = me->distanceprev;
arr->data = dat;
arr->length = 1;
me->DistanceChangedSub(arr);
B4R::StackMemory::cp = cp;
 
Top