Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection.Emit unsafe code

I'm doing some hacking with Reflection Emit in F#. I'm trying to do the equivalent of this C# code:

var ass = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("Test"), AssemblyBuilderAccess.RunAndSave);
var mb = ass.DefineDynamicModule("Test", "Test.dll", false);
var t = mb.DefineType("Foo", TypeAttributes.Public, typeof(ValueType));
t.DefineField("foo", typeof(int*), FieldAttributes.Public);
t.CreateType();
ass.Save("Test.dll");

The line in particular is the definefield line. In F# the closest I can get is

let f = t.DefineField("foo", (typeof<nativeptr<int>>), FieldAttributes.Public)

However the compiled field ends up compiled to of type IntPtr instead of int*.(Note its an IntPtr for nativeint or any other type too)

Additionally, I'd like to be able to use the struct I defined defined programatically and have a Foo* in another struct, but obviously I'm not able to use typeof in that case (in either C# or F#). Is there a way to define a field as Foo* from the Type/TypeBuilder?

Before anyone points out that this is all potentially insane (and I agree), it is for a fun project for myself to figure out how crazy I can generate code that C# mignt not let me :)

like image 597
neil danson Avatar asked Mar 21 '26 15:03

neil danson


1 Answers

I believe ilsigptr<int> is the F# counterpart to C#'s int*.

See also:

  • Don Syme's blog, dead link, see archived copy
  • ilsigptr<'T> on MSDN, dead link, see archived copy
  • F# sources on GitHub
like image 87
Daniel Avatar answered Mar 24 '26 04:03

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!