On Sep 6, 9:12 am, "Adrian" <x...@xx.xxwrote:
Could someone please translate the code below into C#?
Please also tell me the libraries I might need.
Many thanks,
Adrian.
int main()
{
(GetProcAddress( LoadLibrary( "krnl386.exe" ), "exitkernel" ))();
return( 0 );
}
First, this is C, not VB. Does this work if you compile with a C
compiler? Why do you NEED to have it in C#?
You need to add the appropriate DllImport methods. THe "standard" way
would be something like:
[DllImport("kernel32.dll", CallingConvention =
CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError =
true)]
static extern IntPtr LoadLibrary(String lpFileName);
[DllImport("kernel32.dll", CallingConvention =
CallingConvention.Winapi, CharSet = CharSet.Ansi, SetLastError =
true)]
static extern IntPtr GetProcAddress(IntPtr hModule, String
lpEntryPoint);
Then you need to add a delegate definition so that you can call the
function returned from GetProcAddress.
IMPORTANT NOTE: I believe that you can ONLY convert __stdcall function
pointers into delegates.
Something like:
delegate uint GetWindowsDirectory([MarshalAs(UnmanagedType.LPStr)]
StringBuilder lpBuffer, uint uSize);
const uint MAX_PATH = 260;
Then you need to call the functions, something like this:
static void Main(string[] args)
{
// Get the dll you need to load. Note that krnl386.exe doesn't
want to load this way.
IntPtr hLib = LoadLibrary("kernel32.dll");
if (hLib == IntPtr.Zero)
throw new Win32Exception();
// Get the procedure address.
IntPtr procAddress = GetProcAddress(hLib,
"GetWindowsDirectoryA");
if (procAddress == IntPtr.Zero)
throw new Win32Exception();
// Convert it into a delgate.
GetWindowsDirectory getWinDir =
(GetWindowsDirectory)Marshal.GetDelegateForFunctio nPointer(procAddress,
typeof(GetWindowsDirectory));
// Set up parameters
StringBuilder winDir = new StringBuilder((int)MAX_PATH);
// Call the delegate (which calls the function pointer)
uint retval = getWinDir(winDir, MAX_PATH);
if (retval == 0)
throw new Exception("Cannot determine error on non dll
import functions...");
Console.WriteLine(winDir);
}