MeV
MeV

Reputation: 3968

Swift - how to use malloc?

I'm trying to translate an Objective-C app into Swift and I don't know how to implement a malloc.

Is it possible to use it in Swift?

Thank you

Upvotes: 3

Views: 6742

Answers (1)

greymouser
greymouser

Reputation: 3181

You need to implement a bridging header when you use ObjC or C from Swift. The functions exported by your bridging header are then available in your Swift app/module. See here, for the overview.

If you just need to "call some code" on the C-side, then the functions exported from C are basically just wrappers for Swift. However, if you need to interact with the data returned from those functions -- especially if malloc'd and not a simple primitive -- Swift has a number of C related types ready for your use (see here for specifics).

Furthermore, if you're trying to wrap or interact with C++ code, you can't directly do so from Swift. You have to setup an initial interface with ObjC or C for the C++ code, and then bridge that to Swift. Not really fun at all, but thankfully it's not as common a use case as bridging ObjC (primarily) or C.

... and for what it's worth, unless you need low level Core Audio for some reason (granted, like porting an app you already have), AVAudioEngine (iOS8+) is so much simpler for any applicable use case than Core Audio, and is readily available in Swift.

Upvotes: 1

Related Questions