Skip to content

Instantly share code, notes, and snippets.

@rikner
Last active July 20, 2018 12:00
Show Gist options
  • Save rikner/2f2677c56d1adef277d03bdb322eca80 to your computer and use it in GitHub Desktop.
Save rikner/2f2677c56d1adef277d03bdb322eca80 to your computer and use it in GitHub Desktop.
Python Swift Interoperability using ctypes
private var callback: ((Int)->Void)? = nil
private let number: Int = 123
@_silgen_name("set_callback")
public func setCallback(pointerToCTypesFunction: UnsafeMutablePointer<(Int)->Void>) {
print("swift: setting callback")
callback = pointerToCTypesFunction.pointee
}
@_silgen_name("execute_callback")
public func executeCallback() {
if let callback = callback {
print("swift: executing callback with number ", number)
callback(number)
} else {
print("swift: no callback was set")
}
}
from ctypes import *
native_lib = CDLL('./libCallbackTest')
@CFUNCTYPE(None, POINTER(c_int))
def callback(number):
print('python: the number is ', number[0])
native_lib.set_callback(byref(callback))
native_lib.execute_callback()

Python Swift Interoperability using ctypes

A demo on how to call swift code from python and call back python code from swift.

Run on macOS or Linux

  • Put both files into the same directory
  • run swiftc -emit-library -o ./libCallbackTest callbackTest.swift to build a shared library from swift code
  • run python native_callback_test.py to execute the python script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment