Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if DLL entry point exists in C# without calling the function

Tags:

c#

pinvoke

I'm using OpenTK OpenGL wrapper. Since it loads OpenGL dll (or .so on Linux) it contains a lot of DLL imported functions.

The trouble is, some drivers don't export all of the functions. Is there a way to check if the entry point exists? I need to do this since actually calling the function on systems that have it will cause a crash if not done in the proper sequence. So catching EntryPointNotFound exception doesn't work in my case.

like image 667
Latifer Avatar asked Jul 03 '11 05:07

Latifer


People also ask

Does a DLL have an entry-point?

A DLL can have a single entry-point function. The system calls this entry-point function at various times, which I'll discuss shortly. These calls are informational and are usually used by a DLL to perform any per-process or per-thread initialization and cleanup.

What is DLL entry-point?

A DLL can optionally specify an entry-point function. If present, the system calls the entry-point function whenever a process or thread loads or unloads the DLL. It can be used to perform simple initialization and cleanup tasks.

Does a DLL need DllMain?

The DllMain function is an optional method of entry into a dynamic-link library (DLL). If the function is used, it is called by the system when processes and threads are initialized and terminated, or upon calls to LoadLibrary and FreeLibrary.


1 Answers

You can P/Invoke the LoadLibrary and GetProcAddress calls from Win32:

[DllImport("kernel32", SetLastError=true)]
static extern IntPtr LoadLibrary(string lpFileName);

[DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
static extern UIntPtr GetProcAddress(IntPtr hModule, string procName);

Use LoadLibrary to load the module and get the handle, and GetProcAddress to get a function pointer to the entry point. If the latter returns an error, the entry point doesn't exist.

like image 111
Kevin Hsu Avatar answered Oct 19 '22 21:10

Kevin Hsu