Loadlibrary не загружает dll
This is done in order to call Dll1.dll which was created with the functionality to send mail to my own mail server. The above code runs and exits,and no mail is sent.
And i also placed the Dll1.dll in the same folder as UseDll1.
EDIT: I added the Dll1.dll into the system32 folder.
Don't put it in the system32. It's not suppose to go there and you're just hacking around without solving the real problem.
i read in the internet wherein they are saying that there are chances that the dll is not able to load because it also has some dependencies,but in that case function1 would return NULL..wht say??
if the variable myDll is not null but GetProcAddress return null, check whether the dll is exporting required function. do take note of "name mangling" if you are exporting as c++
1 Answer 1
Since you mention that your application is 32-bit, the DLL that you're loading must also be 32-bit.
The likely reason LoadLibrary() is failing is that you're running a 64-bit edition of Windows, but your printer driver has erroneously installed its 32-bit DLL in question into the System32 folder instead of the SysWOW64 folder.
Some background: On 64-bit editions of Windows, 64-bit DLLs go in System32 folder, and 32-bit DLLs go in the SysWOW64 folder. I know it sounds like it should be the other way around, but don't let the names confuse you; the folders are named like that are for backward-compatibility reasons. The SysWOW64 folder is supposed to be transparent to applications: Windows has a feature called file-system redirection that makes it possible for 32-bit applications to load 32-bit DLLs by specifying the System32 folder (just as they always have) even though the DLLs are actually inside SysWOW64 .
On the other hand, LoadLibrary() will simply refuse to load a DLL that's been placed inside the wrong folder. This is the behavior you're probably seeing.
The real solution to your problem is to contact the printer manufacturer and inform them that their driver installer is putting its DLLs into the wrong folder under 64-bit editions of Windows. If they ever fix this, your application will start working correctly without any changes to your existing code.
In the meantime, you should be able to work around your problem by doing this:
- Before you attempt to load the DLL, copy the DLL from %windir%\Sysnative to some known folder that you have control over. (I suggest that you create a uniquely named folder inside %TEMP% and copy the DLL into that folder). Note: Sysnative is a special alias that maps to the native system folder, which is System32 under 64-bit editions of Windows.
- Call LoadLibrary() and pass it the path of the copy of the DLL that you made in step 1.
- When you're done using the DLL, unload it and delete the copy you made in step 1.
The above workaround might not work if you need to support 64-bit Windows XP, since the Sysnative alias is documented to work only on Windows Vista or later. An alternative workaround is to manually bypass file-system redirection:
- Temporarily disable file-system redirection by calling Wow64DisableWow64FsRedirection() . This will allow your application to see what's really in System32 .
- Copy the DLL from System32 to some known folder that you have control over.
- Reenable file-system redirection by calling Wow64RevertWow64FsRedirection() .
- Call LoadLibrary() and pass it the path of the copy of the DLL that you made in step 2.
- When you're done using the DLL, unload it and delete the copy you made in step 2.
Note that if you're thinking of calling Wow64DisableWow64FsRedirection() to get LoadLibrary() to work without having to copy the DLL, don't bother: LoadLibrary() doesn't pay attention to that setting. (I actually tested it.)
7 Answers 7
Have you verify that you have all external dependencies for "DLL1.dll" ?
LoadLibrary will fail even if any of the indirect linked-library is not available.
In my dll calling experience, I had same problem. I did everything for giving path rightly but my library can not be loaded. Firstly I thought my dll had error, but nothing solved my problem at start. I advice doing below step for friends who think their project written rightly but still having same problem:
- Go to your DLL project and assure that you selected Multi-threaded Debug instead of Multi-thread(Debug) DLL(don't use dll because it uses some function from dll instead of embedding them inside) as runtime library(specially for debug mode). You can see runtime library selection under Property>Configuration Property>C/C++>Code Generation.
- After our DLL file is ok, we must ensure that our project uses right platform. If our dll uses x64, our project have to use x64. You can control it from configuration manager and you can select right one from platform box.
After building project with right configuration, it is working now.
Thank you very much, your web page helped me a lot :) I only had to use tchar.h to make it working. You can see it in the rest of the answer.
Just because the code runs and exits doesn't mean it's right! Are you sure that:
- The DLL is being correctly loaded (myDll!=null)
- GetProcAddress is returning a valid pointer (function1!=null)
You should step through the code in a debugger to make sure all this is happening and that the code does get to function1(). If it does then my guess would be that your email function has a bug in it.
по getlasterror получаю ошибку - 14001 = Приложение не было запущено, поскольку оно некорректно настроено. Повторная установка приложения может решить данную проблему.
или так вызываю
по getlasterror получаю ошибку 126 = Не найден указанный модуль.
по моему дело в unicode.
я пишу в ms vs ultimate 2010
Ошибка LoadLibrary
В папке TEMP лежит dll, которую я хочу подгрузить, но при вызове функции LoadLibrary возвращается.
[Решено] LoadLibrary
Здраствуйте. Сделал динамическую библиотеку в студии, загружал ее там же в консольное приложение с.
LoadLibrary возвращает 0
Добрый вечер. Прошу помощи у знающих людей. Есть нативная dll,которую нужно использовать в.
LPCWSTR pbuft = _T("C:\\Documents and Settings\\er\\Мои документы\\Visual Studio 2010\\Projects\\loaddll4\\Debug\\dll4.dll");
HMODULE hdll1 = LoadLibrary(pbuft);
помойму всё делается вот так
а ещё про первую запись забыл сказать когда компилируешь из среды все файлы которых должны запускаться вместе с exe должны лежать вот в этой папке
C:\Documents and Settings\er\Мои документы\Visual Studio 2010\Projects\loaddll4\loaddll4\dll4.dll
Рабочая директория и директория ехе-файла в MSVC по умолчанию не совпадают. На вкладке Debug пропиши рабочую директорию туда же, куда и ехе-файл.
Добавлено через 36 секунд
Так а что это вообще за шняга? О_о
компилятор dllmain создает автоматически или как
Добавлено через 2 часа 13 минут
вот так тоже ничего не входит
я вот так пытаюсь скомпилировать он мне даже говорит что
1>C:\Documents and Settings\er\Мои документы\Visual Studio 2010\Projects\dllt1\Debug\dllt1.dll : fatal error LNK1169: обнаружен многократно определенный символ - один или более
1>
то есть dllmain уже определена (если ее убрать все скомпилируется)
и компилировал я вот так консольное приложение - dll
Но там еще есть "пустой проект" и "экспорт символов" это зачем.
GDI+: подгрузка функций через LoadLibrary(gdiplus.dll")
Есть приложение, оно компилится. В нем есть динамическая линковка GDI+: HMODULE hGDIPlsu =.
LoadLibrary не загружает dll
Здравствуйте. Вот такой код HINSTANCE hLib; int Error = GetLastError(); hLib =.
Вызов LoadLibrary из DLL
Есть две Dll - DLL_A и DLL_B Использую MS Visual Studio 2010 C++(MFC) Из основной программы.
Добавлено через 56 минут
Попробовал загрузить и DLL успешно загрузилась.
Может вы кривой путь указали?
Или пытаетесь сделать 64х битный проект?
Путь я правильно указал, проверял на своей созданной dll в той же папке. Действительно, проблема, наверное, заключалась в том, что я создавал проект на 64х бит. Не подскажите как мне сделать 32х битный проект? Пользуюсь Visual Studio 2022. Если я правильно понимаю, то поменять битность проекта это чуть левее кнопки "Локальный отладчик Windows", но там только х64 и х86.
Как-то странно, на вашем снимке экрана в консоле нет ни строки про ошибку загрузки, ни строки про успешную загрузку.
Не там смотрю, всё есть.
Не знаю в чём дело может быть, но у меня DLL точно грузится для платформы x86
Пытаюсь открыть отладку, выскакивает такая ошибка. Может с этим связанно. Такого файла, вроде-как у меня нет даже.
Это отдельный файл с отладочными символами. Он нужен при отладке, что бы ассемблерный код сопоставить с исходными файлами. Наличие или отсутствие этого файла не влияет на штатную работу программы.
Смотрите, у меня работает загрузка вашей DLL в древней студии VS2005. При попытке сделать тоже самое в более новой студии (2015) сыпятся какие-то исключения. Возможно это что-то значит, но я не знаю что именно)
JuustPush, 2010 и 2012 студии то же выдают исключения во время загрузки.
Если есть исходники библиотеки, то можно попробовать собрать её под новой студией.
Вообще странная ситуация, всегда полагал что DLL от разных студийных компиляторов совместимы.
Исходников, увы, нет. Думаю может как вариант попробовать на билдере 6 попытаться открыть
Добавлено через 1 час 19 минут
Скачал VS2005. На нём библиотека законнектилась, как Вы и сказали. Жаль на самом деле, что с 2022 так же не прокатило(
Qt & MemoryModule - Загрузка DLL из памяти без LoadLibrary
Пишу программу и возникла резкая необходимость сохранить тело DLL библиотеки (тоже написанной мной).
LoadLibrary 64bit? Подключение созданной DLL к своему приложению.
Всем доброго времени суток. Столкнулся с проблемой подключения созданной DLL к своему приложению.
ошибка вызова LoadLibrary (name.dll) - не найден указаный модуль
Здравствуйте. Написал dll, ее вызывает сторонняя программа, проблема в том что на другом.
LoadLibrary, GetProcAddress: как правильно подгружать функцию из библиотеки?
Подскажите пожалуйста, как правильно подгружать функцию из библиотеки? пытаюсь так, не.
Ошибка после создания нового .lib из .dll (библиотека bass.dll)
Скачал библиотеку bass.dll (.dll, .h, .lib) и при подключении либы через pragma comment компилятор.
Пытаюсь сделать динамическую загрузку dll. Dll-библиотека не подает признаков жизни
Здравствуйте. У меня такое дело, я пытаюсь создать в своей программе динамическую загрузку.
The requested lookup key was not found in any active activation context.
Вообще мне надо liblapack.dll загрузить - ее пробовал и просто на диск D класть, и в system32, VS от администратора запускал - всегда ошибка 126 и hLib нулевой.
Как узнать какие dll Загружает процесс или dll
Проблема вот в чем: Нужно определить какие dll загружает процесс. Есть ли такая функция WinAPI?
Qt & MemoryModule - Загрузка DLL из памяти без LoadLibrary
Пишу программу и возникла резкая необходимость сохранить тело DLL библиотеки (тоже написанной мной).
Может путь надо правильный указать? Не C:\Windows\System32\, а например C:\Windows\Sysnative\ или c:\Windows\SysWOW64\.
Или вообще положить вашу liblapack.dll в папку с программой.
Основная проблема при ручной загрузке DLL в отсутствии полноценной диагностики ошибок. При статичном связывании виндовс детально сообщает о причинах невозможности загрузить DLL.
DLL может не грузиться по разным причинам. Наиболее частые.
1) Несовместимость разрядности. Комбинации 32 битной и 64 битной реализации.
2) Отсутствие дополнительных DLL. Ведь DLL может быть статична связана с другими DLL. В этом случае при её загрузке автоматически будет производиться загрузка других DLL и если одной из них не найдётся, то и основная DLL не будет загружена. Ради эксперимента можно сделать тестовый проект, в котором сделать статичное связывание. При его запуске операционка сообщит о причинах отказа в загрузке. Можно попытаться найти все зависимости с помощью различных утилит, вроде "dependency walker", но с тестовым проектом проще, на мой взгляд.
Может путь надо правильный указать? Не C:\Windows\System32\, а например C:\Windows\Sysnative\ или c:\Windows\SysWOW64\.
Или вообще положить вашу liblapack.dll в папку с программой.
В папку с программой первым делом положил. Пути беру из свойств файла, вроде не должно быть ошибки.
Добавлено через 13 минут
Это для которого нужен файл lib - библиотека импорта? (извиняюсь, если не так формулирую - не очень в курсе этой темы)
Ситуация такая:
Нужно решить СЛАУ - решил заморочиться с lapack.
Среди вариантов установки взял тот, где скачиваются готовые lib и dll, однако не зашло - постоянные ошибки во внутренних функциях, не знаю как что проследить.
Решил использовать dll с ручной загрузкой, чтобы напрямую, а здесь фигня уже при загрузке LoadLibrary.
Ладно, может, liblapack.dll ломаная - решил загрузить гарантированно рабочие: выбрал user32.dll и hal.dll (просто на них в инете ссылки увидел первыми).
в итоге при загрузке hal.dll хэндл нулевой, user32.dll при загрузке LoadLibraryA выдает ненулевой хэндл, но LastError дает ошибку - т.е. х.з. что там загрузилось.
Вот такая строка заставляет меня подумать, что изначально вы написали без LPCTSTR и получили от компилятора ругань на несовместимые типы аргумента. Вместо того, что бы изменить настройки проекта на multichar, добавить L перед кавычками или явно указать функцию LoadLibraryA, вы сделали явное преобразование от char к wchar_t, что устранило ругань компилятора, но интерпретация строки в процессе исполнения теперь приводит к ошибке. Эксперименты с таким преобразованием можно считать ошибочными.
Что касается ошибки при успешном исполнении, то я сомневаюсь в корректности такой проверки. В случае успешного выполнения вроде бы ни где не оговаривается, что последняя ошибка должна быть сброшена. Более того, по некоторым соображениям сбрасывать ошибку не очень логично. Могу предположить, что код ошибки вы видите не от успешного вызова функции, а от какого-то неудачного вызова функции, который предшествовал успешному.
Думаю, что правильнее будет разобраться с ошибками при линковке с lib, а не пытаться сделать динамическую загрузку.
I'm trying to load a DLL that was installed with a printer driver in the C:\Windows\System32\ folder with the following code:
GetLastError() is reporting that "The specified module could not be found". If I move the DLL outside of the System32 folder (C:\SomeFolder\MagAPI.dll for example) then it will load fine so it doesn't seem like it's a problem with the DLL itself. Is there some weird Windows security feature that might be blocking my application from loading it? That's the only thing I can think of but I can't find any definitive answers.
Here's the debug output from ShowSnaps, which shows where it's failing:
What version of Windows are you on? You may need admin rights to see the contents of System32. Quick test you can do is right click and run your application as admin (win vista and above I think) and if it works then that's the issue.
@JesusRamos I've already confirmed that the DLL is in that folder at that exact path, if that's what you're asking.
No I'm asking you to confirm whether it's a permissions issue or not. Accessing System32 sometimes from code requires admin rights on the running application even just to read a file.
Doesn't seem to be the issue. I just tried running the application as admin and it's still failing the exact same way. I'm on Windows 7 64-bit btw. It's a 32-bit application though.
When you move the file "out" of system32, where do you move it to? Is it possible that library has import-dependencies that are satisfied when its in the folder where it loads correctly, and not satisfied when residing in system32. Can you do a dependency walk on it (with depends.exe , for example, from MS) and see what might be missing. Its a possibility, but judging by your ShowSnaps output, the file name itself is simply not resolving. How odd.
Читайте также: