System.Reflection.Emit / System.Type.GetConstructor

G

Guest

I have found this code snippet in the MSDN Library

[C#]
using System
using System.Threading

class Tes

static void Main()

ThreadStart threadDelegate = new ThreadStart(Work.DoWork)
Thread newThread = new Thread(threadDelegate)
newThread.Start()



class Work

public static void DoWork() {


I would like to create an assembly by Reflection.Emit that contains that lines
How do I create the line 'ThreadStart threadDelegate = new ThreadStart(Work.DoWork);'
I dont know the number and kind of types (see 'zParameters') that are required to cal
the function 'zILGenerator.Emit(..)'. Here is the a part of the code I am referring to

MethodBuilder zMethodBuilder = ..

ILGenerator zILGenerator = zMethodBuilder.GetILGenerator()

Type[] zParameters = new Type[???]
zParameters[0] = ???
zParameters[1] = ???
// etc

zILGenerator.Emit(OpCodes.Newobj, typeof(System.Threading.ThreadStart).GetConstructor(zParameters))
 
M

Mattias Sjögren

Daniele,
How do I create the line 'ThreadStart threadDelegate = new ThreadStart(Work.DoWork);'?

The easiest way to figure that out is to compile your C# code and use
ILDASM to look at what's generated:

ldnull
ldftn void Work::DoWork()
newobj instance void
[mscorlib]System.Threading.ThreadStart::.ctor(object, native int)

I dont know the number and kind of types (see 'zParameters') that are required to call
the function 'zILGenerator.Emit(..)'.

Object and IntPtr ('native int' in IL Asm)

zILGenerator.Emit(OpCodes.Ldnull);
zILGenerator.Emit(OpCodes.Ldftn, methodBuilderForDoWork);
Type[] zParameters = new Type[] { typeof(object), typeof(IntPtr) };
zILGenerator.Emit(OpCodes.Newobj,
typeof(System.Threading.ThreadStart).GetConstructor(zParameters));



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top