Skip to content

Instantly share code, notes, and snippets.

@noncom
Forked from ChadSki/gist:7992383
Created March 4, 2023 16:15
Show Gist options
  • Save noncom/d90bba286f2d8ee58ca74f342667d6a3 to your computer and use it in GitHub Desktop.
Save noncom/d90bba286f2d8ee58ca74f342667d6a3 to your computer and use it in GitHub Desktop.
Dynamically define C# value types (structs) at runtime with a dynamic assembly
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;
namespace DevConsole
{
class Program
{
static void Main(string[] args)
{
// Create assembly and module
var assemblyName = new AssemblyName("DynamicAssemblyExample");
var assemblyBuilder = AppDomain.CurrentDomain.
DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assemblyBuilder.
DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll");
// Open a new Type for definition
var typeBuilder = moduleBuilder.DefineType("MyDynamicType",
TypeAttributes.Public |
TypeAttributes.Sealed |
TypeAttributes.ExplicitLayout |
TypeAttributes.Serializable |
TypeAttributes.AnsiClass,
typeof(ValueType));
// Find MarshalAsAttribute's constructor by signature, then invoke
var ctorParameters = new Type[] { typeof(UnmanagedType) };
var ctorInfo = typeof(MarshalAsAttribute).GetConstructor(ctorParameters);
var fields = typeof(MarshalAsAttribute).GetFields(BindingFlags.Public | BindingFlags.Instance);
var sizeConst = (from f in fields
where f.Name == "SizeConst"
select f).ToArray();
var marshalAsAttr = new CustomAttributeBuilder(ctorInfo,
new object[] { UnmanagedType.ByValTStr }, sizeConst, new object[] { 5 });
var fbString = typeBuilder.DefineField(
"m_string",
typeof(string),
FieldAttributes.Public);
fbString.SetOffset(0);
fbString.SetCustomAttribute(marshalAsAttr);
var fbNumber = typeBuilder.DefineField(
"m_number",
typeof(int),
FieldAttributes.Public);
fbNumber.SetOffset(8);
var type = typeBuilder.CreateType();
bool isVal = type.IsValueType; // true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment