Friday, March 2, 2018

C String Functions in Swift: a malloc’y Story

Helge Heß (tweet):

The pointer you get back points into a buffer, which doesn’t exist anymore. That is why you need to be super careful when accessing C APIs.

[…]

Why does this [Objective-C] rarely result in an allocation? In the case above the NSString is an NSConstantString which is already backed by an UTF-8 string, and as mentioned above, a lot of NSString’s are backed by UTF-8.

[…]

I was incorrectly assuming that Swift would create the static String in a way that is backed by an UTF-8 buffer, including the terminating 0 (because that byte is negligable). And more importantly, that the compiler would directly pass over the pointer to that cString buffer. […] When using C API with Swift Strings (be it a simple puts or maybe libxml2), be aware that such calls are really expensive (a malloc+free per call).

Comments RSS · Twitter

Leave a Comment