LoginSignup
3
4

More than 3 years have passed since last update.

C言語のchar*をSwiftに渡す

Last updated at Posted at 2017-11-09

すること

C言語でchar*を返し、swiftでStringとして扱う

場面

HelloFrameWork(Cocoa Touch Framework)を作成し終えたので、swiftからその中のメソッドを使いたい

C言語

hello.hは、Xcodeでpublicヘッダーにしておく

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)
// メモリ解放
free(hello_char)

参考

公式 ドキュメント Using Swift with cocoa and Object-C

追記

strdup()を使うのはやはり美しくないようです。
より良く書くなら、swift側でdestinationとなる引数を与えて、そこに値を入れるようにすべきです。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4