scala-native(0.1)で一行だけ読み込んでみる。
あってるのか微妙・・・。
環境: mac osx yosemite
package main
import scalanative.native._;
object Main {
def main(args: Array[String]): Unit = {
println(s"Hello ${readOneLine} .")
}
def readOneLine(): String = stdio.fopen(c"hoge.txt", c"r") match {
case null => ""
case fp => {
val buf = stackalloc[Byte](256)
stdio.fgets(buf, 256, fp)
stdio.fclose(fp)
buf(string.strlen(buf)-1) = '\0'
fromCString(buf.asInstanceOf[CString])
}
}
}
scalaなのにnull。
otoolで共有関係を見てみる。
$ otool -L ./target/scala-2.11/hoge-out
./target/scala-2.11/hoge-out:
/usr/local/opt/bdw-gc/lib/libgc.1.dylib (compatibility version 2.0.0, current version 2.3.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1213.0.0)
なんかそれっぽい。
0.2バージョン 追記
0.2が出たみたいなので、更新してみました。
File I/O APIがサポートされたようですよ。
package main
import scalanative.native._
import java.io.FileReader
import java.io.BufferedReader
import scala.io.Source
object Main {
def main(args: Array[String]): Unit = {
println(s"Hello ${readOneLineByFileReader} .")
println(s"Hello ${readOneLineBySource} .")
}
def readOneLineByFileReader(): String = {
val br = new BufferedReader(new FileReader("hoge.txt"));
br.readLine()
}
def readOneLineBySource(): String = Source.fromFile("hoge.txt").getLines.toList.head
}
コンパイル時にエラーが表示されたので、正規表現用のライブラリ?brew install re2
を
いれてあげたら、コンパイルできました。
↓コンソール
$ brew install re2
<略>
$ cat hoge.txt
1 a
2 b
3 c
$ sbt run
<略>
[info] Compiling to native code (2250 ms)
[info] Linking native code (336 ms)
Hello 1 a .
Hello 1 a .
$ otool -L target/scala-2.11/hoge-out
target/scala-2.11/hoge-out:
/usr/local/opt/bdw-gc/lib/libgc.1.dylib (compatibility version 2.0.0, current version 2.3.0)
/usr/local/opt/re2/lib/libre2.0.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/local/opt/llvm/lib/libc++.1.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1213.0.0)
/usr/lib/libc++abi.dylib (compatibility version 1.0.0, current version 125.0.0)