Call swift functions out of plain C code.

Hello,


I'm investigating the possiblility to use swift and Metal, to create a simulator of a embedded device.


I searched the net, and I found a lot of information about calling plain C functions in some swift code. But I haven't found any information about the inverse way. How to access a swift function in plain C code.

With Objective-C, I just created a C compatible header file, and used an objective-C body to do the work.


Does anybody know how I can access a swift function instead.


PS. The main source code used, is written in plain C, not C++ or objective-C. Because it also needs to run on a custom device. The purpose of my question is that I want swift to initialize the metal framework, creating shaders and supply a simulator interface.


Thanks,


Peter

This is a sample code from Using Swift with Cocoa and Objective-C (Swift 2 Prerelease version available in iBooks store)

func customCopyDescription(p: UnsafePointer<Void>) -> Unmanaged<CFString>! {
    // return an Unmanaged<CFString>! value
}

let callbacks = CFArrayCallBacks(
    version: 0 as CFIndex,
    retain: nil,
    release: nil,
    copyDescription: customCopyDescription,
    equal: { (p1, p2) -> Boolean in
        // return Boolean value
    }
)

var mutableArray = CFArrayCreateMutable(nil, 0, callbacks)

It seems like it is enough to define a closure or a function and it will be accessible to the C-caller (such as CF API). And although I haven't tried it yet, it looks fairly straight forward. The chapter is called "Interacting with C API", Function Pointes

Also you might want to read this http://www.russbishop.net/on-being-a-monster (pre-swift2)

You get access to any thing within classes or protocols marked with @objc that's compatible with Objective-C. This excludes top-level functions.


Workaround:


@objc public class SwiftHelper {
    public static func helloWorld() {
        print("Hello World")
    }
}

and


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        [SwiftHelper helloWorld];
    }
    return 0;
}
Call swift functions out of plain C code.
 
 
Q