Call Swift From Python

There's plenty of documentation around for leveraging PythonKit for invoking python from Swift. Is there a reliable way to do the reverse? What if I want to call swift code from a flask server for example?

Swift has no FFI, so I'd imagine the way to go would be to write a C API wrapper for your Swift code and bundle that up in a Python extension (which is quite nice IIRC).

I assume that the question is about Linux, but if not, you might also get away with PyObjC, and instead of doing a low level C wrap, annotate the Swift APIs you want to export using @objc (and access them as ObjC objects on the Python side).

Not sure whether any more convenient projects came out of the Python integration stuff for Tensorflow?

1 Like

You could use @_cdecl, which is not officially supported, but seems to be used in various places, and then use some of the many Python facilities made for calling C code.

1 Like

Yeah this is what I figured would be the best approach. Maybe I should reword my question to, when will @_cdcl be officially supported / if that is the plan at all?

just found this and figured I'd drop it here

1 Like

Try using Python functions that were recently added to PythonKit.

1 Like

Oh wow I just looked it up, this is awesome! PythonKit/Python.swift at master · pvieito/PythonKit · GitHub Do you have any running examples you suggest to follow?

Actually I think I saw the examples I needed here, you're a beast @philipturner !

I am working on exposing Swift APIs to C-family languages starting with C++ as part of the Swift and C++ interoperability project. We plan on generating the C interfaces for all of the exposed underlying Swift APIs in the generated header. That is going to allow C users to invoke Swift functions and operate with Swift types directly from C (although that would require some amount of C boilerplate most likely). I can imagine that this could be useful for Python interoperability as well.

1 Like

Thats amazing. Not sure if you've seen @ericsink efforts with Alpaca Preview: Native Swift with ASP.NET Core over on dotnet land but it sounds similar

1 Like

@hggz there's one more example that you might also want to check out. It uses the subclassing feature that was recently added to PythonKit. I don't think enough people realize, but it's a game-changer for Python interop.

1 Like