• Avalanche.Core
Search Results for

    Show / Hide Table of Contents
    • Avalanche.Accessor
      • Introduction
      • IAccessor
        • IAccessor
        • IListAccessor
        • IMapAccessor
        • IRecordAccessor
        • IContentAccessor
        • IOneOfAccessor
        • IAnyAccessor
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • Dependency Injection
        • AccessorMessages
    • Avalanche.Binding
      • Introduction
    • Avalanche.Core
      • License
    • Avalanche.DataType
      • Introduction
      • DataType
        • IDataType
        • IListType
        • IMapType
        • IRecordType
        • IFieldType
        • IOneOfType
        • IAnyType
        • IStringType
        • IValueType
        • IIntegerType
        • IEnumerationType
        • IRealType
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • Enum
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • DataTypeRequest
        • PrintTree
        • DataTypeMessages
    • Avalanche.Emit
      • Introduction
      • TypeBuilder
      • ConstructorBuilder
      • MethodBuilder
      • PropertyBuilder
      • FieldBuilder
      • Emit
      • Utilities
    • Avalanche.FileSystem
      • Introduction
      • Abstractions
        • IFileSystem
          • IFileSystemBrowse
          • IFileSystemCreateDirectory
          • IFileSystemDelete
          • IFileSystemFileAttribute
          • IFileSystemMount
          • IFileSystemMove
          • IFileSystemObserve
          • IFileSystemOpen
        • IEvent
        • IEntry
        • IOption
        • IToken
      • FileSystem
      • VirtualFileSystem
      • MemoryFileSystem
      • EmbeddedFileSystem
      • HttpFileSystem
      • Decoration
      • IFileProvider
      • Events
      • Utilities
        • Dispose
        • File Scanner
        • Visit Tree
        • File Operation
    • Avalanche.Identity
      • Introduction
      • Identity
      • IdentityParts
      • IdentityInterner
      • IdentityComparer
      • Print Tree
      • IdentityAccessors
        • Introduction
        • TypeName
    • Avalanche.Localization
      • Introduction
      • Localization
      • LocalizationFile
      • LocalizationFiles
      • LocalizationFileSystem
      • LocalizationFileFormat
      • LocalizationLine
      • LocalizationLines
      • TemplateFormat
      • CultureProvider
      • FallbackCultureProvider
      • ResourceManager
      • LocalizationError
      • Microsoft.Extensions
        • Introduction
        • DependencyInjection
        • FileProvider
        • Logging
        • ITextLocalizer
        • IFileLocalizer
        • Localization
      • Asp.Net
        • Introduction
        • Supplying localization
        • Inject to pages
        • Culture Assigned
        • Minimalistic Api
        • Diagnostics
      • Pluralization
        • Introduction
        • Multiple plural parameters
        • Custom PluralRules
        • Invariant Culture
        • Unit Prefix
        • IPluralRule
        • IPluralNumber
        • IPluralRules
        • CLDRs
        • Unicode.CLDR40
        • Unicode.CLDR41
        • Unicode.CLDR42
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
        • Printing templates
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Microsoft.Extensions
        • DependencyInjection
      • Articles
        • Aggregate Messages
        • Localization
        • Logging
        • Validation
    • Avalanche.Service
      • Introduction
      • Service
        • Introduction
        • IService
        • IServiceDisposable
        • IServiceDecoration
        • IServiceCast
        • IServiceObservable
        • IServiceContainer
        • Construction
        • Query
        • CancellationToken
        • CachePolicy
        • Scope
      • Handler
        • Introduction
        • IHandler
        • IHandlerCast
        • IHandlerDecoration
        • IHandlerWithOrder
        • CancellationToken
        • Cyclicity
        • Delegates
        • Invokable
        • ExportAttribute
        • OrderAttribute
        • PrintTree
        • Recursion
      • Query
        • Introduction
        • IQuery
        • IQueryCast
        • IQueryDecoration
      • Entry
        • Introduction
        • IEntry
        • IEntryCast
        • IEntryDecoration
        • IEntryObservable
        • IEntryVisitable
        • EntryState
      • Request
        • Introduction
        • IRequest
        • IRequestFor
        • IRequestToBeCached
        • IRequestToBeDisposed
        • RequestAttribute
        • ContextParameterAttribute
        • Print Tree
      • Dependency Injection
        • Introduction
        • Asp.Net
        • ServiceRequest<T>
        • Decorating a service
        • Handler
        • CachePolicy
        • CancellationToken
        • QueryLogger
      • Examples
        • NodeCount
        • Expression
        • Mapper
      • Articles
        • Benchmarks
        • Error Handling
        • ServiceMessages
    • Avalanche.StatusCode
      • Introduction
      • HResult
        • Introduction
        • HResult.Facilities
        • BasicMessages
        • RpcMessages
        • DispatchMessages
        • ItfMessages
        • Win32Messages
        • ClrMessages
      • System
        • Introduction
        • AccessControlMessages
        • AggregateMessages
        • AppDomainMessages
        • ArgumentMessages
        • ArgumentNullMessages
        • ArgumentOutOfRangeMessages
        • ArithmeticMessages
        • ArrayMessages
        • AssemblyMessages
        • BadImageFormatMessages
        • CodeContractMessages
        • CodePageMessages
        • CollectionsMessages
        • CompilerServiceMessages
        • CryptographyMessages
        • CultureMessages
        • DiagnosticsMessages
        • EventSourceMessages
        • ExecutionEngineMessages
        • FormatMessages
        • HostProtectionMessages
        • IOMessages
        • IndexOutOfRangeMessages
        • InteropServiceMessages
        • InvalidCastMessages
        • InvalidOperationMessages
        • IsolatedStorageMessages
        • LazyMessages
        • MarshalerMessages
        • MemoryMessages
        • MiscellaneousMessages
        • NotImplementedMessages
        • NotSupportedMessages
        • ObjectDisposedMessages
        • OperationCanceledMessages
        • OverflowMessages
        • PlatformMessages
        • PolicyMessages
        • PrincipalMessages
        • ProgramMessages
        • ReferenceMessages
        • ReflectionMessages
        • RegionMessages
        • RemotingMessages
        • ResourcesMessages
        • SecurityMessages
        • SerializationMessages
        • StackMessages
        • TaskMessages
        • TextMessages
        • ThreadingMessages
        • TimeZoneMessages
        • TypeMessages
        • XmlMessages
      • HttpStatusCode
      • OpcUaStatusCode
    • Avalanche.Template
      • Introduction
      • TemplateFormats
      • ITemplatePrintable
      • ITemplateFormatPrintable
      • ITemplateText
      • ITemplateBreakdown
      • ITemplateFormat
      • ITemplateFormats
      • Extract Arguments
      • Emplacement
    • Avalanche.Tokenizer
      • Introduction
      • IToken
      • ITokenizer
      • Tokenizers
    • Avalanche.Utilities
      • Introduction
      • Collections
        • Tuples
        • StructList
        • ArrayList
        • BijectionMap
        • LocakableDictionary
        • LockableList
        • MapList
        • Pipe
        • RingQueue
        • EnumerableExtensions
        • TupleUtilities
        • ArrayUtilities
      • Comparers
        • IGraphComparer
        • IGraphComparable
        • AlphaNumericComparer
        • EnumerableComparer
        • EnumerableGraphComparer
        • ReferenceComparer
        • KeyValuePairComparer
        • DefaultComparerProvider
        • RecordComparer
      • Cloners
        • ICloner
        • IGraphCloner
        • IGraphCloneable
        • ListCloner
        • DictionaryCloner
        • FieldCloner
        • PassthroughCloner
        • RecordCloner
        • ClonerProvider
      • Dispose
        • IDisposeAttachable
        • IDisposeBelatable
      • Provider
        • Introduction
        • ProviderBase
        • Delegate
        • Pipe
        • Cache
        • ResultCapture
        • AsReadOnly
        • AsService
        • IProviderEvent
      • Record
        • IRecordDescription
        • IFieldDescription
        • IConstructorDescription
        • IConstructionDescription
        • IParameterDescription
        • IRecordProviders
        • RecordDelegates
          • RecordCreate
          • RecordClone
          • RecordCopy
          • IRecordDelegates
        • FieldDelegates
          • FieldRead
          • FieldWrite
          • RecreateWith
          • IFieldDelegates
      • String
        • IEscaper
        • UnicodeString
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    Introduction

    Avalanche.Emit is a class library for building Types and emitting opcodes by utilizing Avalanche.Service architecture. This library is a helper to the System.Reflection.Emit namespace.

    The following example creates a type with method "int MyFunction(int x) => x < 5 ? 0 : 1;"

    // Service that handles assembly builder, module builder and type builder
    IService service = Services.Create((ServiceHandlers.Instance, EmitHandlers.Instance), CachePolicies.Default);
    // Request to create type builder
    IRequestFor<TypeBuilder> typeBuilder = new TypeBuilderRequest("MyClass_", TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass);
    // Request to create method builder for "MyFunction"
    IRequestFor<MethodBuilder> myFunc = new MethodBuilderRequest("MyFunction", MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), typeof(int));
    // Request to create il generator
    IRequestFor<ILGenerator> il = ILGeneratorRequest.Default;
    // Define labels
    IRequestFor<Label> trueLabel = new LabelRequest(), falseLabel = new LabelRequest();
    // "return x < 5 ? 0 : 1"
    il = il.Append(OpCodes.Ldarg_1).Append(OpCodes.Ldc_I4_5).Append(OpCodes.Clt).Append(OpCodes.Brtrue_S, falseLabel);
    // true: return 1;
    il = il.Append(new MarkLabelRequest(trueLabel)).Append(OpCodes.Ldc_I4_1).Append(OpCodes.Ret);
    // false: return 0;
    il = il.Append(new MarkLabelRequest(falseLabel)).Append(OpCodes.Ldc_I4_0).Append(OpCodes.Ret);
    // Add il to "MyFunction"
    myFunc = myFunc.Append(il);
    // Add "MyFunction"
    typeBuilder = typeBuilder.Append(myFunc);
    
    // Request to build type
    IRequestFor<Type> type = new TypeRequest(typeBuilder);
    // Request to create new instance
    IRequestFor<Object> newRequest = type.NewRequest();
    
    // Print request
    newRequest.PrintTreeTo(Console.Out);
    
    // Get instance
    object instance = service.GetRequired<IRequestFor<object>, object>(newRequest);
    // Evaluate: value = 4 < 5 ? 0 : 1;
    int value = (int)instance.GetType().GetMethod("MyFunction", new Type[] { typeof(int) })!.Invoke(instance, new object[] { 4 })!;
    // Print 
    Console.WriteLine(value);
    
    View complete request
    NewRequest
    └── Type = TypeRequest
        └── Key = ContextRequest<TypeBuilder>
            ├── Key = "System.Reflection.Emit.TypeBuilder"
            ├── Value = TypeBuilderRequest
            │   ├── Name = "MyClass_"
            │   └── Attributes = AutoLayout, AnsiClass, Class, Public, AutoClass
            └── Requests[0] = ContextRequest<MethodBuilder>
                ├── Key = "System.Reflection.Emit.Builder"
                ├── Value = MethodBuilderRequest
                │   ├── Name = "MyFunction"
                │   ├── Attributes = PrivateScope, Public, Virtual
                │   ├── ReturnType = System.Int32
                │   └── ParameterTypes[0] = System.Int32
                └── Requests[0] = ContextRequest<ILGenerator>
                    ├── Key = "System.Reflection.Emit.ILGenerator"
                    ├── Value = ILGeneratorRequest
                    ├── Requests[0] = Emit
                    │   └── Opcode = ldarg.1
                    ├── Requests[1] = Emit
                    │   └── Opcode = ldc.i4.5
                    ├── Requests[2] = Emit
                    │   └── Opcode = clt
                    ├── Requests[3] = Emit
                    │   ├── Opcode = brtrue.s
                    │   └── Parameters[0] = LabelRequest
                    │       └── Id = 49972132
                    ├── Requests[4] = MarkLabelRequest
                    │   └── Label = LabelRequest
                    │       └── Id = 65204782
                    ├── Requests[5] = Emit
                    │   └── Opcode = ldc.i4.1
                    ├── Requests[6] = Emit
                    │   └── Opcode = ret
                    ├── Requests[7] = MarkLabelRequest
                    │   └── Label = LabelRequest
                    ├── Requests[8] = Emit
                    │   └── Opcode = ldc.i4.0
                    └── Requests[9] = Emit
                        └── Opcode = ret
    

    Emit Handlers

    EmitHandlers is a collection of handlers that participate in building a type. EmitHandlers requires cache and ServiceHandlers as helper handlers.

    // Service that handles assembly builder, module builder and type builder
    IService service = Services.Create((ServiceHandlers.Instance, EmitHandlers.Instance), CachePolicies.Default);
    
    EmitHandlers
    ├── TypeBuilderFactory
    ├── TypeFactory
    ├── TypeBuiltHandler
    ├── ConstructorBuilderFactory
    ├── MethodBuilderFactory
    ├── FieldBuilderFactory
    ├── PropertyBuilderFactory
    ├── DefineMethodOverrideHandler
    ├── ILGeneratorFactory
    ├── PropertyBuilderSetSetterHandler
    ├── PropertyBuilderSetGetterHandler
    ├── EmitHandler
    ├── EmitLdIndHandler
    ├── EmitStIndHandler
    ├── EmitCastHandler
    ├── LocalBuilderFactory
    ├── LabelFactory
    └── MarkLabelRequestHandler
    

    Full Example

    Full example
    using System;
    using System.Reflection;
    using System.Reflection.Emit;
    using Avalanche.Emit;
    using Avalanche.Service;
    
    public class index
    {
        public static void Run()
        {
            {
                // <1>
                // Service that handles assembly builder, module builder and type builder
                IService service = Services.Create((ServiceHandlers.Instance, EmitHandlers.Instance), CachePolicies.Default);
                // Request to create type builder
                IRequestFor<TypeBuilder> typeBuilder = new TypeBuilderRequest("MyClass_", TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass);
                // Request to create method builder for "MyFunction"
                IRequestFor<MethodBuilder> myFunc = new MethodBuilderRequest("MyFunction", MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), typeof(int));
                // Request to create il generator
                IRequestFor<ILGenerator> il = ILGeneratorRequest.Default;
                // Define labels
                IRequestFor<Label> trueLabel = new LabelRequest(), falseLabel = new LabelRequest();
                // "return x < 5 ? 0 : 1"
                il = il.Append(OpCodes.Ldarg_1).Append(OpCodes.Ldc_I4_5).Append(OpCodes.Clt).Append(OpCodes.Brtrue_S, falseLabel);
                // true: return 1;
                il = il.Append(new MarkLabelRequest(trueLabel)).Append(OpCodes.Ldc_I4_1).Append(OpCodes.Ret);
                // false: return 0;
                il = il.Append(new MarkLabelRequest(falseLabel)).Append(OpCodes.Ldc_I4_0).Append(OpCodes.Ret);
                // Add il to "MyFunction"
                myFunc = myFunc.Append(il);
                // Add "MyFunction"
                typeBuilder = typeBuilder.Append(myFunc);
    
                // Request to build type
                IRequestFor<Type> type = new TypeRequest(typeBuilder);
                // Request to create new instance
                IRequestFor<Object> newRequest = type.NewRequest();
    
                // Print request
                newRequest.PrintTreeTo(Console.Out);
    
                // Get instance
                object instance = service.GetRequired<IRequestFor<object>, object>(newRequest);
                // Evaluate: value = 4 < 5 ? 0 : 1;
                int value = (int)instance.GetType().GetMethod("MyFunction", new Type[] { typeof(int) })!.Invoke(instance, new object[] { 4 })!;
                // Print 
                Console.WriteLine(value);
                // </1>
            }
            {
                // <2>
                // Service that handles assembly builder, module builder and type builder
                IService service = Services.Create((ServiceHandlers.Instance, EmitHandlers.Instance), CachePolicies.Default);
                // </2>
                Console.WriteLine(HandlerInfoPrintTreeExtensions.PrintTree(EmitHandlers.Instance));
            }
        }
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen