creating checkbox/button in opencv - opencv

The error while creating a button in opencv
argument of type 'void (Window::)(int, void*)' does not match 'cv::ButtonCallback {aka void ()(int, void)}'
class Window{
void ChecKBox(int state, void* val){
// do nothing for now
return;
}
public:
void createCheckbox(){
cv::createButton(checkboxname, CheckBox, NULL, CV_CHECKBOX, 0);
}
};
int main(){
Window w;
w.createCheckBox();
}
I can't seem to find the fix to this problem.

oh, you can't pass in a member function of a class here. think of it, where would the 'this' pointer come from ? (like you call class members like w.CheckBox(1,NULL); there is no 'w' here. )
the highgui interface is a bit limited. it can only call free functions or static members.
so, if your callback function does not need anything from Window, make it static:
class Window {
static void CheckBox(int state, void* val) { /*you can't use 'this' here!*/ return; }
public:
void createCheckBox() { cv::createButton(checkboxname, CheckBox, NULL, CV_CHECKBOX, 0); }
};
int main() {
Window w;
w.createCheckBox();
}

Related

Getting an error on a qsort compare function

I'm using C++Builder 10.4.2 and having a problem with qsort. I rarely use qsort so I might be making a clumsy mistake. Array 'buffer' is a 2D 'char' array with more than 26,000 rows of single words.
This is the call:
qsort((void *)buffer,wordcount,sizeof(buffer[1]),sort_function);
This is the compare function:
int TForm::sort_function(const void *a, const void *b)
{
return( strcmp((char *)a,(char *)b) );
}
This is the error message. Notice that it's complaining about sort_function for 4th argument:
search.h(46): candidate function not viable: no known conversion from 'int (__closure *)(const void *, const void *)' to 'int (*)(const void *, const void *) __attribute__((cdecl))'
What is 'int (__closure *)'? Is there a way to fix my compare function?
__closure is a Borland compiler extension for obtaining a pointer to a non-static class method, without regard to the type of class being used. This is most commonly used in VCL/FMX components, which allow you to assign event handlers from any class you want, which is not something that standard C++ typically allows you to do.
qsort() expects a C-style function pointer in the 4th parameter. You can't get such a pointer to a non-static class method.
To solve this, you need to use either:
a standalone function
a static class method
a non-capturing C++ lambda (C++11 or higher only)
Since your sort_function() does not need access to your TForm object, declaring sort_function() as static would be the simplest fix:
// .h
class TForm
{
...
private:
static int sort_function(const void *a, const void *b);
void doSomething();
...
};
// .cpp
int TForm::sort_function(const void *a, const void *b)
{
return strcmp((const char *)a, (const char *)b);
}
void TForm::doSomething()
{
...
qsort(buffer, wordcount, sizeof(buffer[1]), sort_function);
...
}
However, it really should be a standalone function instead since it really has no relation to your TForm class at all:
// .cpp
static int sort_function(const void *a, const void *b)
{
return strcmp((const char *)a, (const char *)b);
}
void TForm::doSomething()
{
...
qsort(buffer, wordcount, sizeof(buffer[1]), sort_function);
...
}

store a lambda that captures this

Using C++ 17, I'm looking for a way to store a lambda that captures the this pointer, without using std::function<>. The reason to not using std::function<> is that I need the guaranty that no dynamic memory allocations are used. The purpose of this, is to be able to define some asynchronous program flow. Example:
class foo {
public:
void start() {
timer(1ms, [this](){
set_pin(1,2);
timer(1ms, [this](){
set_pin(2,1);
}
}
}
private:
template < class Timeout, class Callback >
void timer( Timeout to, Callback&& cb ) {
cb_ = cb;
// setup timer and call cb_ one timeout reached
...
}
??? cb_;
};
Edit: Maybe it's not really clear: std::function<void()> would do the job, but I need / like to have the guaranty, that no dynamic allocations happens as the project is in the embedded field. In practice std::function<void()> seems to not require dynamic memory allocation, if the lambda just captures this. I guess this is due to some small object optimizations, but I would like to not rely on that.
You can write your own function_lite to store the lambda, then you can use static_assert to check the size and alignment requirements are satisfied:
#include <cstddef>
#include <new>
#include <type_traits>
class function_lite {
static constexpr unsigned buffer_size = 16;
using trampoline_type = void (function_lite::*)() const;
trampoline_type trampoline;
trampoline_type cleanup;
alignas(std::max_align_t) char buffer[buffer_size];
template <typename T>
void trampoline_func() const {
auto const obj =
std::launder(static_cast<const T*>(static_cast<const void*>(buffer)));
(*obj)();
}
template <typename T>
void cleanup_func() const {
auto const obj =
std::launder(static_cast<const T*>(static_cast<const void*>(buffer)));
obj->~T();
}
public:
template <typename T>
function_lite(T t)
: trampoline(&function_lite::trampoline_func<T>),
cleanup(&function_lite::cleanup_func<T>) {
static_assert(sizeof(T) <= buffer_size);
static_assert(alignof(T) <= alignof(std::max_align_t));
new (static_cast<void*>(buffer)) T(t);
}
~function_lite() { (this->*cleanup)(); }
function_lite(function_lite const&) = delete;
function_lite& operator=(function_lite const&) = delete;
void operator()() const { (this->*trampoline)(); }
};
int main() {
int x = 0;
function_lite f([x] {});
}
Note: this is not copyable; to add copy or move semantics you will need to add new members like trampoline and cleanup which can properly copy the stored object.
There is no drop in replacement in the language or the standard library.
Every lambda is a unique type in the typesystem. Technically you may have a lambda as a member, but then its type is fixed. You may not assign other lambdas to it.
If you really want to have an owning function wrapper like std::function, you need to write your own. Actually you want a std::function with a big enough small-buffer-optimization buffer.
Another approach would be to omit the this capture and pass it to the function when doing the call. So you have a captureless lambda, which is convertible to a function pointer which you can easily store. I would take this route and adapter complexer ways if really nessessary.
it would look like this (i trimmed down the code a bit):
class foo
{
public:
void start()
{
timer(1, [](foo* instance)
{
instance->set_pin(1,2);
});
}
private:
template < class Timeout, class Callback >
void timer( Timeout to, Callback&& cb )
{
cb_ = cb;
cb_(this); // call the callback like this
}
void set_pin(int, int)
{
std::cout << "pin set\n";
}
void(*cb_)(foo*);
};

Why is it Segmentation fault every time?

This code gives error only in runtime and it's "Segmentation fault". How can this be tackled? I don't have any idea how to remove this error. Thanks in Advance!
#include <iostream>
#include <cstddef>
using namespace std;
class Node
{
private:
int data;
Node* nextNodeAddress;
public:
Node(): nextNodeAddress(NULL) {} // if next node is not used it must be null.
void setData(int); // this function sets data in the node
int retrieveData(); // this function retrieves the data from the node
};
void Node::setData(int data)
{ this->data=data; }
class List
{
private:
Node* headNode;
Node* currentNode;
int listSize;
public:
List();
void addNode(int);
void deleteNode(int);
};
List::List(): headNode(NULL),currentNode(NULL)
{
}
void List::addNode(int data)
{
Node* newNode = NULL;
newNode->setData(data);
newNode->setNextNode(NULL);
if(headNode==NULL)
headNode = newNode;
else
currentNode->setNextNode(newNode);
currentNode = newNode;
this->listSize++;
}
GCC with all warnings on throws this:
In member function ‘void Node::setData(int)’:
18:28: warning: declaration of ‘data’ shadows a member of 'this' [-Wshadow]
void Node::setData(int data)
Might be a good place to start checking.
Edit: The issue is discussed here, basically you're reusing the name data in both private int in the class definition and int data as the parameter for the method. How could it possibly decide which one is which when you do this->data = data?

How to store function as class member variable

Is it possible in Dart to store a callback function with return and argument type information? It appears I can do the following:
class MyClass {
void addCallback( callback( int ) )
{
_callback = callback;
}
var _callback;
}
But I thought it would be nice if _callback wasn't declared as var, and instead had information about its return and argument types. I couldn't find info on this in the docs, anyone know?
Dart 2 supports a function type syntax:
class MyClass {
void addCallback( callback( int ) )
{
_callback = callback;
}
void Function(int) _callback;
}
The Effective Dart Design Guide states that this form is preferred over typedefs.
You can typedef a Function signature like this:
typedef bool Filter(num x);
List<num> filterNumbers(List<num> numbers, Filter filter) {
return numbers.where(filter).toList();
}
For more great information like this, check out this article: https://www.dartlang.org/articles/idiomatic-dart/

pthread compile error

I am trying to create a thread using pthread. So far I have this:
sample.h:
void* ReceiveLoop(void*);
pthread_t mythread;
sample.cpp:
void* ReceiveLoop(void*) {
cout<<"whatever";
}
void sample::read() {
pthread_create(&mythread, NULL, ReceiveLoop, NULL);
}
Which I think is ok having read some posts about this. I have also tried with
pthread_create(&mythread, NULL, &ReceiveLoop, NULL);
But I get this:
.cpp:532: error: no matches converting function 'ReceiveLoop' to type 'void* (*)(void*)'
.cpp:234: error: void* sample::ReceiveLoop(void*)
Anyone can help me? Thanks.
I recall a few idiosyncrasies between older versions of gcc/g++ with regards to errors like this. You didn't indicate the compiler you were using.
Go ahead and give the void* parameter passed to ReceiveLoop a name:
void ReceiveLoop(void* threadarg);
void* ReceiveLoop(void* threadarg){ cout<<"whatever"; }
For some reason, I seem to recall that's the only way I could get a particular piece of code to compile on some random compiler even though the parameter passed in wasn't actually used.
Also, if ReceiveLoop is a member function of a class, it needs to be declared static.
class sample
{
public:
void ReceiveLoopImpl()
{
cout<<"whatever";
}
static void* ReceiveLoop(void* threadargs)
{
return ((sample*)threadargs)->RecieveLoopImpl();
}
void read()
{
pthread_create(&mythread, NULL, sample::ReceiveLoop, this);
}
};

Resources