# Best way to call a Swift function from C?

**URL:** <https://forums.swift.org/t/best-way-to-call-a-swift-function-from-c/9829>\
**Category:** Using Swift\
**Tags:** ffi\
**Created:** [February 12, 2018, 5:15pm UTC](https://forums.swift.org/t/best-way-to-call-a-swift-function-from-c/9829 "2018-02-12T17:15:22Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Joe\_Groff](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joe_groff/32/1929_2.png) [@Joe\_Groff](https://forums.swift.org/u/Joe_Groff)\
**Post date:** [February 12, 2018, 5:41pm UTC](https://forums.swift.org/t/best-way-to-call-a-swift-function-from-c/9829/2 "2018-02-12T17:41:22Z")

</div>

There's no official way yet. Aside from name mangling, Swift functions use a different calling convention from C. Unofficially, if you're willing to deal with more than the usual amount of code breakage and compiler bugs, there's an unofficial attribute `@_cdecl` that does this:

```swift
@_cdecl("mymodule_foo")
func foo(x: Int) -> Int {
  return x * 2
}

```

which you can then call from C:

```swift
#include <stdint.h>

intptr_t mymodule_foo(intptr_t);

intptr_t invoke_foo(intptr_t x) {
  return mymodule_foo(x);
}

```

---

_[View the full topic](https://forums.swift.org/t/best-way-to-call-a-swift-function-from-c/9829)._
