C#C
C#13mo ago
Richard01_CZ

Issues loading DLL

I'm trying to load a C++ DLL and use it's function GetEngineVersion to get the engine version to find out installed version of the game. I need it to be loaded from Properties.Settings.Default.InstallPath, "LS3DF.dll". I get an error 126 and can't fix it.
I can use the DLL function if i use [DllImport] but that only uses fixed path.

I need it to be dynamic and load the path from InstallPath setting. i'm using .NET Framework 4.7.2, platform is set to x86

here is a code for a button i use for testing:
private void Button_Click(object sender, EventArgs e)
{
    try
    {
        // find dll
        string dllPath = System.IO.Path.Combine(Properties.Settings.Default.InstallPath, "LS3DF.dll");

        // load dll
        IntPtr hModule = LoadLibrary(dllPath);
        if (hModule == IntPtr.Zero)
        {
            System.Windows.Forms.MessageBox.Show("Failed to load the DLL.");
            return;
        }

        // pointer
        IntPtr pAddressOfFunction = GetProcAddress(hModule, "GetEngineVersion");
        if (pAddressOfFunction == IntPtr.Zero)
        {
            System.Windows.Forms.MessageBox.Show("Failed to get the address of the function.");
            return;
        }

        // delegate
        var getEngineVersion = (GetEngineVersionDelegate)Marshal.GetDelegateForFunctionPointer(pAddressOfFunction, typeof(GetEngineVersionDelegate));

        // call function
        int engineVersion = getEngineVersion();
        System.Windows.Forms.MessageBox.Show($"Engine Version: {engineVersion}");
    }
    catch (DllNotFoundException ex)
    {
        System.Windows.Forms.MessageBox.Show($"DLL not found: {ex.Message}");
    }
    catch (EntryPointNotFoundException ex)
    {
        System.Windows.Forms.MessageBox.Show($"Method not found in DLL: {ex.Message}");
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show($"An error occurred: {ex.Message}");
    }
}
Was this page helpful?