1

I have an API function in my application:

    <Runtime.InteropServices.DllImport("kernel32.dll", SetLastError:=True, CharSet:=Runtime.InteropServices.CharSet.Ansi, ExactSpelling:=True)>
    Private Shared Function GetProcAddress(ByVal hModule As IntPtr, ByVal procName As String) As IntPtr
    End Function

I just want to learn the pointer 'IntPtr' value of this function. How can I do it?

Note: I will show you the exact thing that I want in C++

void* fnGetProcAddress;
fnGetProcAddress = GetProcAddress;

2 Answers2

2

Well, you can continue using P/Invoke...

(Note, this is in C#, but easily convertible)

[System.Runtime.InteropServices.DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

[System.Runtime.InteropServices.DllImport("kernel32.dll")]
public static extern IntPtr GetModuleHandle(string moduleName);


var hModule = GetModuleHandle("kernel32.dll");
var procAddress = GetProcAddress(hModule, "GetProcAddress");
JerKimball
  • 16,584
  • 3
  • 43
  • 55
2

I want to get this address and write it in a BinaryStream as UInt32

This is a very troublesome plan. Short from the wrong data type, you have no guarantees whatsoever that the address you write is still valid when you read the stream:

  • The DLL might simply not be loaded when you read the stream. It does require making the LoadLibrary() call to get it in the process. So at a very minimum you'd also have to serialize the DLL path.

  • DLLs do not promise to get loaded at the exact same address again. The load address embedded in the DLL header is merely a request, it is very common that the requested address is already in use by another DLL, forcing Windows to relocate the DLL. That relocated address is not predictable. A far bigger problem is that relocation is intentionally done on modern Windows versions. A feature called Address Space Layout Randomization, enabled when the DLL was linked with the /DYNAMICBASE linker option. It is an anti-malware feature, making it intentionally hard for malware to patch code.

Surely there's a better way to do what you want to do. You however made the common mistake of not explaining your reasons, it is impossible to guess at.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • @MuhammedUğurNazlı All of the points Hans makes here are absolutely correct; while what I put above should..."sorta work", it is **not** recommended – JerKimball Jul 31 '13 at 17:08
  • Actually, I am translating c++ codes into VB.NET. And c++ codes are working very well. So if this problem is there in c++ too, it doesn't matter. – Muhammed Uğur Nazlı Jul 31 '13 at 19:32
  • This is the wrong thing to do in C++ as well. That's you've been lucky so far does not constitute proof. Especially given the drastically different VM layout of a managed program. And managed programs having ASLR turned on. – Hans Passant Jul 31 '13 at 19:37