title: How to properly pass a callback-function from swift to c++?
body: <p>I am trying to pass a callback-function from swift-code to c++ code. I am using the current version of Xcode. It works for simple variables, but not for functions so far:</p>
  
  <p>cpp-class.cpp:</p>
  
  <pre><code>bool * swiftvar;
  
  void register_var(bool * varpntr){
      swiftvar = varpntr;
      cout&lt;&lt;"registered"&lt;&lt;endl;
  }
  
  void switch_var(){
      *swiftvar = !(*swiftvar);
      cout&lt;&lt;"switched"&lt;&lt;endl;
  }
  </code></pre>
  
  <p>cpp-class.hpp:</p>
  
  <pre><code>#ifdef __cplusplus
  extern "C"{
  #endif
  
      void register_var(bool *);
      void switch_var();
  
  #ifdef __cplusplus
  }
  #endif
  </code></pre>
  
  <p>and in swift:</p>
  
  <pre><code>register_var(&amp;testbool)
  print(testbool)
  switch_var()
  print(testbool)
  </code></pre>
  
  <p>If i try the same for functions (which should be that simple in the current swift version as far as I know), I get errors. So how do I have to pass the function pointer in swift? All methods I found were causing errors. As i read, the old way of defining an UnsafeMutablePointer object an so on became obsolete, but how does it work now? I expect something like:</p>
  
  <p>cpp-class.cpp:</p>
  
  <pre><code>void run_func(void * funcpntr()){
      (*funcpntr)();
  }
  </code></pre>
  
  <p>cpp-class.hpp:</p>
  
  <pre><code>void run_func(void *);
  </code></pre>
  
  <p>(swift-pseudo-code):</p>
  
  <pre><code>run_func(testfunc())
  </code></pre>
  
  <p>Or is there even a better solution to run swift-functions from wrapped cpp-code?</p>
  
  <p>Any help would be really appreciated. Thanks in advance</p>