实现回调三步走:
1,我这个函数需要传入一个回调,我调用这个回调用run。这个是模板抽象。
void MyFunction1(base::OnceCallback<int(int32, double)> my_callback) { // OnceCallback int result1 = std::move(my_callback).Run(10, 1.0); // After running a OnceCallback, it's consumed and nulled out. DCHECK(!my_callback) ... }
2,这是个回调函数:
void MyFunction(int32 a, double b){ xxxx }
MyFunction通过bind后变成一个回调函数声明。my_callback1就可以传入1,作为实体参数。
base::OnceCallback<void(double)> my_callback1 = base::BindOnce(&MyFunction, 10); //这个10相当于第一个参数是10,第二个参数run时再指定:如std::move(my_callback1).Run(3.5);
3, 调用
MyFunction1(my_callback1)
ok
C++ in Chromium 101 - Codelab
This tutorial will guide you through the creation of various example C++ applications, highlighting important Chromium C++ concepts. This tutorial assumes robust knowledge of C++ (the language) but does not assume you know how to write an application specific to Chromium's style and architecture. This tutorial does assume that you know how to check files out of Chromium's repository.
As always, consider the following resources as of primary importance:
This tutorial does not assume you have read any of the above, though you should feel free to peruse them when necessary. This tutorial will cover information across all of those guides. Exercise 0: "Hello World!"This exercise demonstrates the use of the ninja build system to build a simple C++ binary and demonstrates how typical C++ builds are organized within Chromium. Create a new target in Sample execution: $ cd /path/to/chromium/src $ gclient runhooks
$ ninja -C out/Default hello_world $ out/Default/hello_world Hello, world! AMI: might be confusing how rietveld shows the new file as a copy/diff against an unrelated file.
AMI: output doesn't actually match what's in the solution. Might be confusing.
Part 1: Using command-line argumentsWe will augment our int main(int argc, char** argv) { CommandLine::Init(argc, argv); // Main program execution ... return 0; } Flags are not explicitly defined in Chromium. Instead, we use GetSwitchValueAsASCII() and friends to retrieve values passed in.Important include files#include "base/command_line.h" Exercise 1: Using command-line argumentsChange Part 2: Callbacks and BindC++, unlike other languages such as Python, Javascript, or Lisp, has only rudimentary support for callbacks and no support for partial application. However, Chromium has the AMI: last sentence might benefit from a pointer to refcounting (without which it might be less clear how binding works with copying of bound closures). The // The type of a callback that: // - Can run only once. / / - Is move-only and non-copyable./ / - Takes no arguments and does not return anything.// base::OnceClosure is an alias of this type. base::OnceCallback<void()>
// The types of a callback that takes two arguments (a string and a double) // and returns an int. base::OnceCallback<int(std::string, double)> base::RepeatingCallback<int(std::string, double)> Callbacks are executed by invoking the void MyFunction1(base::OnceCallback<int(std::string, double)> my_callback) { // OnceCallback
... }
int result1 = my_callback.Run("my string 1", 1.0);
// Run() can be called as many times as you wish for RepeatingCallback. int result2 = my_callback.Run("my string 2", 2); ... } Callbacks are constructed using the // Declare a function. void MyFunction(int32 a, double b); base::OnceCallback<void(double)> my_callback1 = base::BindOnce(&MyFunction, 10); base::RepeatingCallback<void(double)> my_callback2 = base::BindRepeating(&MyFunction, 10); // Equivalent to: // // MyFunction(10, 3.5); // std::move(my_callback1).Run(3.5); my_callback2.Run(3.5);
Important Include FilesExercise 2: Fibonacci closuresImplement a function that returns a callback that takes no arguments and returns successive Fibonacci numbers. That is, a function that can be used like this: base::RepeatingCallback<int()> fibonacci_closure = MakeFibonacciClosure(); printf("%d
", fibonacci_closure.Run()); // Prints "1" printf("%d
", fibonacci_closure.Run()); // Prints "1" printf("%d
", fibonacci_closure.Run()); // Prints "2" ... Each returned Fibonacci callback should be independent; running one callback shouldn't affect the result of running another callback. Write a fibonacci executable that takes an integer argument n and uses your function to print out the first n Fibonacci numbers.(This exercise was inspired by this Go exercise: Function closures.) Exercise solution Part 3: Message loopsChromium's abstraction for event loops is
base::MessageLoop . base::MessageLoop handles running tasks (which are instances of base::Closure ) on the current thread. Given a pointer to the message loop for a thread, you can post tasks on it with base::MessageLoop::PostTask (or base::MessageLoop::PostDelayedTask if you want to add a delay).Normally you wouldn't have to worry about setting up a
base::MessageLoop and keeping it running, since that is automatically done by Chromium's thread classes. However, since the main thread doesn't automatically start off with a base::MessageLoop , you have to create, pump, and shutdown one yourself if you're writing a new executable. The base::RunLoop class is the current recommended way of doing that.#include "base/message_loop/message_loop.h" Exercise 3: SleepImplement the Unix command-line utility Part 4: Threads and task runnersChromium's platform-independent abstraction for threads is Chromium's abstraction for asynchronously running posted tasks is An important member function of Important header files#include "base/task_runner.h" More informationExercise 4: Integer factorizationTake the given (slow) function to find a non-trivial factor of a given integer: bool FindNonTrivialFactor(int n, int* factor) { // Really naive algorithm. for (int i = n-1; i >= 2; --i) { if (n % i == 0) { *factor = i; return true; } } return false; }Write a command-line utility Callback<> and Bind()[TOC] IntroductionThe templated Partial application is the process of binding a subset of a function's arguments to produce another function that takes fewer arguments. This can be used to pass around a unit of delayed execution, much like lexical closures are used in other languages. For example, it is used in Chromium code to schedule tasks on different MessageLoops. A callback with no unbound input parameters ( OnceCallback<> And RepeatingCallback<>
The legacy
Memory Management And PassingPass
When you pass a Quick reference for basic stuffBinding A Bare Function
Binding A Captureless Lambda
Binding A Capturing Lambda (In Tests)When writing tests, it is often useful to capture arguments that need to be modified in a callback.
Binding A Class MethodThe first argument to bind is the member function to call, the second is the object on which to call it.
By default the object must support RefCounted or you will get a compiler error. If you're passing between threads, be sure it's RefCountedThreadSafe! See "Advanced binding of member functions" below if you don't want to use reference counting. Running A CallbackCallbacks can be run with their
RepeatingCallbacks can be run more than once (they don't get deleted or marked when run). However, this precludes using
If running a callback could result in its own destruction (e.g., if the callback recipient deletes the object the callback is a member of), the callback should be moved before it can be safely invoked. (Note that this is only an issue for RepeatingCallbacks, because a OnceCallback always has to be moved for execution.)
Creating a Callback That Does NothingSometimes you need a callback that does nothing when run (e.g. test code that doesn't care to be notified about certain types of events). It may be tempting to pass a default-constructed callback of the right type:
Default-constructed callbacks are null, and thus cannot be Run(). Instead, use
Implementation-wise,
Passing Unbound Input ParametersUnbound parameters are specified at the time a callback is
Passing Bound Input ParametersBound parameters are specified when you create the callback as arguments to
A callback with no unbound input parameters (
When calling member functions, bound parameters just go after the object pointer.
Partial Binding Of ParametersYou can specify some parameters when you create the callback, and specify the rest when you execute the callback. When calling a function bound parameters are first, followed by unbound parameters.
This technique is known as partial application. It should be used in lieu of creating an adapter class that holds the bound arguments. Notice also that the Avoiding Copies With Callback ParametersA parameter of
Arguments bound with In contrast, arguments bound with DANGER: A Avoid using
Quick reference for advanced bindingBinding A Class Method With Weak PointersIf
The callback will not be run if the object has already been destroyed. Note that class method callbacks bound to To use
If Binding A Class Method With Manual Lifetime Management
This disables all lifetime management on the object. You're responsible for making sure the object is alive at the time of the call. You break it, you own it! Binding A Class Method And Having The Callback Own The Class
The object will be deleted when the callback is destroyed, even if it's not run (like if you post a task during shutdown). Potentially useful for "fire and forget" cases. Smart pointers (e.g.
Ignoring Return ValuesSometimes you want to call a function that returns a value in a callback that doesn't expect a return value.
Quick reference for binding parameters to Bind()Bound parameters are specified as arguments to Passing Parameters Owned By The Callback
The parameter will be deleted when the callback is destroyed, even if it's not run (like if you post a task during shutdown). Passing Parameters As A unique_ptr
Ownership of the parameter will be with the callback until the callback is run, and then ownership is passed to the callback function. This means the callback can only be run once. If the callback is never run, it will delete the object when it's destroyed. Passing Parameters As A scoped_refptr
This should "just work." The closure will take a reference as long as it is alive, and another reference will be taken for the called function.
Passing Parameters By ReferenceReferences are copied unless
Normally parameters are copied in the closure. DANGER: Implementation notesWhere Is This Design From:The design of Customizing the behaviorThere are several injection points that controls binding behavior from outside of its implementation.
If
How The Implementation Works:There are three main components to the system:
The Callback classes represent a generic function pointer. Internally, it stores a refcounted piece of state that represents the target function and all its bound parameters. The
To
The By default To change this behavior, we introduce a set of argument wrappers (e.g., These types are passed to the
Missing Functionality
If you are thinking of forward declaring Partial applicationIn computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity. Given a function {displaystyle fcolon (X imes Y imes Z) o N}, we might fix (or 'bind') the first argument, producing a function of type {displaystyle { ext{partial}}(f)colon (Y imes Z) o N}. Evaluation of this function might be represented as {displaystyle f_{partial}(2,3)}. Note that the result of partial function application in this case is a function that takes two arguments. Partial application is sometimes incorrectly called currying, which is a related, but distinct concept. ContentsMotivation[edit]Intuitively, partial function application says "if you fix the first arguments of the function, you get a function of the remaining arguments". For example, if function div(x,y) = x/y, then div with the parameter x fixed at 1 is another function: div1(y) = div(1,y) = 1/y. This is the same as the function inv that returns the multiplicative inverse of its argument, defined by inv(y) = 1/y. The practical motivation for partial application is that very often the functions obtained by supplying some but not all of the arguments to a function are useful; for example, many languages have a function or operator similar to Implementations[edit]In languages such as ML, Haskell and F#, functions are defined in curried form by default. Supplying fewer than the total number of arguments is referred to as partial application. In languages with first-class functions one can define Scala implements optional partial application with placeholder, e.g. Clojure implements partial application using the The C++ standard library provides int f(int a, int b);
auto f_partial = [](int a) { return f(a, 123); };
assert(f_partial(456) == f(456, 123) );
In Java, In Raku, the The Python standard library module In XQuery, an argument placeholder ( Definitions[edit]In the simply-typed lambda calculus with function and product types (λ→,×) partial application, currying and uncurrying can be defined as:
Note that |