Search code examples
c#pinvokefunction-pointersdllimport

Is there a way to get function pointer for extern method in C#


I want to get the function pointer (ie IntPtr) for an extern method such as:

[DllImport("DbgHelp.dll")]
static extern void SymFunctionTableAccess64(IntPtr process, ulong addrBase);

which, then also be used as a parameter for an extern method such as:

[DllImport("DbgHelp.dll")]
static extern int StackWalk64(......., IntPtr FunctionTableAccessRoutine, ....);

I know I can use LoadLibrary and then GetProcAddress, or wrap the function in a C# method and then use Marshal.GetFunctionPointerForDelegate for a function pointer. I wonder if we can retrieve the function pointer directly from P/Invoke mechanism, because, during runtime, functions will already be loaded via DllImport. Just to note, my problem is not specific to StackWalk64 or any DbgHelp.dll functions.


Solution

  • You need to use GetProcAddress to get the address of an external unmanaged function.

    There's no problem doing this. Functions are not loaded as such. Modules are loaded. Once a module has been loaded, GetProcAddress just performs a lookup in the export table of the module. If you know that the module is already loaded then you don't need to call LoadLibrary again. You can use GetModuleHandle. Not that a call to LoadLibrary presents any problem either really. If the module is already loaded, then a call to LoadLibrary simply increases the reference count of the module, and returns its handle.

    Mind you, what you are attempting doesn't look suited to p/invoke. Native code is surely more appropriate.