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();});
17 // Callback<int(void)> callback = BindBlock(^{return 42;});
23 // Helper functions to run the block contained in the parameter.
25 R
RunBlock(base::mac::ScopedBlock
<R(^)()> block
) {
26 R(^extracted_block
)() = block
.get();
27 return extracted_block();
30 template<typename R
, typename A1
>
31 R
RunBlock(base::mac::ScopedBlock
<R(^)(A1
)> block
, A1 a
) {
32 R(^extracted_block
)(A1
) = block
.get();
33 return extracted_block(a
);
36 } // namespace internal
38 // Construct a callback with no argument from an objective-C block.
40 base::Callback
<R(void)> BindBlock(R(^block
)()) {
41 return base::Bind(&base::internal::RunBlock
<R
>,
42 base::mac::ScopedBlock
<R(^)()>(Block_copy(block
)));
45 // Construct a callback with one argument from an objective-C block.
46 template<typename R
, typename A1
>
47 base::Callback
<R(A1
)> BindBlock(R(^block
)(A1
)) {
48 return base::Bind(&base::internal::RunBlock
<R
, A1
>,
49 base::mac::ScopedBlock
<R(^)(A1
)>(Block_copy(block
)));
54 #endif // BASE_MAC_BIND_OBJC_BLOCK_H_