Skip to content

Instantly share code, notes, and snippets.

@jim-ec
Last active June 21, 2023 10:38
Show Gist options
  • Save jim-ec/75e048e50d929a609fbcfa1ff2bca25f to your computer and use it in GitHub Desktop.
Save jim-ec/75e048e50d929a609fbcfa1ff2bca25f to your computer and use it in GitHub Desktop.
Calling Swift from C++

Calling Swift from C++

foo.swift

@_cdecl("foo")
public func foo(x: Int) -> Int {
    x * x
}

The @_cdecl will disable name mangling and enforces cdecl-calling convention.

main.cpp

#include <iostream>

extern "C" int foo(int);

int main()
{
    int x = foo(8);
    std::cout << x << std::endl;
}

Build commands

swiftc -emit-library foo.swift
clang++ -o main main.cpp libfoo.dylib

Links:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment