Create Instance

349 views
Skip to first unread message

Dario Quintana

unread,
May 31, 2007, 1:40:35 PM5/31/07
to mono-...@googlegroups.com
Hi people,

With Cecil can I create a object instance from a type? From a
TypeDefinition perhaps?

Regards
--
Dario Quintana
http://blog.darioquintana.com.ar

Jb Evain

unread,
May 31, 2007, 1:48:42 PM5/31/07
to mono-...@googlegroups.com
Hi Dario,

On 5/31/07, Dario Quintana <uoo...@gmail.com> wrote:
> With Cecil can I create a object instance from a type? From a
> TypeDefinition perhaps?

No, you can't directly create an instance of a Cecil type, as the
Cecil tree is just a view over what contains an assembly, but it's not
tied to the runtime as a System.Type is.

So the short answer is no.

The long answer is, you could create a type, if you can load the
assembly created with Cecil in the runtime, and get its corresponding
System.Type. But it's an heavy process to load an assembly, so you may
want to work only with System.Reflection and System.Reflection.Emit if
you want to dynamically create instances of types emitted at runtime.

--
Jb

Ayende Rahien

unread,
May 31, 2007, 4:21:32 PM5/31/07
to mono-...@googlegroups.com
I don't see how loading an assembly from cecil is any different than loading assembly from SRE.
Any pointers?

Ayende Rahien

unread,
May 31, 2007, 4:22:26 PM5/31/07
to mono-...@googlegroups.com
Here is a way to output the create instruction, if this is what you meant.

cil .InsertBefore( ins,cil. Create(OpCodes. Newobj,
                                      t .Module.Import (typeof(ObjectDisposedException ).GetConstructors()[ 0]) ))

On 5/31/07, Dario Quintana <uoo...@gmail.com > wrote:

Jb Evain

unread,
May 31, 2007, 4:54:30 PM5/31/07
to mono-...@googlegroups.com
Hey,

On 5/31/07, Ayende Rahien <aye...@ayende.com> wrote:
> I don't see how loading an assembly from cecil is any different than loading
> assembly from SRE.
> Any pointers?

Well, loading an assembly from Cecil doesn't load the assembly in the
runtime. Which means that there is no relation between a
Mono.Cecil.TypeDefinition and a System.Type.

Which also means, and I think that it was the question, that there is
no way to Activator.CreateInstance () a Mono.Cecil.TypeDefinition.

But of course, as your code suggests, you can emit whatever you want
using Cecil, including instantiating types in the CIL stream.

--
Jb

Dario Quintana

unread,
May 31, 2007, 11:04:15 PM5/31/07
to mono-...@googlegroups.com
Thanks Jb & Oren, I gonna try to do something that you did tell me.

Regards

On 5/31/07, Jb Evain <j...@nurv.fr> wrote:
>

Reply all
Reply to author
Forward
0 new messages