Skip to content

Instantly share code, notes, and snippets.

@ChadSki
Last active August 16, 2023 15:45
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ChadSki/7992383 to your computer and use it in GitHub Desktop.
Save ChadSki/7992383 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