Click to See Complete Forum and Search --> : CreateThread API.... problem !!!


endofcsharp
June 21st, 2006, 05:59 PM
Hi everybody
I want to write some code with C# using Threading functionality
I want to use Windows API's for that (not System.Threading namespace)

to use that, I have to use these API :

[DllImport("kernel32.dll", SetLastError=true)] static extern int CreateThread (ref SECURITY_ATTRIBUTES lpThreadAttributes,
int dwStackSize, ref int lpStartAddress,
ref object lpParameter, int dwCreationFlags,
ref int lpThreadId)


As you can see, I need to set the parameter lpStartAddress that points to the Method that the thread must execute it

How can I get the method address ?

in VB.net therese an operator called AddressOf that returns the address of method ?

Is there anything like that in C#?

boudino
June 22nd, 2006, 02:22 AM
If you use unsafe code (method declaration or statement modifier keyword), you can work with pointers similar to C/C++ and obtain address with & operator. But it is neccessary to leave safe managed code?

endofcsharp
June 22nd, 2006, 02:34 PM
Problem Solved !!!

delegate void dl();


Main()
{
dl d = new dl(Test);

IntPtr pointer = Marshal.GetFunctionPointerForDelegate(d);

SECURITY_ATTRIBUTES sec=new SECURITY_ATTRIBUTES();

int Handle = CreateThread(ref sec, 1024, pointer.ToInt32(), 0, 0, 0);
}



This can Only used on .Net 2.0

endofcsharp
June 22nd, 2006, 02:35 PM
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Text;

namespace TestThreadAPI
{
class Program
{
[DllImport("kernel32.dll")]
private static extern int CreateThread(ref SECURITY_ATTRIBUTES lpThreadAttributes, int dwStackSize,
int lpStartAddress,int lpParameter, int dwCreationFlags, int lpThreadId);

[StructLayout(LayoutKind.Sequential)]
private struct SECURITY_ATTRIBUTES
{
internal int nLength;
internal int lpSecurityDescriptor;
internal int bInheritHandle;
}

delegate void dl();

static void Main(string[] args)
{
int addr = 0;

dl d = new dl(Test);

IntPtr pointer = Marshal.GetFunctionPointerForDelegate(d);

SECURITY_ATTRIBUTES sec=new SECURITY_ATTRIBUTES();

int Handle = CreateThread(ref sec, 1024, pointer.ToInt32(), 0, 0, 0);


Console.ReadLine();
}

public static void Test()
{
Console.WriteLine("Executing Thread");

Console.WriteLine("Terminating Thread");
Console.WriteLine("___________________________________________");
}
}
}