C++ calling swift function

I am working on swift program to access C++ library which will need a callback function to send data back to caller asynchronizely.

On my project, I used the bridging-Header.h to access C++ files, wrap.h and wrap.cpp

In the wrap.h,

I declared a callback function

typedef void (*callbackfunctionS)();

In the wrap.cpp,

bool RegisterCallBack(callbackfunctionS ptrfn)

{

(*ptrfn)();

return false;

}


In the main.swift,

func DataCallback()->Void {

println("DataCalback called")

}

let p = UnsafeMutablePointer<()->Void>.alloc(1) // allocate memory for function

p.initialize(PenDataS) /initialize with value

let cp = COpaquePointer(p) //convert UnsafeMutablePointer to COpaquePointer

let fp = CFunctionPointer<()->Void>(cp) //convert COpaquePointer to CFunctionPointer

RegisterCallBack(fp) //Error EXC_BAD_ACCESS(code =2, address = 0x10052fa80)


I don't know how to make the C++ calling Swift function to work, Can anyone to help?

I am using Swift 2.0 on Xcode 6, new to Mac world

I am using Swift 2.0 on Xcode 6

Are you using Swift 1.2 on Xcode 6? (Xcode 6.x does not support Swift 2.) Then no way. You cannot convert Swift function to C-function pointer. Add an Objective-C(++) file to bridge between Swift and C++.


If you are using Swift 2 on Xcode7, global functions can be automatically converted to C-function pointers, just write it as:

RegisterCallBack(DataCallback)

I remember one thing which should be noted.

In Swift 1.x and 2, functions can be automatically converted into blocks(in Swift terms, closures).

Change the RegisterCallBack's argument form C-function pointer type to block type, if you can.

after upgrade to xcode 7 beta, the c++ to swift callback works.

Thanks for your help

C&#43;&#43; calling swift function
 
 
Q