pthread compile error - pthreads

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);
}
};

Related

Mql4 undeclared identifier for delete object

I am using the code from the example here Keep order details in arrays?
I am getting an error of listOfTrades - undeclared identifier when I add the code in the
void OnDeinit(const int reason)
{
//--- destroy timer
EventKillTimer();
delete(listOfTrades);
}
I have a feeling it is because listOfTrades is declared in the OnInit() and not outside global but not sure how that would affect it.
Main.mql
#include <CTrade.mqh>
int OnInit()
{
CArrayObj *listOfTrades=new CArrayObj;
}
void OnDeinit(const int reason)
{
//--- destroy timer
EventKillTimer();
delete(listOfTrades);
}
Yes, you have to declare that globally, before calling OnInit(). Missed that point in the mentioned question, will update.
If you pass the object by pointer somehow void OnTick(){ doSomeFunction(listOfTrades); } then you should make sure the same variable name is not used (at least in the same file), otherwise you will have warnings that some day may become a bug.
void doSomeFunction(CArrayObj* _listOfTrades)// not "listOfTrades" !!!
{
for(int i=_listOfTrades.Total()-1;i>=0;i--)
{
CTrade* trade=_listOfTrades.At(i);
// action with CTrade object
}
}

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*);
};

UnitySendMessage doesn't work on iOS

I was trying to send some data using UnitySendMessage in iOS plugin, but it seem like it doesn't do anything, i don't see any errors and response. I checked function where UnitySendMessage is located, and i'm 100% sure that it starts.
- (void) callback{
NSLog(#"UNITY test callback");
UnitySendMessage("PluginTest", "listener", "test callback");
}
On scene i have gameObject named PluginTest with pluginListener component which contains method:
public void listener(string parameter)
{
print(parameter);
}
I also added to UnityAppController.mm this line, which was recommended to add in some post:
extern void UnitySendMessage(const char *, const char *, const char *);
I have no idea what i'm doing wrong, unitySendMessage seems like it should work without much effort.
Any help will be appreciated

creating checkbox/button in 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();
}

Creating function with variable number of arguments or parameters in Dart

I am looking for a way to create a function with a variable number of arguments or parameters in Dart. I know I could create an array parameter instead, but I would prefer to not do that because I'm working on a library where syntactic brevity is important.
For example, in plain JavaScript, we could do something like this (borrowed from here):
function superHeroes() {
for (var i = 0; i < arguments.length; i++) {
console.log("There's no stopping " + arguments[i]);
}
}
superHeroes('UberMan', 'Exceptional Woman', 'The Hunk');
However, in dart, that code will not run. Is there a way to do the same thing in dart? If not, is this something that is on the roadmap?
You can't do that for now.
I don't really know if varargs will come back - they were there some times ago but have been removed.
However it is possible to emulate varargs with Emulating functions. See the below code snippet.
typedef OnCall = dynamic Function(List arguments);
class VarargsFunction {
VarargsFunction(this._onCall);
final OnCall _onCall;
noSuchMethod(Invocation invocation) {
if (!invocation.isMethod || invocation.namedArguments.isNotEmpty)
super.noSuchMethod(invocation);
final arguments = invocation.positionalArguments;
return _onCall(arguments);
}
}
main() {
final superHeroes = VarargsFunction((arguments) {
for (final superHero in arguments) {
print("There's no stopping ${superHero}");
}
}) as dynamic;
superHeroes('UberMan', 'Exceptional Woman', 'The Hunk');
}
Dart does indirectly support var-args as long as you aren't too much into syntactic brevity.
void testFunction([List<dynamic> args=[]])
{
for(dynamic arg:args)
{
// Handle each arg...
}
}
testFunction([0, 1, 2, 3, 4, 5, 6]);
testFunction();
testFunction([0, 1, 2]);
Note: You can do the same thing with named parameters, but you'll have to handle things internally, just in case if the user (of that function; which could be you) decides to not pass any value to that named parameter.
I would like to thank #Ladicek for indirectly letting me know that a word like brevity exists in English.
This version:
Works with both positional and keyword arguments.
Supports typing of the return value.
Works with modern Dart.
typedef VarArgsCallback = void Function(List<dynamic> args, Map<String, dynamic> kwargs);
class VarArgsFunction {
final VarArgsCallback callback;
static var _offset = 'Symbol("'.length;
VarArgsFunction(this.callback);
void call() => callback([], {});
#override
dynamic noSuchMethod(Invocation inv) {
return callback(
inv.positionalArguments,
inv.namedArguments.map(
(_k, v) {
var k = _k.toString();
return MapEntry(k.substring(_offset, k.length - 2), v);
},
),
);
}
}
void main() {
dynamic myFunc = VarArgsFunction((args, kwargs) {
print('Got args: $args, kwargs: $kwargs');
});
myFunc(1, 2, x: true, y: false); // Got args: [1, 2], kwargs: {x: true, y: false}
}
Thanks, Alexandre for your answer!
I played around a little with Alexandre Ardhuin's answer and found that we can tweak a couple of things to make this work in the current version of Dart:
class VarArgsClass {
noSuchMethod(InvocationMirror invocation) {
if (invocation.memberName == 'superheroes') {
this.superheroes(invocation.positionalArguments);
}
}
void superheroes(List<String> heroNames) {
for (final superHero in heroNames) {
print("There's no stopping ${superHero}!");
}
}
}
main() {
new VarArgsClass().superheroes('UberMan', 'Exceptional Woman', 'The Hunk');
}
This has lots of problems, including:
A warning is generated wherever you call superheroes() because the signature doesn't match your parameters.
More manual checking would need to be done to make sure the list of arguments passed to superheroes is really a List<String>.
Needing to check the member name in noSuchMethod() makes it more likely you'll forget to change the 'superheroes' string if you change the method name.
Reflection makes the code path harder to trace.
BUT if you are fine with all of those issues, then this gets the job done.
If you are really into syntactic brevity, just declare a function/method with say 10 optional positional parameters and be done. It's unlikely someone will call that with more than 10 arguments.
If it sounds like a hack, that's because it is a hack. But I've seen the Dart team doing the same :-)
For example:
void someMethod(arg0, [arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9]) {
final args = [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9];
args.removeWhere((value) => value == null);
/* do something the the args List */
print(args);
}
For the example you've written, I think you're best off using a list. Sorry about that!
I'm looking at dartbug.com, but I don't see a feature request for this. You're definitely welcome to create one!

Resources