Russian Qt Forum

Qt => Общие вопросы => Тема начата: Nalsur1982 от Сентябрь 10, 2008, 10:58



Название: И сново о dll !
Отправлено: 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


Название: Re: И сново о dll !
Отправлено: ритт от Сентябрь 10, 2008, 11:05
> QLibrary     lib("DLL");
"DLL" - это название твоей либы?


Название: Re: И сново о dll !
Отправлено: Nalsur1982 от Сентябрь 10, 2008, 11:30
да DLL.dll


Название: Re: И сново о dll !
Отправлено: pastor от Сентябрь 10, 2008, 12:03
Советую почитать темы по строке поиска "dllexport"


Название: Re: И сново о dll !
Отправлено: Alex03 от Сентябрь 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


Название: Re: И сново о dll !
Отправлено: Nalsur1982 от Сентябрь 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;
}


Название: Re: И сново о dll !
Отправлено: pastor от Сентябрь 10, 2008, 14:46
А что пишет QLibrary::errorString при попытке загрузки библиотеки?


Название: Re: И сново о dll !
Отправлено: pastor от Сентябрь 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


Название: Re: И сново о dll !
Отправлено: Nalsur1982 от Сентябрь 10, 2008, 15:17
Пишет что не может найти


Название: Re: И сново о dll !
Отправлено: Nalsur1982 от Сентябрь 11, 2008, 08:19
Может кто-нибудь выложит или вышлет рабочий пример с одной функцией и с классом для Windows и Ubuntu? Буду крайне благодарен! ruslan_i<dog>list<point>ru.


Название: Re: И сново о dll !
Отправлено: pastor от Сентябрь 11, 2008, 11:04
Пишет что не может найти

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


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


Название: Re: И сново о dll !
Отправлено: pastor от Сентябрь 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.


Название: Re: И сново о dll !
Отправлено: Nalsur1982 от Сентябрь 12, 2008, 21:49
To Alex03 and pastor спасибо.
В Ubuntu проблемма решилась указанием абсолютного пути библиотеки.
Буду решать для Windows.


Название: Re: И сново о dll !
Отправлено: Nalsur1982 от Сентябрь 17, 2008, 11:02
Сделал все то же самое и почему то заработало  ???