3

I have a C++ DLL which I'm importing into a C# project using a DllImported LoadLibrary.

class Program
{
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern IntPtr LoadLibrary(string dllToLoad);

    static void Main(string[] args)
    {
        IntPtr library = LoadLibrary(@"MyDll.dll");
        if (library == IntPtr.Zero)
        {
            var err = Marshal.GetLastWin32Error();
            throw new Exception($"Library load error, code {err}");
        }
    }
}

I now want to enumerate over the functions exported from this DLL. I've seen this question, but it applies to C++, and I'm not sure how I could do the same in C#.

Parsing the output of dumpbin /exports would probably work, but I'd like to know if there's a more concrete way of doing it first.

How can I obtain a list of all of the functions in the C++ DLL from C#?

Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78
  • 1
    If you don't want to shell out to an external process and parse its output, then manually parsing the DLL's PE header to enumerate its EXPORTS table directly is the only way. If you don't want to do the work yourself, try looking for a 3rd party library that does it for you. – Remy Lebeau Jun 05 '18 at 17:16

2 Answers2

4

After Remy Lebeau's comment pointed me in the right direction, I had a look for PE parsers and found PeNet. It does the job really well, and reveals plenty of information beyond just the exported functions.

It's on NuGet, so you can just install it, add using PeNet to the top of the file, and then use code like this:

var pe = new PeFile(@"MyDll.dll");
var functions = pe.ExportedFunctions.Select(x => x.Name).ToList();
Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78
0

There is a great article on how to read the PE Headers from a file here: https://blogs.msdn.microsoft.com/kstanton/2004/03/31/exploring-pe-file-headers-using-managed-code/

You will want to examine the .edata section to find the exports: https://msdn.microsoft.com/en-us/library/windows/desktop/ms680547(v=vs.85).aspx#the_.edata_section__image_only_

mcoill
  • 41
  • 5