MichaelPidde.com

DLL Loading

Due to a desire to rewrite certain parts of my game code or potentially start working on a new version altogether with different mechanics, I took some time this evening to throw together an example of importing functions from a DLL which is barely more than a Hello World, but allowed me to see how simple the process really is. In this example I leveraged some Win32 API functions to get files in a particular directory.

This is the content of my Win32API.cpp module which will get compiled into a DLL:

#define Export __declspec(dllexport)

#include <Windows.h>
#include <stack>
#include <string>
#include <vector>

// Adapted from: 
// https://stackoverflow.com/questions/67273/how-do-you-iterate-through-every-file-directory-recursively-in-standard-c#answer-67336
// Not using wstring_t (WIN32_FIND_DATA, FindFirstFile, FindNextFile, wcscmp)

Export std::vector<std::string> GetDirectoryFiles(std::string dir, std::string mask) {
    std::vector<std::string> files;
    
    HANDLE handle = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATAA find;
    std::string spec = dir + "\\" + mask;

    handle = FindFirstFileA(spec.c_str(), &find);
    if(handle == INVALID_HANDLE_VALUE) {
        return files;
    }

    do {
        if(strcmp(find.cFileName, ".") != 0 && strcmp(find.cFileName, "..") != 0) {
            if((find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY) {
                files.push_back(find.cFileName);
            }
        }
    } while(FindNextFileA(handle, &find) != 0);

    FindClose(handle);

    return files;
}

The code that imports and uses that function is pretty straightforward:

#define Import __declspec(dllimport)

#include <iostream>
#include <string>
#include <vector>

Import std::vector<std::string> GetDirectoryFiles(std::string dir, std::string mask);

void main() {
    std::vector<std::string> files = GetDirectoryFiles("C:\\Windows", "*");

    for(std::string file : files) {
        std::cout << file << std::endl;
    }
}

And, because I don't particularly like make files (though I'm sure I'd probably like Premake alright), here's a simple batch file build script:

@echo off

rd /S /Q lib
mkdir lib
cl /nologo /EHsc /LD /Fe"lib/Win32API.dll" Win32API.cpp

cl /nologo /EHsc /Fe"run.exe" main.cpp ^
/link /LIBPATH:lib ^
Win32API.lib ^
/SUBSYSTEM:CONSOLE

rd /S /Q bin
mkdir bin
copy lib\Win32API.dll bin
copy run.exe bin

Finally, some actual program output when run:

D:\Code\cpp\dlls>bin\run.exe
AsCDProc.log
comsetup.log
DDACLSys.log
Directx.log
DPINST.LOG
DtcInstall.log
iis.log
Inst.log
Inst_AsModelCopy.log
Inst_CMD.log
Inst_Device.log
mplaynow.log
PFRO.log
setupact.log
setuperr.log
WindowsUpdate.log