how implement callback from C++ function to Swift - c++

I tried do something in a cpp class and when doing the function return callback to swift.
So i do these things :
Creating this function in callbackClass.cpp
int callback::run(void (*callback)(int))
{
for (unsigned int i = 0; i < 100; i++)
{
callback(i);
}
return 0;
}
In callbackClass.hpp :
class callbackClass.hpp
{
.
.
.
public:
int run(void (*callback)(int));
};
#endif
And for header.h‍‍ :
int callback(void (*callback)(int));
It's good until logging callback in Swift side:
func callbackFunc(){
callback({valueFromCallback in //call cpp function
print(valueFromCallback) //Works fine
})
}
But when try to do other stuff like :
func callbackFunc(){
var value : String!
callback({valueFromCallback in //call cpp function
value = String(valueFromCallback) //It has a problem
})
}
Xcode return this error :
A C function pointer cannot be formed from a closure that captures context
I have already seen these questions but did not help:
Swift: Pass data to a closure that captures context
How to cast self to UnsafeMutablePointer<Void> type in swift
A C function pointer cannot be formed from a closure that captures context

Eventually I realized it possible to pass 'closure' to c++ as argument
So at first I created a Closure in Swift class:
typealias closureCallback = (Int32) -> ()
Then passed it to cpp side :
In header.h‍‍
int callback(void (^closureCallback)(int));
In callbackClass.hpp :
class callbackClass.hpp
{
.
.
.
public:
int run(void (^closureCallback)(int));
};
#endif
And in callbackClass.cpp
int callback::run(void (^closureCallback)(int))
{
for (unsigned int i = 0; i < 100; i++)
{
closureCallback(i);
}
return 0;
}
At last handle it in Swift :
typealias closureCallback = (Int32) -> ()
func callbackFunc(){
var value : String!
let closureValue: closureCallback = {valueFromclosureCallback in
value = String(valueFromclosureCallback)
}
callback(closureValue) //call cpp function
}

Related

Unit Testing: Verify that a method was called, without testing frameworks like Mockito or MockK

Not using testing frameworks like MockK or Mockito seems to be becoming more and more popular. I decided to try this approach. So far so good, returning fake data is simple. But how do I verify that a function (that does not return data) has been called?
Imagine having a calss like this:
class TestToaster: Toaster {
override fun showSuccessMessage(message: String) {
throw UnsupportedOperationException()
}
override fun showSuccessMessage(message: Int) {
throw UnsupportedOperationException()
}
override fun showErrorMessage(message: String) {
throw UnsupportedOperationException()
}
override fun showErrorMessage(message: Int) {
throw UnsupportedOperationException()
}
}
With MockK I would do
verify { toaster.showSuccessMessage() }
I do not want to reinvent a wheel so decided to ask. Finding anything on Google seems to be very difficult.
Since this is a thing, I assume the point would be to totally remove mocking libraries and everything can be done without them.
The old school way to do it before any appearance of the mocking library is to manually create an implementation that is just for testing . The test implementation will store how an method is called to some internal state such that the testing codes can verify if a method is called with expected parameters by checking the related state.
For example , a very simple Toaster implementation for testing can be :
public class MockToaster implements Toaster {
public String showSuccesMessageStr ;
public Integer showSuccesMessageInt;
public String showErrorMessageStr;
public Integer showErrorMessageInt;
public void showSuccessMessage(String msg){
this.showSuccesMessageStr = msg;
}
public void showSuccessMessage(Integer msg){
this.showSuccesMessageInt = msg;
}
public void showErrorMessage(String msg){
this.showErrorMessageStr = msg;
}
public void showErrorMessage(Integer msg){
this.showErrorMessageInt = msg;
}
}
Then in your test codes , you configure the object that you want to test to use MockToaster. To verify if it does really call showSuccessMessage("foo") , you can then assert if its showSuccesMessageStr equal to foo at the end of the test.
A lot of people seem to be suggesting the very straight forward solution for this, which totally makes sense. I decided to go a bit fancy and achieve this syntax:
verify(toaster = toaster, times = 1).showErrorMessage(any<String>()).
I created simple Matchers:
inline fun <reified T> anyObject(): T {
return T::class.constructors.first().call()
}
inline fun <reified T> anyPrimitive(): T {
return when (T::class) {
Int::class -> Int.MIN_VALUE as T
Long::class -> Long.MIN_VALUE as T
Byte::class -> Byte.MIN_VALUE as T
Short::class -> Short.MIN_VALUE as T
Float::class -> Float.MIN_VALUE as T
Double::class -> Double.MIN_VALUE as T
Char::class -> Char.MIN_VALUE as T
String:: class -> "io.readian.readian.matchers.strings" as T
Boolean::class -> false as T
else -> {
throw IllegalArgumentException("Not a primitive type ${T::class}")
}
}
}
Added a map to store call count for each method to my TestToaster where the key is the name of the function and value is the count:
private var callCount: MutableMap<String, Int> = mutableMapOf()
Whenever a function gets called I increase current call count value for a method. I get current method name through reflection
val key = object {}.javaClass.enclosingMethod?.name + param::class.simpleName
addCall(key)
In oder to achieve the "fancy" syntax, I created inner subcalss for TestToaster and a verify function:
fun verify(toaster: Toaster , times: Int = 1): Toaster {
return TestToaster.InnerToaster(toaster, times)
}
That function sends current toaster instance to the inner subclass to create new instance and returns it. When I call a method of the subclass in my above syntax, the check happens. If the check passes, nothing happens and test is passed, if conditions not met - and exception is thrown.
To make it more general and extendable I created this interface:
interface TestCallVerifiable {
var callCount: MutableMap<String, Int>
val callParams: MutableMap<String, CallParam>
fun addCall(key: String, vararg param: Any) {
val currentCountValue = callCount.getOrDefault(key, 0)
callCount[key] = currentCountValue + 1
callParams[key] = CallParam(param.toMutableList())
}
abstract class InnerTestVerifiable(
private val outer: TestCallVerifiable,
private val times: Int = 1,
) {
protected val params: CallParam = CallParam(mutableListOf())
protected fun check(functionName: String) {
val actualTimes = getActualCallCount(functionName)
if (actualTimes != times) {
throw IllegalStateException(
"$functionName expected to be called $times, but actual was $actualTimes"
)
}
val callParams = outer.callParams.getOrDefault(functionName, CallParam(mutableListOf()))
val result = mutableListOf<Boolean>()
callParams.values.forEachIndexed { index, item ->
val actualParam = params.values[index]
if (item == params.values[index] || (item != actualParam && isAnyParams(actualParam))) {
result.add(true)
}
}
if (params.values.isNotEmpty() && !result.all { it } || result.isEmpty()) {
throw IllegalStateException(
"$functionName expected to be called with ${callParams.values}, but actual was with ${params.values}"
)
}
}
private fun isAnyParams(vararg param: Any): Boolean {
param.forEach {
if (it.isAnyPrimitive()) return true
}
return false
}
private fun getActualCallCount(functionName: String): Int {
return outer.callCount.getOrDefault(functionName, 0)
}
}
data class CallParam(val values: MutableList<Any> = mutableListOf())
}
Here is the complete class:
open class TestToaster : TestCallVerifiable, Toaster {
override var callCount: MutableMap<String, Int> = mutableMapOf()
override val callParams: MutableMap<String, TestCallVerifiable.CallParam> = mutableMapOf()
override fun showSuccessMessage(message: String) {
val key = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
addCall(key, message)
}
override fun showSuccessMessage(message: Int) {
val key = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
addCall(key, message)
}
override fun showErrorMessage(message: String) {
val key = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
addCall(key, message)
}
override fun showErrorMessage(message: Int) {
val key = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
addCall(key, message)
}
private class InnerToaster(
verifiable: TestCallVerifiable,
times: Int,
) : TestCallVerifiable.InnerTestVerifiable(
outer = verifiable,
times = times,
), Toaster {
override fun showSuccessMessage(message: String) {
params.values.add(message)
val functionName = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
check(functionName)
}
override fun showSuccessMessage(message: Int) {
params.values.add(message)
val functionName = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
check(functionName)
}
override fun showErrorMessage(message: String) {
params.values.add(message)
val functionName = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
check(functionName)
}
override fun showErrorMessage(message: Int) {
params.values.add(message)
val functionName = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
check(functionName)
}
}
companion object {
fun verify(toaster: Toaster, times: Int = 1): Toaster {
return InnerToaster(toaster as TestCallVerifiable, times)
}
}
}
I have not tested this extensively and it will evolve with time, but so far it works well for me.
I also wrote an article about this on Medium: https://sermilion.medium.com/unit-testing-verify-that-a-method-was-called-without-testing-frameworks-like-mockito-or-mockk-433ef8e1aff4

C++ when i try get string, it always empty, lambda

I have object of class
class MenuItem {
public:
void updateInputText(string text)
{
this->text += text;
}
string getText() const {
return this->text;
}
void trigger(Event event)
{
switch (event) {
case ENTER:
this->onEnterAction();
break;
}
}
function<void(void)> onEnterAction;
private:
Text text;
void onEnter();
};
I create object and set event handler
MenuItem IP;
IP.onEnterAction = eventOnEnter;
// ENTER - element from enum
IP.trigger(ENTER);
Event handler:
function<void(void)> eventOnEnter = [&] () {
auto selected = next(this->currentMenu.begin(), this->selected);
selected->updateInputText("Hello");
};
And second object of MenuItem
MenuItem nextButton;
next.onEnterAction = [&] () {
Log::write("IP: " + IP.getText());
};
// ENTER - element from enum
next.trigger(ENTER);
But IP.getText() always empty. What i do wrong?
All objects created in one scope (in one function)
Whenever I see something like this
MenuItem nextButton;
next.onEnterAction = [&] () { // Should next be nextButton???
Log::write("IP: " + IP.getText());
};
// ENTER - element from enum
next.trigger(ENTER);
I'm waiting for a disaster to occur. And if you had shown a fully working example you would have noted that your example code might have worked ... so what is the problem.
The main problem is that you capture everything by reference, but from your code I can't se if it should work, but I think not in a large system, the reason is that the captured values have gone out of scope.
std::vector<MenuItem> CreateMenu() {
std::vector<MenuItem> res;
function<void(void)> eventOnEnter = [&] () {
auto selected = next(this->currentMenu.begin(), this->selected);
selected->updateInputText("Hello");
};
MenuItem IP;
IP.onEnterAction = eventOnEnter;
res.push_back(IP);
MenuItem nextButton;
nextButton.onEnterAction = [&] () {
Log::write("IP: " + IP.getText());
};
res.push_back(nextButton);
return res;
}
void Call() {
auto buttons = CreateMenu();
// what is captured at this point???
buttons.back().trigger(ENTER);
}
Most of the captured has now gone out of scope.
Surt gave me a hint... Scope.
All MenuItems pushed to vector, and when i use this function
next.onEnterAction = [&] () {
Log::write("IP: " + IP.getText());
};
I try to get text from empty variable, when i changed function to
next.onEnterAction = [&] () {
auto selectedIP = std::next(currentMenu.begin(), 0);
Log::write("IP: " + selectedIP.getText());
};

Passing a TForm as an argument to a function

I have an application with several Forms. Two of them are quite similar, they have features in the form of VCL objects (labels, images, etc...) in common, which I named the same.
I want to have a function in a specific class which can accept one of these two Form as a parameter in order to modify the parameters that they have in common. The solution I came around does not seem to work.
As my application is quite big and complicated, I replicated the problem using a small example.
First, below is an example of my MainForm :
And an example of one subForm (they are all arranged in a similar way)
I have an additionnal class which is used to fill in the Edits on the subForms. The code for this class is the following:
#pragma hdrstop
#include "master_class.h"
#include "sub_Form2.h"
#include "sub_Form3.h"
#include "sub_Form4.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
Master::Master(void)
{
}
Master::~Master(void)
{
}
void Master::WriteToForm(TForm* Form)
{
TForm2* curForm = static_cast<TForm2*>(Form);
TForm3* self = dynamic_cast<TForm3*>(Form);
TForm2* self2 = dynamic_cast<TForm2*>(Form);
if (self != NULL && self2 == NULL) {
TForm3* curForm = static_cast<TForm3*>(Form);
}
else if (self == NULL && self2 != NULL) {
TForm2* curForm = static_cast<TForm2*>(Form);
}
curForm -> Edit1 -> Text = "blablabla_1";
curForm -> Edit2 -> Text = "blablabla_2";
}
And in the MainForm, the code for the "Fill Form2" button is the following:
Master1 -> WriteToForm(Form2);
where Master1 is just an object of the Master class.
This works very well for Form2 :
But for Form3, which is filled up using Master1 -> WriteToForm(Form3), here is what I get, which the same pb than in my real application:
So what should go to the Edit, is misplaced. I think the main pb comes from the fact that I did not create every label, edit, etc... on the same order. I did that on purpose to mimic my real application. To verify this, I created a 3rd subForm, where this time the VCL objects were created in the same order as my first subForm, and this works:
So I would suspect that this comes from the initial cast
TForm2* curForm = static_cast<TForm2*>(Form);
When I pass Form3 as an argument, Form3 is somewhat casted into the "shape" of Form2, which is not defined in the same order. Maybe this could be corrected by modifying directly the DFM file, but it is not a realistic approach for my main app.
I do this initial cast otherwise I get a compilation error saying that curForm is not known at the first line
curForm -> Edit1 -> Text = "blablabla_1";
So, is there a better way to pass the Form as an argument to the WriteToForm function?
Just because two types are similar does not mean they are related. Your code does not work because your two Form classes are not related to each other in any way. You can't just cast one to the other arbitrarily.
To solve this, you have several options:
code for both Form classes separately, eg:
void Master::WriteToForm(TForm* Form)
{
TForm2* curForm2 = dynamic_cast<TForm2*>(Form);
TForm3* curForm3 = dynamic_cast<TForm3*>(Form);
if (curForm2)
{
curForm2->Edit1->Text = _D("blablabla_1");
curForm2->Edit2->Text = _D("blablabla_2");
}
else if (curForm3)
{
curForm3->Edit1->Text = _D("blablabla_1");
curForm3->Edit2->Text = _D("blablabla_2");
}
}
Or:
void WriteToForm(TForm2* Form);
void WriteToForm(TForm3* Form);
...
void Master::WriteToForm(TForm2* Form)
{
Form->Edit1->Text = _D("blablabla_1");
Form->Edit2->Text = _D("blablabla_2");
}
void Master::WriteToForm(TForm3* Form)
{
Form->Edit1->Text = _D("blablabla_1");
Form->Edit2->Text = _D("blablabla_2");
}
Make your function use a template (however, be aware of this: Why can templates only be implemented in the header file?):
template<typename T>
void WriteToForm(T* Form);
...
void Master::WriteToForm<T>(T* Form)
{
Form->Edit1->Text = _D("blablabla_1");
Form->Edit2->Text = _D("blablabla_2");
}
make the two Form classes derive from a common base class or interface, eg:
class TBaseForm : public TForm
{
public:
inline __fastcall TBaseForm(TComponent *Owner) : TForm(Owner) {}
virtual void SetEdit1(const String &Text) = 0;
virtual void SetEdit2(const String &Text) = 0;
};
...
class TForm2 : public TBaseForm
{
...
public:
__fastcall TForm2(TComponent *Owner);
...
void SetEdit1(const String &NewText);
void SetEdit2(const String &NewText);
};
__fastcall TForm2::TForm2(TComponent *Owner)
: TBaseForm(Owner)
{
...
}
void TForm2::SetEdit1(const String &NewText)
{
Edit1->Text = NewText;
}
void TForm2::SetEdit2(const String &NewText)
{
Edit2->Text = NewText;
}
...
repeat for TForm3...
...
void Master::WriteToForm(TBaseForm* Form)
{
Form->SetEdit1(_D("blablabla_1"));
Form->SetEdit2(_D("blablabla_2"));
}
Or:
__interface INTERFACE_UUID("{E900785E-0151-480F-A33A-1F1452A431D2}")
IMyIntf : public IInterface
{
public:
virtual void SetEdit1(const String &Text) = 0;
virtual void SetEdit2(const String &Text) = 0;
};
...
class TForm2 : public TForm, public IMyIntf
{
...
public:
__fastcall TForm2(TComponent *Owner);
...
void SetEdit1(const String &NewText);
void SetEdit2(const String &NewText);
};
__fastcall TForm2::TForm2(TComponent *Owner)
: TForm(Owner)
{
...
}
void TForm2::SetEdit1(const String &NewText)
{
Edit1->Text = NewText;
}
void TForm2::SetEdit2(const String &NewText)
{
Edit2->Text = NewText;
}
...
repeat for TForm3...
...
void Master::WriteToForm(IMyIntf* Intf)
{
Intf->SetEdit1(_D("blablabla_1"));
Intf->SetEdit2(_D("blablabla_2"));
}
use RTTI to access the fields, eg:
#include <System.Rtti.hpp>
void Master::WriteToForm(TForm* Form)
{
TRttiContext Ctx;
TRttiType *FormType = Ctx.GetType(Form->ClassType());
TRttiField *Field = FormType->GetField(_D("Edit1"));
if (Field)
{
TValue value = Field->GetValue(Form);
if( (!value.Empty) && (value.IsObject()) )
{
TObject *Obj = value.AsObject();
// Either:
static_cast<TEdit*>(Obj)->Text = _D("blablabla_1");
// Or:
TRttiProperty *Prop = Ctx.GetType(Obj->ClassType())->GetProperty(_D("Text"));
if (Prop) Prop->SetValue(Obj, String(_D("blablabla_1")));
}
}
Field = FormType->GetField(_D("Edit2"));
if (Field)
{
TValue value = Field->GetValue(Form);
if( (!value.Empty) && (value.IsObject()) )
{
TObject *Obj = value.AsObject();
// Either:
static_cast<TEdit*>(Obj)->Text = _D("blablabla_2");
// Or:
TRttiProperty *Prop = Ctx.GetType(Obj->ClassType())->GetProperty(_D("Text"));
if (Prop) Prop->SetValue(Obj, String(_D("blablabla_2")));
}
}
}

capnproto : Can I get an AnyPointer from a struct?

Given this schema
struct TestObject
{
value1 #0 : Int32 = -5;
value2 #1 : Float32 = 9.4;
}
struct TestContainer
{
object #0: TestObject;
}
Is it possible to get an AnyPointer::Builder from the TestObject::Builder in c++ code?
This is what I am trying to do:
::capnp::MallocMessageBuilder message;
auto container = message.initRoot<TestContainer>();
TestObject::Builder objBuilder = container.initObject();
//Get an AnyPointer
capnp::AnyPointer::Builder anyBuilder = capnp::toAny( objBuilder )(); //No this does not work.
MyTestObject test( 41, 643.7f );
test.serialise( anyBuilder );
What I am trying to do is have an abstract interface with a single argument type
eg.
class ISerialisable
{
virtual void serialise(capnp::AnyPointer::Builder& any) = 0;
}
class MyTestObject: public ISerialisable
{
void serialise(capnp::AnyPointer::Builder& any) override
{
auto testObjBuilder = any.getAs<TestObject>(); or should initAs be used?
testObject.setValue1( whatever1);
testObject.setValue2( whatever2);
}
}
Is it possible to go down this route?

BlackBerry ObjectListField

I am developing a BlackBerry project under JDE 4.6.1. The problem is that when adding an item to the list, a NullPointerException is thrown from method measureListRow
NPE callstack:
CustomerListField(ObjectListField).measureListRow(ListField, int, int)
CustomerListField(ListField).layout(int, int)
CustomerListField(ObjectListField).layout(int, int)
VList(Manager).layoutChild(Field, int, int)
Notes:
db_.getDataAccess() - database
getListCount - getting the number of items in the list
CustomerListItem - the structure of a list item
And the relevant code:
public class CustomerListField extends ObjectListField implements ListFieldCallback, ChangeListener {
private PagedDataFetcher dataFetcher = new CustomerListPagedDataFetcher();
…
public CustomerListField() {
try {
super.set(new Object[db_.getDataAccess().getListCount()]);
} catch (Throwable e) {
}
}
public void drawListRow(ListField listField, Graphics g, int index, int y,
int width) {
CustomerListItem currentRow = (CustomerListItem) get(listField, index);
…
}
public Object get(ListField list, int index) {
try {
return dataFetcher.getRowAtIndex(index);
} catch (Throwable e) {
return null;
}
}
// To obtain the data
public class CustomerListPagedDataFetcher extends PagedDataFetcher {
protected Vector get(int from, int to) throws Exception {
return DataAccess.getDataAccess().getLists(from, to);
}
}
/**
* layout for list
*/
final class VList extends VerticalFieldManager {
private final ObjectListField list;
int maxHeight = Display.getHeight() - getFont().getHeight() * 2 - 5;
VList(ObjectListField list) {
super(Manager.VERTICAL_SCROLLBAR | Manager.VERTICAL_SCROLL);
this.list = list;
}
public int getPreferredHeight() {
return 45 * list.getSize();
}
protected void sublayout(int width, int height) {
super.sublayout(width, height);
setExtent(width, maxHeight);
}
}
If you're getting a NullPointerException in measureRowList, the first place I'd look is the source of that method to see what null value is being dereferenced. It looks like you didn't include the source for that method though.