I’m running into the same issue regarding printf
if I follow writing out the code as it is shown in the book.
I tried looking up the official documentation to see where printf
is defined and the docs have dead links.
https://scala-native.readthedocs.io/en/v0.3.9-docs/lib/libc.html
Real link:
So nativelib
was renamed to clib
. So to be fair, scala-native
is v0.3.9 and not stabilised yet so these quirks are part of the territory for bleeding edge.
Circling back to the pragprog listing though, I downloaded the latest source code which adds a compat.scala
file which remaps printf
to vprintf
.
package scala.scalanative
import scalanative.unsafe._
import scalanative.libc.stdio
package object libc {
implicit class StdioHelpers(val _stdio: libc.stdio.type) extends AnyVal {
def printf(format: CString, args: CVarArg*): CInt =
Zone { implicit z =>
stdio.vprintf(format, toCVarArgList(args.toSeq))
}
// Other unrelated code truncated
}
}
If I download the source from:
http://media.pragprog.com/titles/rwscala/code/rwscala-code.zip
Extract it.
Then cd
into code/InputAndOutput/hello_native
and run sbt run
it works.
Also I thought it was a typo between the “hello” and “hello_native” projects but it seems like capitalising the object name Main
is important when linking.
hello/hello.scala
object main {
def main(args:Array[String]) {
println("hello, world!")
}
}
hello_native/hello.scala
import scala.scalanative.unsafe._
import scala.scalanative.libc._
object Main {
def main(args: Array[String]): Unit = {
stdio.printf(c"Hello native %s!\n", c"world")
}
}
After some digging it seems you can use vprintf
directly using the following snippet:
import scala.scalanative.unsafe._
import scala.scalanative.libc._
object Main {
def main(args: Array[String]) {
Zone { implicit z =>
stdio.vprintf(c"Hello native %s!\n", toCVarArgList(c"world"))
}
}
}
Using vprintf
gave me the error “Given method requires an implicit zone”.
https://scala-native.readthedocs.io/en/v0.3.9-docs/user/interop.html#memory-management
Adding the Zone { implicit z => ..... }
creates a section of code to help with unmanaged memory allocations like our CVarArgList.