bazelbuild / rules_swift

Bazel rules to build Swift on Apple and Linux platforms
Apache License 2.0
309 stars 133 forks source link

Add example of Swift <--> C++ interop #1198

Closed jiawen closed 2 months ago

jiawen commented 4 months ago

In the last year, Swift has gradually gained the ability to interop with C++. rules_swift should add a minimal example on how that would work. It would provide at baseline a means by which we can easily reproduce issues (module naming, static and dynamic linking, ODR violations, etc) as they are discovered.

gkoreman commented 3 months ago

Yes please!

I just tried this out and was pleasantly surprised at how easy it was. Here are some quick notes based on my experience in case anyone else sees this before the examples come out.

BUILD

swift_library(
    name = "mySwiftLib",
    srcs = [ "lib.swift" ], #note - if you make this main.swift then it will have an extra _main symbol which conficts with your app
    generates_header = True,
    copts = ["-cxx-interoperability-mode=default"], #needed to export c++ bindings
)

cc_binary(
...
    deps = [":mySwiftLib"]
)

SWIFT lib.swift

public func printWelcomeMessage(_ name: String) {
  print("Welcome \(name)")
}

C++

#include "full/path/to/module/mySwiftLib-Swift.h"

int main(int, char**)
{
    // Namespace appears to be the full path to the module
    full_path_to_module::printWelcomeMessage("friend");
    return 0;
}
davidzchen commented 3 months ago

It would be great to have an example of the other way around: calling C++ code from Swift. This will make it easier for developers to utilize C++ libraries in Swift code.

kersson commented 2 months ago

Just put up a PR to add a basic example to show how to invoke C++ code from Swift: https://github.com/bazelbuild/rules_swift/pull/1280