title: EXC_BAD_ACCESS exception when calling a Swift closure from C
body: <p>I'm trying to call a Swift closure from C. </p>
  
  <p>The following piece of code shall represent what I'm currently working on.</p>
  
  <p>First, in Swift, I initialize a static constant, the closure that is supposed to be called later.</p>
  
  <p>This closure is then passed to a C function (<code>api_set_callback_block</code>) that stores the block pointer.</p>
  
  <p>Some time after that, the C function <code>api_trigger_block</code> is called. This function should invoke the Swift closure. Instead of doing so, it always throws a runtime error: EXC_BAD_ACCESS when trying to access <code>cb_block_cb()</code> (also see below).</p>
  
  <p>Usually, this should mean that something tries to access a previously stored variable was deallocated. However, I don't get how that could be the case as I was passing a static constant.</p>
  
  <p>I double-checked that <code>cb_block_cb</code> is not NULL when accessing it.</p>
  
  <pre class="lang-c prettyprint-override"><code>void (^cb_block_cb)(int, int) = NULL;
  void api_set_callback_block(void (^cb_block)(int, int))
  {
      if (cb_block == NULL)
      {
          puts("error: when setting callback block: cb_block is null");
          return;
      }
      cb_block_cb = cb_block;
  }
  
  void api_trigger_block()
  {
      if (cb_block_cb == NULL)
      {
          puts("error: when triggering callback block: cb_block_cb is null");
          return;
      }
      cb_block_cb(3,3); // &lt;-- This is where the exception gets thrown
  }
  </code></pre>
  
  <pre class="lang-swift prettyprint-override"><code>class CustomClass: NSObject {
      public static let callback: (Int32, Int32) -&gt; Swift.Void = { (cid, aid) in
          print("Callback block called!")
      }
  }
  
  @UIApplicationMain
  class AppDelegate: UIResponder, UIApplicationDelegate {
  
      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {
          // Override point for customization after application launch.
  
          api_set_callback_block(CustomClass.callback)
  
          DispatchQueue.main.asyncAfter(deadline: .now() + 7) {
              api_trigger_block()
          }
          return true
      }
  
      // ...
  }
  </code></pre>