Callback from python - callback

After reading a lot from this wonderful web, I need some help.
I have this function (in a dll):
kvStatus kvSetNotifyCallback ( const int hnd, kvCallback_t callback, void * context,
unsigned int notifyFlags);
How to call this function from Python?
I tried:
kvSetNotifyCallback(c_int(hnd1),c_void_p(self.can_rx()),None, c_int(canNOTIFY_RX))
def can_rx(self):
print("OK")
The function can_rx does execute only once. Any suggestions? Thank you very much.
MM

first thing:
The argtypes of ctypes WINFUCNTYPE or CFUNCTYPE should be a c_void_p
The argtypes of fucntion which you are defining should be py_object instead of a c_void_p
so that you can pass objects of structures and arrays as well.
then in the callback fucntion cast the void_p data as
ct.cast(userdata,ct.py_object).value
second thing:
code running only once: put a return value at bottom of the code.
return 1 or return TRUE
example:
CALLBACKFUNC = WINFUNCTYPE("returnvalue",c_int,c_void_p)
kvSetNotifyCallback.argtypes = [c_int,CALLBACKFUNC,py_object,c_uint]
then in the fucntion:
def can_rx(arg1,arg2):
arg3 = cast(arg2,py_object).value #yields object value
print arg1
print arg3
return 1 #for continuing execution
The CALLBACK FUNCTION can_rx should be called at CALLBACKFUNC(can_rx), the data to be passed along with arg1 should be passed at py_object position.
so you should call your callback as:
kvSetNotifyCallback(somevalue,CALLBACKFUC(can_rx),arg2,canNOTIFY_RX)
arg2 is the value to be passed to the callback func can_rx
can_rx can be defined as a global function also.

Related

Why is lambda expression used in DOTween?

I'm using a lambda expression in my C# script in my Unity project to call a function with a parameter when a DOTween callback is called.
It simply looks like this: animation.OnComplete(() => DestroyOnCompleted(children));
It works just fine, but I am note sure why a lambda expression is used in this case. I know it has something to do with delegates, but other than that, I'm not too sure; and I would like to explain it to my exam, if I get asked about it.
Could anyone enlighten me? :-)
Why not? ;)
I don't know that API too much but it seems like it is simply expecting something like
OnComplete(TweenCallback callback)
where TweenCallback from your usage basically seems to equal the c# built-in Action delegate and basically simply a parameter less void
public delegate void TweenCallback();
so whether you pass in this callback as a lambda like
animation.OnComplete(() => DestroyOnCompleted(children));
or anonymous method using the delegate operator like
animation.OnComplete(delegate { DestroyOnCompleted(children); });
or using a method
animation.OnComplete(OnCompletedAnimation);
...
private void OnCompletedAnimation()
{
DestroyOnCompleted(children);
}
is basically equivalent.
The main difference between the first two and the last one is: Where does children come from?
The lambda and delegate way allows you to pass in children from the current scope variables without having to store it in any field!
If you look at the documentation of DotTween, you see that row:
Now looking at the Source Code of DotTween, you can see the definition of TweenCallback:
public delegate void TweenCallback();
So the question now is, what is a delegate void in c#?
A delegate in c# is basically an object that "represent" a function.
But functions are not all the same, they can have parameters in input and return something (or return void).
To understand what kind of function does a delegate represent, try to just remove the keyword delegate.
For example, the TweenCallback without the keyboard delegate is:
public void TweenCaalback()
So the delegate represent a void function that has no parameters in input! (And it is Public).
What does it means represent a function?
It means that this is valid code:
void DoNothing()
{
}
TweenCallback x = DoNothing;
x();
So you can "assign functions" to a delegate that has the same function signature.
In this case, TweenCallback is a delegate void (), so you can assign to it a void() function.
What is a lambda?
A lambda is an expression of that style:
(string name, int age) => { return 3 };
you can read that as "string name and int age go in return 3"
That's a more concise way to describe that function:
int AnonymousFunction (string name, int age) {}
The main difference is that lambdas do not have any name. If you have not any parameter in input the lambda become like this:
() => {return 3;}
If you have only one statement inside the {} you are allowed to write it more shortly as
() => 3;
Final step
Is this valid code?
void DoNothing()
{
}
TweenCallback x = () => DoNothing();
Yes it is! Tween callback is expects a void () function.
() => DoNothing(); Is a lambda (un-named function) that takes nothing in input and calls some other function. It's the shorter version of () => {DoNothing();} that you have to think as void () {DoNothing();}
So when writing
animation.OnComplete(() => DestroyOnCompleted(children));
You are just passing a void () function to OnComplete Method, that makes sense because TweenCallback is a void () delegate.
Notes
As you can see, functions and lambdas expression can be converted implicitly to delegates. But you have to understand that they are all different things, and in more advanced coding scenarios that distinction is not just pure theory.

Flutter. Dart. Null-aware callback call? [duplicate]

In the same way we can have
nullableClassInstance?.method(blah)
Is there a way to do
nullableFunctionInstance?(blah)
In other words, is there an operator that checks whether a function instance is not null, if so, invoke the function all in one line?
Using the call method, you can achieve what you want with:
nullableFunctionInstance?.call(blah)
There's also the apply method if you want to pass arguments.
If you have a Function Object , you can use the call method and send all the parameters to that which works exactly as calling the function. Here , you can use the null aware member access operator.
void myFun(int a , int b){...}
var myVar = myFun ;
call
The function myVar will only get called if its not null as shown below.
myVar?.call( arg1 , arg2 );
apply
If your function is dynamic or you wish to control which function is being called at run time , you can use the apply static method of Function like so :
Function.apply(myVar , [arg1 , arg2]);
apply takes the function and a List of parameters that will be sent to the function.
Read more about call and apply :

Null item error when placing factory registration within a function

I'm trying to write a function that creates registers an item with the factory then does some basic operations to that item. The problem I'm having is that when I try to execute this code, I get a null item error.
An example excerpt of the code I'd like to have would be:
modified_sequence_item example_msg_item
function new (string name = ex_sequence);
super.new(name);
create_message(example_msg_item, "example_msg_item", 32'hDEADBEEF);
endfunction
function create_message(modified_sequence_item msg_item, string msg_name, bit[31:0] data);
msg_item = modified_sequence_item::type_id::create(msg_name);
msg_item.data_field = data;
endfunction
Unfortunately, this doesn't work. I get the following error:
UVM_FATAL # 5710: reporter [NullITM] attempting to start a null item from sequence 'main'
However, the following code does work:
modified_sequence_item example_msg_item
function new (string name = ex_sequence);
super.new(name);
example_msg_item = modified_sequence_item::type_id_create("example_msg_item");
example_msg_item.data_field = 32'hDEADBEEF;
endfunction
Looking at these two bits of code, to me they are nearly identical aside from the actions being nested inside a function in the first bit of code. This leads me to believe the issue is most likely an issue with passing data being the functions.
Does anyone have any recommendations on how I could modify the first code example so that it does not have a null item error?
Two problems with your function declaration:
The handle that you are creating inside your function needs to be copied out when exiting the function, so msg_item needs to be declared as an output argument.
You forgot to declare the return type as void. Otherwise the default is a 1-bit 4-state result (IEEE Std 1800-2017, section 13.4 Functions: implicit_data_type)
function void create_message(
output modified_sequence_item msg_item,
input string msg_name, bit[31:0] data);
msg_item = modified_sequence_item::type_id::create(msg_name);
msg_item.data_field = data;
endfunction

How can I specify the value of a named argument in boost.python?

i want to embed a function written in python into c++ code.
My python code is:test.py
def func(x=None, y=None, z=None):
print x,y,z
My c++ code is:
module = import("test");
namespace = module.attr("__dict__");
//then i want to know how to pass value 'y' only.
module.attr("func")("y=1") // is that right?
I'm not sure Boost.Python implements the ** dereference operator as claimed, but you can still use the Python C-API to execute the method you are intested on, as described here.
Here is a prototype of the solution:
//I'm starting from where you should change
boost::python::object callable = module.attr("func");
//Build your keyword argument dictionary using boost.python
boost::python::dict kw;
kw["x"] = 1;
kw["y"] = 3.14;
kw["z"] = "hello, world!";
//Note: This will return a **new** reference
PyObject* c_retval = PyObject_Call(callable.ptr(), NULL, kw.ptr());
//Converts a new (C) reference to a formal boost::python::object
boost::python::object retval(boost::python::handle<>(c_retval));
After you have converted the return value from PyObject_Call to a formal boost::python::object, you can either return it from your function or you can just forget it and the new reference returned by PyObject_Call will be auto-deleted.
For more information about wrapping PyObject* as boost::python::object, have a look at the Boost.Python tutorial. More precisely, at this link, end of the page.
a theoretical answer (no time to try myself :-| ):
boost::python::dict kw;
kw["y"]=1;
module.attr("func")(**kw);

Timer Thread with passed Function* and Param

I'm working on finishing up my server for my first iPhone application, and I want to implement a simple little feature.
I would like to run a function (perhaps method as well), if another function returns a certain value after a certain waiting period. Fairly simple concept.... right?
Here's my basic foundation.
template <typename T,class TYP>
struct funcpar{
T (*function)(TYP);
TYP parameter;
funcpar(T (*func)(TYP),TYP param);
funcpar& operator=(const funcpar& fp);
};
The goal here is to be able to call funcpar::function(funcpar::parameter) to run the stored function and parameter, and not have to worry about anything else...
When I attempted to use a void* parameter instead of the template, I couldn't copy the memory as an object (because I didn't know what the end object was going to be, or the beginning for that matter) and when I tried multiple timers, every single object's parameter would change to the new parameter passed to the new timer... With the previous struct I have a
question:
Is it possible to make an all-inclusive pointer to this type of object inside a method of a class? Can I templatize a method, and not the whole class? Would it work exactly like a function template?
I have a managing class that holds a vector of these "jobs" and takes care of everything fairly well. I just don't know how to use a templatized function with the struct, or how to utilize templates on a single method in a class..
I'm also utilizing this in my custom simple threadpool, and that's working fairly well, and has the same problems...
I have another question:
Can I possibly store a function with a parameter before it's run? Something like toRun = dontrunmeyet(withThisParameter);? Is my struct even necessary?
Am I going about this whole thing incorrectly?
If this is overly ambiguous, I can set you up with my whole code for context
In order to create a class method that takes a template parameter, yes, it would work almost exactly like a function template. For example:
class A
{
public:
template<typename T>
void my_function(const T& value) { }
};
int main()
{
A test;
test.my_function(5);
return 0;
}
Secondly, for your structure, you can actually turn that into a functor-object that by overloading operator(), lets you call the structure as-if it were a function rather than having to actually call the specific function pointer members inside the structure. For instance, your structure could be re-written to look like this:
#include <iostream>
template <class ReturnType, class ParameterType>
class funcpar
{
private:
ReturnType (*function)(ParameterType);
ParameterType parameter;
public:
funcpar(ReturnType (*func)(ParameterType),ParameterType param):
function(func), parameter(param) {}
funcpar& operator=(const funcpar& fp);
//operator() overloaded to be a function that takes no arguments
//and returns type ReturnType
ReturnType operator() ()
{
return function(parameter);
}
};
int sample_func(int value)
{
return value + 1;
}
int main()
{
funcpar<int, int> test_functor(sample_func, 5);
//you can call any instance of funcpar just like a normal function
std::cout << test_functor() << std::endl;
return 0;
}
BTW, you do need the functor object (or your structure, etc.) in order to bind a dynamic parameter to a function before the function is called in C/C++ ... you can't "store" a parameter with an actual function. Binding a parameter to a function is actually called a closure, and in C/C++, creating a closure requires a structure/class or some type of associated data-structure you can use to bind a function with a specific parameter stored in memory that is used only for a specific instance of that function call.