On Sep 6, 9:12 am, "Adrian" <x...@xx.xxwrot e:
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.ex e" ), "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("kern el32.dll", CallingConventi on =
CallingConventi on.Winapi, CharSet = CharSet.Auto, SetLastError =
true)]
static extern IntPtr LoadLibrary(Str ing lpFileName);
[DllImport("kern el32.dll", CallingConventi on =
CallingConventi on.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 GetWindowsDirec tory([MarshalAs(Unman agedType.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("ke rnel32.dll");
if (hLib == IntPtr.Zero)
throw new Win32Exception( );
// Get the procedure address.
IntPtr procAddress = GetProcAddress( hLib,
"GetWindowsDire ctoryA");
if (procAddress == IntPtr.Zero)
throw new Win32Exception( );
// Convert it into a delgate.
GetWindowsDirec tory getWinDir =
(GetWindowsDire ctory)Marshal.G etDelegateForFu nctionPointer(p rocAddress,
typeof(GetWindo wsDirectory));
// Set up parameters
StringBuilder winDir = new StringBuilder(( int)MAX_PATH);
// Call the delegate (which calls the function pointer)
uint retval = getWinDir(winDi r, MAX_PATH);
if (retval == 0)
throw new Exception("Cann ot determine error on non dll
import functions...");
Console.WriteLi ne(winDir);
}