[swift-dev] C Macros and Variadic functions

Joe Groff jgroff at apple.com
Wed Jan 6 13:18:34 CST 2016


> On Jan 5, 2016, at 1:57 PM, Kate Stone via swift-dev <swift-dev at swift.org> wrote:
> 
>> On Jan 5, 2016, at 12:32 PM, Ryan Lovelett via swift-dev <swift-dev at swift.org <mailto:swift-dev at swift.org>> wrote:
>> 
>> Just to be clear though the intent of my question was not to quibble
>> with compiler error messages. My real question is how are we meant to do
>> systems programming with Swift on Linux if we cannot call ioctl?
> 
> In the absence of an automatic mechanism for importing the definition of variadic functions you can still define your own prototypes and bind them to the system implementation.  For example, this declaration:
> 
> @_silgen_name("ioctl") func ioctl(fildes: CInt, request: UInt64, result: UnsafePointer<Int>) -> Int
> 
> … gives you a non-variadic interface to ioctl that you can use for invocations that conform to this specific convention.  You can define as many overloads as you wish, and so long as you’re cautious about which one you’re using for a given request you should be able to make progress.
> 
> The same basic strategy can be applied to any variadic functional interfaces.  Ideally you’d want to hide this implementation detail behind a more Swift-friendly API where the request type is implied to create a more type-safe interface.

Don't do this. User code never has any business using underscored attributes. @_silgen_name produces an external reference to a Swift function, with Swift's calling convention.  It cannot be safely used to refer to C functions, especially not variadic ones, since the convention for variadics in C is also different from non-variadic C functions. For variadic functions, you should write non-variadic wrappers in C (which can be static inline, to avoid wrapping overhead in production builds) and import them as Clang modules. See how open and fcntl are exported by the Darwin and Glibc overlays for an example.

-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20160106/994e4e0d/attachment.html>


More information about the swift-dev mailing list