Scala Native中如何通过名称访问结构体成员?
To answer your questions directly:
Current Support
Right now, Scala Native does not support accessing C struct members by name—you're limited to using the index-based syntax (_1, _2, _3, etc.) as shown in your example. This is because CStructN types are implemented as positional tuples under the hood, with no built-in mapping to named fields.
Future Enhancement Plans
As you noted, there's no existing issue or public roadmap item for named struct member access in Scala Native's tracker. That means this feature isn't currently scheduled for upcoming releases. However, Scala Native is a community-driven project—if this functionality is important to you, submitting a feature request in the official repository would be the best way to push for it. Maintainers and contributors often prioritize features that have clear community demand.
Workaround: Wrapping with Extensions
If you want named access today, you can create a Scala extension to wrap the positional struct access with meaningful names. Here's how you could adapt your Vec example:
import scala.scalanative.unsafe._ type Vec = CStruct3[Double, Double, Double] extension (vec: Ptr[Vec]) def x: Double = vec._1 def x_=(value: Double): Unit = vec._1 = value def y: Double = vec._2 def y_=(value: Double): Unit = vec._2 = value def z: Double = vec._3 def z_=(value: Double): Unit = vec._3 = value // Usage example val vec = stackalloc[Vec] vec.x = 10.0 vec.y = 20.0 vec.z = 30.0 println(s"Vec: ${vec.x}, ${vec.y}, ${vec.z}")
This gives you the ergonomics of named member access while working within Scala Native's current struct handling capabilities.
内容的提问来源于stack exchange,提问作者user573215

