Repository navigation
[generator] Marshal Kotlin value classes across JNI - #13581
jonathanpeppers wants to merge 8 commits into
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved generator defects cause compilation failures for value-class bindings, while missing R8 retention metadata and array boxing support can cause runtime failures.
6 open issues
Java field getters retain incompatible value-class types · New R8 can strip value-class JNI boxing methods · New Generated helpers fail to compile with MemorySafetyRulesVersion=2 · New Referenced assemblies lose value-class mapping metadata · New Nullable nested value classes use the wrong binding writer · New Arrays of value classes lack boxing and unboxing marshaling · New
What changed in this PR
This PR extends Kotlin value-class support in the .NET for Android binding pipeline, preserving metadata through JavaTypeSystem adjustment and adding marshaling for boxed values.
Changes:
- Preserve value-class metadata and identify value-class extension receivers.
- Generate JNI boxing/unboxing helpers and adapt parameter, return, callback, and generic projections.
- Add metadata round-trip, generator, and Maven binding tests.
| File | Description |
|---|---|
tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinInlineClassCollisionTests.cs |
Tests extension-receiver metadata. |
tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/InlineClassCollisions.kt |
Adds nullable, generic, extension, and callback fixtures. |
tests/Java.Interop.Tools.JavaTypeSystem-Tests/JavaTypeModelsTests.cs |
Tests value-class attribute round-tripping. |
tests/generator-Tests/Unit-Tests/KotlinInlineClassEndToEndTests.cs |
Tests adjusted metadata and boxed-value code generation. |
tests/generator-Tests/generator-Tests.csproj |
Embeds the callback fixture. |
src/Xamarin.Android.Tools.Bytecode/Kotlin/KotlinFixups.cs |
Recognizes value-class parameters and extension receivers. |
src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs |
Adds a Compose value-class binding test. |
src/Java.Interop.Tools.JavaTypeSystem/JavaModels/JavaParameterModel.cs |
Adds parameter metadata storage. |
src/Java.Interop.Tools.JavaTypeSystem/Adapters/JavaXmlApiImporter.cs |
Imports value-class attributes. |
src/Java.Interop.Tools.JavaTypeSystem/Adapters/JavaXmlApiExporter.cs |
Preserves value-class attributes during export. |
src/generator/SourceWriters/KotlinInlineClassStruct.cs |
Emits construction, boxing, and unboxing helpers. |
src/generator/Java.Interop.Tools.Generator.ObjectModel/Symbols/KotlinInlineClassBoxedSymbol.cs |
Adds boxed-value marshaling and generic projection. |
src/generator/Java.Interop.Tools.Generator.ObjectModel/Symbols/GenericSymbol.cs |
Projects value-class generic arguments as Java objects. |
src/generator/Java.Interop.Tools.Generator.ObjectModel/ReturnValue.cs |
Projects boxed returns as nullable structs. |
src/generator/Java.Interop.Tools.Generator.ObjectModel/Parameter.cs |
Handles boxed parameters and explicit callback conversions. |
src/generator/Java.Interop.Tools.Generator.ObjectModel/GenericParameterList.cs |
Applies value-class generic-argument projection. |
src/generator/CodeGenerationOptions.cs |
Avoids null-forgiving operators for value-class projections. |
Review effort: Balanced
079b2c4 to
55d4bf2
Compare
63f5f5f to
e416b5e
Compare
Kotlin `@JvmInline value class` types backed by a primitive are bound as a C# `readonly partial struct` where the JVM passes the underlying primitive. Other cases did not work:
* The api.xml adjuster (`JavaXmlApiImporter`/`JavaXmlApiExporter`) dropped the value-class attributes from class-parse output (`kotlin-inline-class`, `kotlin-inline-class-underlying-jni-type`, `kotlin-inline-class-return-jni-type`, `kotlin-inline-class-jni-type`) and the unmangled `managedName`. The generator reads the adjusted file, so in a real binding build no value-class struct projection happened. This bug is also on `main`.
* Where the JVM passes the *boxed* value class (Kotlin `Foo?`, generic type arguments), the generator emitted `GetObject<Foo>` and `JNIEnv.ToLocalJniHandle (foo)` for a struct, which does not compile.
* An extension receiver (`fun Dp.coerceAtLeast(…)`) was not projected, and Kotlin parameter names were not applied to value-class parameters (they became `p0`).
* Java-to-C# callbacks passed the raw primitive and relied on an implicit conversion. With overloads such as `Density.roundToPx(Dp)` and `roundToPx(TextUnit)` this fails with `error CS0121: The call is ambiguous between the following methods or properties`.
* With nullable reference types enabled, value-class arguments got the `!` operator.
### Changes
* The adjuster keeps the value-class attributes in `PropertyBag` and writes them back. `JavaParameterModel` gets a `PropertyBag`.
* The generated struct gets `Create (T)`, `ToLocalJniHandle (Foo?)` and `FromJniHandle (IntPtr, JniHandleOwnership)`. They call the Kotlin `constructor-impl`, `box-impl` and `unbox-impl` helpers. kotlinc always generates these helpers with fixed signatures, so the generator derives the signatures from the underlying JNI type.
* A boxed `Foo?` is projected as C# `Foo?` and marshaled with these helpers. In generic type arguments the value class becomes `Java.Lang.Object`, because `JavaList<T>` cannot hold a struct.
* class-parse projects the extension receiver and passes the inline-class map to `TypesMatch`, so parameter names are applied.
* Callbacks construct the struct explicitly: `var dp = new MyDp (native_dp);`.
* No `!` is emitted for value-class parameters or return values.
* Nested value classes use the struct writer, and Java fields of a value-class type are projected like parameters.
* The struct helpers use `unsafe { }` blocks, so they compile with `MemorySafetyRulesVersion=2`.
* R8: the structs call `box-impl`/`unbox-impl`/`constructor-impl` by name, so R8 must keep them, but only for value classes the app uses. `JavaPeerScanner` adds each `[Register]` struct to the trimmable typemap as an entry with no proxy (key: the Kotlin class; proxy and trim target: the struct). The typemap-based R8 rules and acw-map.txt then keep the Kotlin class and its members only when the struct survives trimming. The entry has no `JavaPeerProxy`, so runtime lookups still fall back to `java/lang/Object`. `GenerateProguardConfiguration` (used when typemap R8 trimming is off) keeps all members of a `[Register]` struct. With `AndroidR8ObfuscationMode=runtime-remapping`, a `-keepclassmembernames` rule keeps the helper names, which the remapping tables do not cover.
* Across binding assemblies: `[Register]` now allows structs (`AttributeTargets.Struct`; added to the API-compatibility baseline), and the struct gets `[Register ("jni/name", DoNotGenerateAcw=true)]`. `CecilApiImporter` imports such a struct as a value class, and binds a `Foo` or `Foo?` parameter or return from a referenced assembly from the JNI type in its `[Register]` signature (otherwise `Foo` became `Foo?`, which breaks overrides and invokers). class-parse marks a value class from another library when the Kotlin type is a non-`kotlin/` class and the JVM type is a primitive, and the generator projects it only when the referenced struct has the same underlying type.
### Limitations
* `List<Foo>` becomes `IList<Java.Lang.Object>`; callers convert items with `Foo.FromJniHandle`.
* Members that use arrays of value classes are skipped.
* Value classes backed by a reference type (for example `String`) are not projected.
* Types nested in a value class (for example `Companion`) are not bound; members that use them are skipped.
* `new Foo (v)` and the implicit conversions do not run Kotlin `init` checks; `Foo.Create` does.
### Validation
`BindingBuildTest.AndroidMavenLibrary_KotlinValueClasses` binds the real `androidx.compose.ui:ui-unit-android` 1.12.1 library with `MemorySafetyRulesVersion=2`, and `TextIndent` from `ui-text-android` in a second binding project that references it (about 16 s). It checks that `Dp` is a registered struct, that `CoerceAtLeast (Dp obj, Dp minimumValue)` is generated from `coerceAtLeast-YgX7TsA(FF)F`, that the mangled `lerp-…` overloads become `Lerp (DpSize …)`, and that `TextIndent.FirstLine` uses the `TextUnit` struct from the other assembly. This test found the receiver, parameter-name and callback bugs. The new unit tests fail without their fixes.
* `dotnet-local.cmd build Microsoft.Android.slnx` and `dotnet-local.cmd build Microsoft.Android.slnx -t:PackDotNet`: succeeded
* `dotnet-local.cmd test bin\TestDebug\net11.0\Xamarin.Android.Build.Tests.dll --filter Name~AndroidMavenLibrary_KotlinValueClasses` (with `TEST_ANDROID_JDK_PATH` set to JDK 21): 1 passed
* `dotnet test tests\Xamarin.Android.Tools.Bytecode-Tests\Xamarin.Android.Tools.Bytecode-Tests.csproj`: 138 passed, 2 skipped
* `dotnet test tests\Java.Interop.Tools.JavaTypeSystem-Tests`: 17 passed
* `dotnet-local.cmd test tests\generator-Tests\generator-Tests.csproj`: 493 passed
* `dotnet-local.cmd test src\Microsoft.Android.Build.Tasks\Tests\Microsoft.Android.Build.Tasks.Tests\Microsoft.Android.Build.Tasks.Tests.csproj`: 1037 passed, 50 skipped
On device, `Mono.Android.NET-Tests` binds a small Kotlin library (`tests/Mono.Android-Tests.Gradle`) with `<AndroidGradleProject>`. It uses the repository's Gradle wrapper through a new private `$(_AndroidGradleWrapperDirectory)` property. `KotlinValueClassTests` calls unboxed and boxed parameters and returns, an extension receiver, a property, a `List<Meters>` return, and `Create` (the Kotlin `init` block runs). CI runs these tests in the existing Debug, Release (R8, full trimming), NoAab and NativeAOT lanes.
* `dotnet-local.cmd build -t:Install -c Debug tests\Mono.Android-Tests\Mono.Android-Tests\Mono.Android.NET-Tests.csproj -p:Device=emulator-5554`, then `dotnet-local.cmd test Mono.Android.NET-Tests.csproj --no-build -c Debug -p:Device=emulator-5554` (API 29 x86_64 emulator): all `KotlinValueClassTests` passed. `JavaMarshalGCBridgeTests.ManagedPeerCycleSurvivesJavaRootAndIsCollectedAfterRelease` failed once and passed on a rerun with `-p:IncludeCategories=GCBridge`. `ExceptionTest.ManagedExceptionRoundTripPreservesIdentity (False)` aborted the process; it is not related to this change.
* Release (R8, `TrimMode=full`), same commands with `-c Release` on a Pixel 10: 1094 passed, 0 failed; all 7 `KotlinValueClassTests` passed. `proguard_project_references.cfg` has `-keep class net.dot.android.test.kotlin.Meters` and `…Id` from the typemap keys.
* `AndroidGradleProjectTests.BindLibrary` (4 passed) and `InvalidItemRefError` (2 passed) with the new property.
* `-c Release -p:AndroidR8ObfuscationMode=runtime-remapping` on the Pixel 10: all 7 `KotlinValueClassTests` passed, and the R8 mapping keeps `box-impl`/`unbox-impl`/`constructor-impl` while it renames other members. (The `[Export]` tests fail in this mode; no CI lane runs it.)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
e416b5e to
d24d334
Compare
Real builds import referenced types lazily (`UseShallowReferencedTypes`). `CecilApiImporter.CreateClass ()` returns early for a `[Register]` struct and sets no `PopulateAction`, so `SymbolTable.EnsurePopulated ()` threw a `NullReferenceException` when a dependent binding used the value class (`AndroidMavenLibrary_KotlinValueClasses` on CI). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
C# users expect `new Meters (-1)` to fail like Kotlin's `Meters(-1.0)`.
class-parse now marks value classes with an `init` block: without one,
kotlinc writes `constructor-impl` as only "load; return" (2 bytes). It
writes `kotlin-inline-class-has-init`, which the adjuster keeps.
* With an `init` block, the struct constructor calls
`constructor-impl`, and the conversion from the primitive is
`explicit`, because implicit conversions must not throw.
* Without one (`Dp`, `TextUnit`, …), the constructor only stores the
value and makes no JNI call.
* Generated marshaling code uses a hidden `FromJniValue ()`, because
Java already ran the `init` block.
* `Create ()` is removed.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* class-parse checks the *primary* `constructor-impl` for an `init`
block. Secondary constructors also compile to `constructor-impl`,
with other signatures, and made a class without an `init` block
look like it had one.
* A value class replaces a primitive only when the primitive is the
struct's `Value` type. Comparing JNI names let a `ulong` (for
example from Metadata.xml) match a `long` struct, which does not
compile.
* `ReturnValue.Clone ()` keeps the value-class marshaling flag.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
/review |
|
✅ Android PR Reviewer completed successfully! Warning Firewall blocked 1 domainThe following domain was blocked by the firewall during workflow execution:
To allow these domains, add them to the network:
allowed:
- defaults
- "169.254.169.254"See Network Configuration for more information.
|
There was a problem hiding this comment.
⚠️ Needs Changes
2 ❌ errors · 0
The adjuster attribute round-trip, explicit callback conversions, and value-class retention wiring address important gaps in real binding builds. The cross-assembly and on-device coverage are valuable. Two generated-code failures remain, detailed inline:
- The newly supported nested
Outer.Valueproduces a struct namedValuecontaining a field namedValue(CS0542). - External value-class annotations prevent overload deduplication even when no matching struct is available, producing duplicate primitive signatures when consuming older bindings.
Verification: Built the standalone generator successfully and reproduced both generated-output shapes through its class-parse XML/adjuster pipeline. An isolated compilation confirmed CS0542 for the nested struct. The focused NUnit run could not execute because compilation of unchanged Java.Interop sources failed with CS9363 under the installed .NET SDK 11.0.100; those diagnostics are not attributed to this PR.
CI: The latest GitHub check results show all 47 checks completed: 46 succeeded and 1 skipped, including a successful overall dotnet-android check. Direct Azure DevOps build/timeline retrieval required authentication, so independent Azure status verification was unavailable.
Warning
Firewall blocked 1 domain
The following domain was blocked by the firewall during workflow execution:
169.254.169.254
To allow these domains, add them to the network.allowed list in your workflow frontmatter:
network:
allowed:
- defaults
- "169.254.169.254"See Network Configuration for more information.
Generated by Android PR Reviewer for #13581 · copilot · gpt61 · 289.7 AIC · ⌖ 4.09 AIC · ⊞ 21K
Comment /review to run again
| // Without an `init` block, kotlinc writes the primary `constructor-impl` as "load the argument, return it" (2 bytes). | ||
| // Secondary constructors also compile to `constructor-impl`, with other signatures. | ||
| var primary = $"({backing.Descriptor}){backing.Descriptor}"; | ||
| c.KotlinInlineClassHasInit = c.Methods.FirstOrDefault (m => m.Name == "constructor-impl" && m.Descriptor == primary)?.Attributes.Get<CodeAttribute> ()?.ByteCode is { Length: > 2 }; | ||
|
|
There was a problem hiding this comment.
I'm glad we can detect empty constructor-impl so easily. If if we had to call a pinvoke every time somebody creates an instance of Dp, it could add up (unless Dp has inits, but maybe it has secondary constructors, so we can't tell those from init blocks?).
There was a problem hiding this comment.
We can tell them apart: a secondary constructor compiles to its own constructor-impl with a different signature (e.g. constructor(value: Int) on a ULong class is constructor-impl(I)J), and class-parse only checks the primary constructor-impl(T)T. The MyColor fixture has a secondary constructor, and Fixup_StampsKotlinInlineClassUnderlyingJniType checks it is still "no init block".
|
Do we support |
* A value class named `Value` keeps the peer-class binding: the
struct's `Value` field cannot have the type's name (CS0542).
* Before removing colliding mangled overloads, clear the value-class
mark on parameters whose type is not a value class in the symbol
table (for example a peer class from an older binding). They stay
the primitive, so they collide like the primitive, as before.
* Test `@JvmName` on value-class functions (`Compute (uint)` next to
`Compute (int)`), and compile the generated code in two tests.
* Mono.Android-Tests.Gradle: `compileSdk = 37`, `minSdk = 24`.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
@simonrozsival yes. The C# name comes from the Kotlin name, and JNI uses the @JvmName("computeUInt")
fun compute(x: UInt) { }
fun compute(x: Int) { }
@JvmName("tintColor")
fun tintWith(color: MyColor) { }and [Register ("computeUInt", "(I)V", "")]
public void Compute (uint x)
[Register ("compute", "(I)V", "")]
public void Compute (int x)
[Register ("tintColor", "(J)V", "")]
public void TintWith (MyColor color)So |
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…n-value-class-support
|
/review |
|
✅ Android PR Reviewer completed successfully! Warning Firewall blocked 1 domainThe following domain was blocked by the firewall during workflow execution:
To allow these domains, add them to the network:
allowed:
- defaults
- "169.254.169.254"See Network Configuration for more information.
|
There was a problem hiding this comment.
Review: ⚠️ Validation pending
Findings: 0 errors, 0 warnings, 1 non-blocking testing suggestion posted inline. No new blocking correctness issue identified in the 48-file change. I checked the full changed sources and relevant callers, including attribute round-tripping, boxed/unboxed marshaling, nested generation, referenced-binding imports, and typemap-to-R8 retention. The current code addresses the earlier field, nested-type, ownership-context, and fallback-collision findings; the documented unsupported projections were treated as intentional limitations.
The separation between constructor validation and FromJniValue is sound, and retaining registered structs without creating Java-peer proxies keeps the R8 integration appropriately scoped.
Validation: The focused KotlinInlineClassCollisionTests run passed 10/10 using dotnet test tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj --filter FullyQualifiedName~KotlinInlineClassCollisionTests with explicit paths to the installed JDK. The focused generator run (dotnet test tests/generator-Tests/generator-Tests.csproj --filter 'FullyQualifiedName~KotlinInlineClass|FullyQualifiedName~KotlinFixups') could not reach test execution: compilation reported CS9363 in the unchanged src/Java.Interop/Java.Interop/JniNativeMethodRegistration.cs, lines 50–51. No source changes were made to work around that failure, and I did not independently run the Android device/R8 matrix.
CI: The returned checks for Azure build 1692967 still show four jobs in progress and the aggregate check queued, with no failures reported so far. Direct Azure build/timeline access was blocked by an authentication requirement, so CI is not confirmed green and this is not an LGTM/merge-readiness verdict.
Warning
Firewall blocked 1 domain
The following domain was blocked by the firewall during workflow execution:
169.254.169.254
To allow these domains, add them to the network.allowed list in your workflow frontmatter:
network:
allowed:
- defaults
- "169.254.169.254"See Network Configuration for more information.
Generated by Android PR Reviewer for #13581 · copilot · gpt61 · 168.4 AIC · ⌖ 4.31 AIC · ⊞ 21K
Comment /review to run again
| var lengths = ValueClasses.Lengths (3); | ||
| Assert.AreEqual (3, lengths.Count); | ||
| Assert.AreEqual (new Meters (2), Meters.FromJniHandle (lengths [2].Handle, Android.Runtime.JniHandleOwnership.DoNotTransfer)); | ||
| } |
There was a problem hiding this comment.
🤖 💡 Testing — Could we add a direct boxing-helper round-trip test covering TransferLocalRef, TransferGlobalRef, and DoNotTransfer? The current tests exercise local transfers indirectly through generated calls and this borrowed-reference path, but never the new global-transfer cleanup branch. Use live references created by ToLocalJniHandle/JNIEnv.NewGlobalRef, verify the returned value, and verify that a borrowed reference remains usable before explicitly releasing it. This would protect the ownership contract independently of the value/null assertions.
{Rule: Test JNI reference ownership and cleanup paths.}


Context: #11844
Background
A Kotlin
@JvmInline value classwraps one value. kotlinc erases it to that value on the JVM, and mangles the names of functions that use it. For example, a fileLengths.kt:The top-level functions go into the JVM class
example.LengthsKt(the "file facade";@file:JvmNamechanges its name):LengthsKtadd(a: Meters, b: Meters): Metersadd-…(DD)DMeters.doubled(): Metersdoubled-…(D)DorZero(meters: Meters?): MetersorZero-…(Lexample/Meters;)DfindId(value: Long): Id?findId(J)Lexample/Id;A non-null
Metersis passed as adouble. A nullableMeters?(and a value class in a generic type argument or field) is passed as the boxedMetersobject. Every value class also gets staticbox-impl/constructor-implmethods and an instanceunbox-implmethod.mainalready binds a value class as a C#readonly partial structand handles the unboxed case in class-parse output. Real bindings failed:JavaXmlApiImporter/JavaXmlApiExporter) dropped thekotlin-inline-class*attributes andmanagedName, so a real binding build never produced the structs.Foo?, the generated code calledGetObject<Foo>on a struct, which does not compile.Meters.doubled()) were not projected, and value-class parameters were namedp0.Density.roundToPx(Dp)/roundToPx(TextUnit)witherror CS0121: The call is ambiguous.Binding output
Each value class becomes a struct with a
[Register]attribute (so other assemblies and the build can find it) and helpers that call the Kotlin*-implmethods:Members use the struct, with unmangled names. Unboxed values are passed as the primitive; boxed values go through the helpers:
C# and Kotlin callers:
tests/Mono.Android-Tests.Gradlehas this Kotlin code (in packagenet.dot.android.test.kotlin, facadeValueClasses).Construction and cost
In Kotlin,
Meters(-1.0)runs theinitblock. To match, the C# constructor calls Java only for value classes that have aninitblock. class-parse checks the primaryconstructor-impl (T)T(secondary constructors compile toconstructor-implwith other signatures). Without aninitblock, kotlinc writes it as "load, return":initblock (Id; also Compose'sDp,TextUnit, most others)initblock (Meters)new Foo (v)v; no JNI callValue = ConstructorImpl (v): one JNI call to the staticconstructor-impl, which throws like KotlinT → Fooconversionimplicitexplicit(implicit conversions must not throw)unbox-impl)FromJniValue: stores the valueFromJniValue: stores the value; Kotlin already ran theinitblockconstructor-implis a static method that takes and returns the primitive, sonew Meters (5)does not create a Java object (the onlynewin it is the exception). Kotlin also cannot change the value there: the property is avalset from the parameter, soconstructor-implreturns its input or throws.Java objects are created only where Kotlin itself passes the boxed value:
Fooparameter or returnFoo?passed to Java (box-impl)Foo, plus a JNI local reference that is deleted after the callNullable<Foo>)Foo?returned from Java (unbox-impl)List<Foo>Java.Lang.Objectpeer per item read (#13668 tracks a typedIList<Foo>)default (Foo)and array elements do not run theinitblock, as for any C# struct.Changes
The adjuster keeps the value-class attributes. class-parse adds
kotlin-inline-class-has-init.The generator writes the struct helpers above, binds
Foo?as C#Foo?, and binds nested value classes and fields of a value-class type. A value class in a generic type argument becomesJava.Lang.Object.class-parse projects extension receivers and applies Kotlin parameter names. Callbacks wrap the value explicitly (
var dp = Dp.FromJniValue (native_dp);).Across binding assemblies:
[Register]now allows structs (API-compatibility baseline updated). When a binding references another binding's struct,CecilApiImporterimports it as a value class, and class-parse marks a value class from another library (a non-kotlin/class erased to a primitive). The generator projects it only when the referenced struct has the same underlying type. For example,ui-text'sTextIndent.FirstLineusesui-unit'sTextUnitstruct.R8: the helpers call
box-impl/unbox-impl/constructor-implby name, so R8 must keep them, but only for value classes the app uses.JavaPeerScannergives each[Register]struct a typemap entry with no proxy, whose trim target is the struct. The existing typemap and acw-map.txt R8 rules then keep the Kotlin class only when the struct survives trimming:The entry has no
JavaPeerProxy, so runtime typemap lookups are unchanged.GenerateProguardConfiguration(used when typemap R8 trimming is off) keeps all members of a[Register]struct, andAndroidR8ObfuscationMode=runtime-remappingkeeps the helper names.Limitations
List<Foo>becomesIList<Java.Lang.Object>; convert items withFoo.FromJniHandle (item.Handle, JniHandleOwnership.DoNotTransfer).Companion), are skipped.String) are not projected.Valuekeeps the peer-class binding, because the struct'sValuefield cannot have the type's name.Follow-ups: #13667 (members declared in value classes), #13668 (
IList<Foo>), #13669 (implementing interfaces with value-class parameters), #13670 (reference-backed value classes), #13671 (extension methods).Validation
BindingBuildTest.AndroidMavenLibrary_KotlinValueClassesbindsandroidx.compose.ui:ui-unit-android1.12.1, andTextIndentfromui-text-androidin a second binding project that references it. It checks theDpstruct,CoerceAtLeast (Dp obj, Dp minimumValue)fromcoerceAtLeast-YgX7TsA(FF)F,Lerp (DpSize …), andTextIndent.FirstLineusingTextUnitfrom the other assembly.Mono.Android.NET-Testsnow binds the test Kotlin library (tests/Mono.Android-Tests.Gradle) with<AndroidGradleProject>, using the repository's Gradle wrapper through a new private$(_AndroidGradleWrapperDirectory).KotlinValueClassTestsruns in the existing Debug, Release, NoAab and NativeAOT lanes.Xamarin.Android.Build.Tests --filter Name~AndroidMavenLibrary_KotlinValueClasses: passedgenerator-Tests: 494 passedXamarin.Android.Tools.Bytecode-Tests: 138 passed, 2 skippedJava.Interop.Tools.JavaTypeSystem-Tests: 17 passedMicrosoft.Android.Build.Tasks.Tests: 1037 passed, 50 skippedAndroidGradleProjectTests.BindLibraryandInvalidItemRefError: passedMono.Android.NET-Tests, Debug on an API 29 emulator:KotlinValueClassTestspassed. Two unrelated tests failed (a flaky GC bridge test, andExceptionTest.ManagedExceptionRoundTripPreservesIdentity, which aborts the process).Mono.Android.NET-Tests, Release (R8, full trimming) on a Pixel 10: 1094 passed, 0 failed, and the generated R8 rules keepMetersandId. After the constructor change, all 7KotlinValueClassTestspassed again, includingConstructorRunsInitBlock; the run stopped at the same unrelatedManagedExceptionRoundTripPreservesIdentitycrash.AndroidR8ObfuscationMode=runtime-remappingon a Pixel 10:KotlinValueClassTestspassed, and the R8 mapping keeps the helper names. The[Export]tests fail in this mode; no CI lane runs it.