Russian Qt Forum
Сентябрь 24, 2024, 12:18 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
  Начало   Форум  WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  

Страниц: [1]   Вниз
  Печать  
Автор Тема: И сново о dll !  (Прочитано 8615 раз)
Nalsur1982
Гость
« : Сентябрь 10, 2008, 10:58 »

Доброе всем!
Пытаюсь освоить dll в qt и никак  Злой
Собираю пример из книги Шлее Qt4. Все собираеться, но не работает и пишет что библиотека не грузиться. И в Ubuntu пробовал и в Windows.
Помогите разобраться!

DLL.pro
Код:
TEMPLATE = lib
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
# Input
HEADERS += dynlib.h
SOURCES += dynlib.cpp
CONFIG +=dll

dynlib.h
Код:
#include <QString>

extern "C" {
    QString oddUpper(const QString& str);
}

dynlib.cpp
Код:
#include "dynlib.h"

// ----------------------------------------------------------------------
QString oddUpper(const QString& str)
{
    QString strTemp;

    for (int i = 0; i < str.length(); ++i) {
        strTemp += (i % 2) ? str.at(i) : str.at(i).toUpper();
    }

    return strTemp;
}

Application.pro
Код:
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .

# Input
SOURCES += main.cpp

main.cpp
Код:
#include <QtGui>

// ----------------------------------------------------------------------
int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    QLabel       lbl("this is the example text");
    QLibrary     lib("DLL");

    typedef QString (*Fct) (const QString&);
    Fct fct = (Fct)(lib.resolve("oddUpper"));
    if (fct) {
        lbl.setText(fct(lbl.text()));
    }
    lbl.show();

    return app.exec();
}

WinXP SP2 Qt4.4 VS2008 и Ubuntu
Записан
ритт
Гость
« Ответ #1 : Сентябрь 10, 2008, 11:05 »

> QLibrary     lib("DLL");
"DLL" - это название твоей либы?
Записан
Nalsur1982
Гость
« Ответ #2 : Сентябрь 10, 2008, 11:30 »

да DLL.dll
Записан
pastor
Administrator
Джедай : наставник для всех
*****
Offline Offline

Сообщений: 2901



Просмотр профиля WWW
« Ответ #3 : Сентябрь 10, 2008, 12:03 »

Советую почитать темы по строке поиска "dllexport"
Записан

Integrated Computer Solutions, Inc. (ICS)
http://www.ics.com/
Alex03
Гость
« Ответ #4 : Сентябрь 10, 2008, 12:10 »

Для винды нет dllexport
Для oddUpper() нет extern "C" в cpp файле (dynlib.h в данном случае вообще не нужен)

Далее пути к DLL и т.д.
В винде должны быть что то из:
Цитировать
If SafeDllSearchMode is 1, the search order is as follows:
1. The directory from which the application loaded.
2. The system directory. Use the GetSystemDirectory function to get the path of this directory.
3. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
4. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
5. The current directory.
6. The directories that are listed in the PATH environment variable.
If SafeDllSearchMode is 0, the search order is as follows:
1. The directory from which the application loaded.
2. The current directory.
3. The system directory. Use the GetSystemDirectory function to get the path of this directory.
4. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
6. The directories that are listed in the PATH environment variable.



В линуксе смотри:
man ldconfig
man ld
Переменные окружения LD_LIBRARY_PATH, LD_PRELOAD
фйлы типа /etc/ld.so.conf
Записан
Nalsur1982
Гость
« Ответ #5 : Сентябрь 10, 2008, 12:53 »

Исправил, но не работает!  Непонимающий
DLL.dll скопировал в папку с приложением. Может надо создать папку plugins?
Все собралось без ошибок, но при запуске приложения результат=0.

DLL.pro
Код:
TEMPLATE = lib
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
CONFOG +=dll

# Input
HEADERS += dynlib.h
SOURCES += dynlib.cpp

dynlib.h
Код:
#ifdef Q_OS_WIN
#define LIB_EXPORT __declspec(dllexport)
#else
#define LIB_EXPORT
#endif

#include <QString>

LIB_EXPORT QString oddUpper(const QString& str);

dynlib.cpp
Код:
#include "dynlib.h"

QString oddUpper(const QString& str)
{
    QString strTemp;

    for (int i = 0; i < str.length(); ++i) {
        strTemp += (i % 2) ? str.at(i) : str.at(i).toUpper();
    }

    return strTemp;
}
Записан
pastor
Administrator
Джедай : наставник для всех
*****
Offline Offline

Сообщений: 2901



Просмотр профиля WWW
« Ответ #6 : Сентябрь 10, 2008, 14:46 »

А что пишет QLibrary::errorString при попытке загрузки библиотеки?
Записан

Integrated Computer Solutions, Inc. (ICS)
http://www.ics.com/
pastor
Administrator
Джедай : наставник для всех
*****
Offline Offline

Сообщений: 2901



Просмотр профиля WWW
« Ответ #7 : Сентябрь 10, 2008, 14:50 »

Собственно говоря в ассистанте все написано как экспортировать фунцию:

Цитировать
The symbol must be exported as a C function from the library. This means that the function must be wrapped in an extern "C" if the library is compiled with a C++ compiler. On Windows you must also explicitly export the function from the DLL using the __declspec(dllexport) compiler directive, for example:

Код:
extern "C" MY_EXPORT int avg(int a, int b)
{
    return (a + b) / 2;
}

Цитировать
with MY_EXPORT defined as

Код:
#ifdef Q_WS_WIN
#define MY_EXPORT __declspec(dllexport)
#else
#define MY_EXPORT
#endif
Записан

Integrated Computer Solutions, Inc. (ICS)
http://www.ics.com/
Nalsur1982
Гость
« Ответ #8 : Сентябрь 10, 2008, 15:17 »

Пишет что не может найти
Записан
Nalsur1982
Гость
« Ответ #9 : Сентябрь 11, 2008, 08:19 »

Может кто-нибудь выложит или вышлет рабочий пример с одной функцией и с классом для Windows и Ubuntu? Буду крайне благодарен! ruslan_i<dog>list<point>ru.
Записан
pastor
Administrator
Джедай : наставник для всех
*****
Offline Offline

Сообщений: 2901



Просмотр профиля WWW
« Ответ #10 : Сентябрь 11, 2008, 11:04 »

Пишет что не может найти

Неможет найти что?
Записан

Integrated Computer Solutions, Inc. (ICS)
http://www.ics.com/
Nalsur1982
Гость
« Ответ #11 : Сентябрь 11, 2008, 11:59 »

Точно строку привести не могу, так как дома делал. Но приблизительно не может найти директорию или файл (на Ubuntu).
И еще почему на Ubuntu создаеться 4 файла:lib.so, lib.so.1.0 или что-то вроде? И какую использовать?
Записан
pastor
Administrator
Джедай : наставник для всех
*****
Offline Offline

Сообщений: 2901



Просмотр профиля WWW
« Ответ #12 : Сентябрь 11, 2008, 12:23 »

Точно строку привести не могу, так как дома делал. Но приблизительно не может найти директорию или файл (на Ubuntu).
И еще почему на Ubuntu создаеться 4 файла:lib.so, lib.so.1.0 или что-то вроде? И какую использовать?

Создаеться всего 1 so, остальные симлинки на него.


Для линукса перечитайте еще раз пост Alex03. Копирование so к исполняемому файлу ничего не дает, это не винда.

Цитировать
When loading the library, QLibrary searches in all system-specific library locations (e.g. LD_LIBRARY_PATH on Unix), unless the file name has an absolute path.
« Последнее редактирование: Сентябрь 11, 2008, 12:28 от pastor » Записан

Integrated Computer Solutions, Inc. (ICS)
http://www.ics.com/
Nalsur1982
Гость
« Ответ #13 : Сентябрь 12, 2008, 21:49 »

To Alex03 and pastor спасибо.
В Ubuntu проблемма решилась указанием абсолютного пути библиотеки.
Буду решать для Windows.
Записан
Nalsur1982
Гость
« Ответ #14 : Сентябрь 17, 2008, 11:02 »

Сделал все то же самое и почему то заработало  Непонимающий
Записан
Страниц: [1]   Вверх
  Печать  
 
Перейти в:  


Страница сгенерирована за 0.128 секунд. Запросов: 23.