What is CLR Interop?
CLR Interop is the mechanism by which SolarSharp bridges the gap between Lua’s dynamic runtime and .NET’s statically-typed Common Language Runtime. It handles:- Type registration and descriptor management
- Method and property access from Lua
- Automatic type conversion between Lua and CLR types
- Custom type descriptors for fine-grained control
Key Components
The interop system consists of several key components:UserData
TheUserData class is the central registry for CLR types exposed to Lua. It maintains a global registry of type descriptors and provides methods for type registration.
Type Descriptors
Type descriptors (IUserDataDescriptor) define how Lua scripts can interact with CLR objects. They handle:
- Index operations (property/field access)
- Method invocations
- Metamethod implementations
- Type compatibility checks
Registration Policies
Registration policies (IRegistrationPolicy) control how types are registered and whether automatic registration is allowed:
- DefaultRegistrationPolicy - Prevents overwriting existing registrations, no auto-registration
- AutomaticRegistrationPolicy - Allows automatic type registration on first use
- PermanentRegistrationPolicy - Prevents type deregistration
InteropAccessMode
TheInteropAccessMode enum determines how SolarSharp optimizes member access for registered types:
Access Modes
| Mode | Optimization Timing | Performance | Memory Usage | Use Case |
|---|---|---|---|---|
| Reflection | Never | Slowest | Lowest | Rarely-used types |
| LazyOptimized | On first access | Good | Medium | General purpose (default) |
| Preoptimized | At registration | Fastest | Highest | Frequently-used types |
| BackgroundOptimized | Background thread | Good | Medium | Large types, async scenarios |
| HideMembers | N/A | N/A | Lowest | Prevent all member access |
| NoReflectionAllowed | N/A | N/A | Lowest | Custom descriptors only |
On AOT platforms like iOS, SolarSharp may automatically downgrade optimization modes to Reflection regardless of the specified mode.
Default Access Mode
You can set a default access mode for all type registrations:Type Registration Methods
SolarSharp provides several ways to register types:Checking Registration Status
You can check if a type is registered:Unregistering Types
Types can be unregistered, though this should be done carefully:Next Steps
Calling C# from Lua
Learn how to expose C# methods and objects to Lua scripts
Calling Lua from C#
Execute Lua functions from your C# code
UserData Types
Deep dive into UserData registration and custom types
Type Converters
Customize type conversion between Lua and CLR