Search code examples
structmemberffilanguage-interoperabilityscala-native

How to access struct members by name in scala native?


From the scala native docs at https://scala-native.readthedocs.io/en/latest/ this is how to access struct members:

type Vec = CStruct3[Double, Double, Double]
val vec = stackalloc[Vec] // allocate c struct on stack
vec._1 = 10.0             // initialize fields
vec._2 = 20.0
vec._3 = 30.0
length(vec)               // pass by reference

Does scala native provide a way to access struct members by name instead of by index? And if not is it planned as a future enhancement?

I did not find a related issue in the issue tracker at github.


Solution

  • currently there is no support for by name accessors, however in the future we would like to change that, with goal of using plain case classes/classes with @struct annotation instead of current CStruct types. As a workaround a good practice currently is to create extension methods / implicit class for your struct to access fields by names, here's an example https://github.com/scala-native/scala-native/blob/cf0d7db6ee6133de8b9258b7dacceb39fa25c825/posixlib/src/main/scala/scala/scalanative/posix/signal.scala#L322