1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_MAC_BIND_OBJC_BLOCK_H_
6 #define BASE_MAC_BIND_OBJC_BLOCK_H_
10 #include "base/bind.h"
11 #include "base/callback_forward.h"
12 #include "base/mac/scoped_block.h"
14 // BindBlock builds a callback from an Objective-C block. Example usages:
16 // Closure closure = BindBlock(^{DoSomething();});
18 // Callback<int(void)> callback = BindBlock(^{return 42;});
20 // Callback<void(const std::string&, const std::string&)> callback =
21 // BindBlock(^(const std::string& arg0, const std::string& arg1) {
29 // Helper functions to run the block contained in the parameter.
31 R
RunBlock(base::mac::ScopedBlock
<R(^)()> block
) {
32 R(^extracted_block
)() = block
.get();
33 return extracted_block();
36 template<typename R
, typename A1
>
37 R
RunBlock(base::mac::ScopedBlock
<R(^)(A1
)> block
, A1 a
) {
38 R(^extracted_block
)(A1
) = block
.get();
39 return extracted_block(a
);
42 template<typename R
, typename A1
, typename A2
>
43 R
RunBlock(base::mac::ScopedBlock
<R(^)(A1
, A2
)> block
, A1 a
, A2 b
) {
44 R(^extracted_block
)(A1
, A2
) = block
.get();
45 return extracted_block(a
, b
);
48 } // namespace internal
50 // Construct a callback with no argument from an objective-C block.
52 base::Callback
<R(void)> BindBlock(R(^block
)()) {
53 return base::Bind(&base::internal::RunBlock
<R
>,
54 base::mac::ScopedBlock
<R(^)()>(Block_copy(block
)));
57 // Construct a callback with one argument from an objective-C block.
58 template<typename R
, typename A1
>
59 base::Callback
<R(A1
)> BindBlock(R(^block
)(A1
)) {
60 return base::Bind(&base::internal::RunBlock
<R
, A1
>,
61 base::mac::ScopedBlock
<R(^)(A1
)>(Block_copy(block
)));
64 // Construct a callback with two arguments from an objective-C block.
65 template<typename R
, typename A1
, typename A2
>
66 base::Callback
<R(A1
, A2
)> BindBlock(R(^block
)(A1
, A2
)) {
67 return base::Bind(&base::internal::RunBlock
<R
, A1
, A2
>,
68 base::mac::ScopedBlock
<R(^)(A1
, A2
)>(Block_copy(block
)));
73 #endif // BASE_MAC_BIND_OBJC_BLOCK_H_