Pass C ++ char * to Swift

To do

Returns char * in C and treats it as a String in swift

scene

Now that I've created HelloFrameWork (Cocoa Touch Framework), I want to use the methods in it from swift.

C language

hello.h should be a public header in Xcode

hello.h


#ifndef HELLO_H
#define HELLO_H

char* getHello();

#endif

hello.c


char* getHello() {
    return strdup("Hello");
}

swift

let hello_char = getHello()
let hello: String = String(cString: hello_char)
//Memory release
free(hello_char)

reference

Official Documentation Using Swift with cocoa and Object-C

Postscript

Using strdup () doesn't seem to be beautiful either. To write better, you should give a destination argument on the swift side and put a value there.

Recommended Posts

Pass C ++ char * to Swift
Handle C char ** well in Swift
Convert Swift 2D array to C 2D array
Convert from C String pointer to Swift String type
Port C code with a lot of typecasts to Swift
[Swift] How to use UserDefaults
How to use Swift UIScrollView
Pass a variable to Scope.
[Swift] Processing to share screenshots
Pass parameters to Rails link_to
[Swift5] How to communicate from ViewController to Model and pass a value
Swift: I want to chain arrays
I tried to chew C # (indexer)
Introduction to swift practice output Chapter5
Pass the i18n locale to JavaScript
[Swift] Another way to use Result?
[Swift] How to use SwiftLint (cocoapods)
How to pass Oracle Java Silver
Pass environment variables to docker container
[Swift] How to replace multiple strings
I tried to chew C # (polymorphism: polymorphism)
Call a C function from Swift
[Swift] How to pass the Label value in the selected collectionViewCell to the destination TextField