Russian Qt Forum
Мая 09, 2025, 17:23 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
   Начало   Форум WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  
Страниц: 1 2 [3] 4 5 ... 10
 21 
 : Сентября 26, 2024, 13:06 
Автор Александра - Последний ответ от ssoft
Еще есть вариант собрать hidapi в виде статической библиотеки.
Тип указывается в настройках проекта в Visual Studio.

 22 
 : Сентября 26, 2024, 10:14 
Автор Александра - Последний ответ от ssoft
Эти ошибки возникают на этапе линковки и только в Windows, так как методы библиотеки не экспортированы.
Обычно в проектах делают что-то типа

Код
C++ (Qt)
#if defined( BUILD_DLL )
   #define IMPORT_EXPORT __declspec(dllexport)
#else
   #define IMPORT_EXPORT __declspec(dllimport)
#endif
class IMPORT_EXPORT MyClass {
   ...
};
 
IMPORT_EXPORT void myMethod();
 

Где при сборке библиотеки IMPORT_EXPORT определяется как __declspec(dllexport), а при сборке приложения как__declspec(dllimport).

Похоже hidapi не содержит такого механизма, либо при его сборке не определен необходимый DEFINE.

Можно обойтись без IMPORT_EXPORT, тогда необходимо сгенерировать def файл по инструкции

https://learn.microsoft.com/ru-ru/cpp/build/exporting-from-a-dll-using-def-files?view=msvc-170
https://learn.microsoft.com/en-us/cpp/build/reference/def-specify-module-definition-file?view=msvc-170

 23 
 : Сентября 25, 2024, 12:53 
Автор Александра - Последний ответ от Александра
Добрый день. Создаю проект, в котором нужно будет общаться с hid-устройством, чтобы контролировать зажигающиеся светодиоды. Сама я со сторонними библиотеками дело не имела, потому длительное изучение данной темы привело меня на небезызвестную (судя по ее упоминаниям) библиотеку hidapi с github'а. Саму библиотеку я скомпилировала, как было написано в README для WINDOWS на Visual studio, создала .dll, .lib файлы, стала подключать ее к проекту, который я пока не разбирала, но пример которого был взят с другого сайта, чтобы просто проверить хотя бы подключение библиотеки, не говоря уже о работе.
Подключала я ее следующим образом:
keykey.pro
Код:
QT -= gui
 
CONFIG += c++11 console
CONFIG -= app_bundle
 
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
 
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
 
SOURCES += \
        main.cpp
 
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
 
INCLUDEPATH += $$PWD/.
LIBS += -L$$PWD/./ -lhidapi

main.cpp
Код:
#include <QCoreApplication>
 
#include <stdio.h>
#include <wchar.h>
#include <string.h>
#include <stdlib.h>
#include "hidapi.h"
#include <unistd.h>
 
#define MAX_STR 255
 
int main(int argc, char *argv[])
{
    //QCoreApplication a(argc, argv);
    //return a.exec();
 
 
    int res;
    unsigned char buf[256];
 
    wchar_t wstr[MAX_STR];
    hid_device *handle;
    int i;
 
 
    struct hid_device_info *devs, *cur_dev;
 
    if (hid_init())
        return -1;
 
        devs = hid_enumerate(0x0, 0x0);
        cur_dev = devs;
        while (cur_dev) {
            printf("Device Found\n  type: %04hx %04hx\n  path: %s\n  serial_number: %ls", cur_dev->vendor_id, cur_dev->product_id, cur_dev->path, cur_dev->serial_number);
            printf("\n");
            printf("  Manufacturer: %ls\n", cur_dev->manufacturer_string);
            printf("  Product:      %ls\n", cur_dev->product_string);
            printf("  Release:      %hx\n", cur_dev->release_number);
            printf("  Interface:    %d\n",  cur_dev->interface_number);
            printf("\n");
            cur_dev = cur_dev->next;
        }
        hid_free_enumeration(devs);
 
        // Set up the command buffer.
        memset(buf,0x00,sizeof(buf));
        buf[0] = 0x01;
        buf[1] = 0x81;
 
 
        // Open the device using the VID, PID,
        // and optionally the Serial number.
        ////handle = hid_open(0x4d8, 0x3f, L"12345");
        handle = hid_open(0x4d8, 0x3f, NULL);
        if (!handle) {
            printf("unable to open device\n");
            return 1;
        }
 
        // Read the Manufacturer String
        wstr[0] = 0x0000;
        res = hid_get_manufacturer_string(handle, wstr, MAX_STR);
        if (res < 0)
            printf("Unable to read manufacturer string\n");
        printf("Manufacturer String: %ls\n", wstr);
 
        // Read the Product String
        wstr[0] = 0x0000;
        res = hid_get_product_string(handle, wstr, MAX_STR);
        if (res < 0)
            printf("Unable to read product string\n");
        printf("Product String: %ls\n", wstr);
 
        // Read the Serial Number String
        wstr[0] = 0x0000;
        res = hid_get_serial_number_string(handle, wstr, MAX_STR);
        if (res < 0)
            printf("Unable to read serial number string\n");
        printf("Serial Number String: (%d) %ls", wstr[0], wstr);
        printf("\n");
 
        // Read Indexed String 1
        wstr[0] = 0x0000;
        res = hid_get_indexed_string(handle, 1, wstr, MAX_STR);
        if (res < 0)
            printf("Unable to read indexed string 1\n");
        printf("Indexed String 1: %ls\n", wstr);
 
        // Set the hid_read() function to be non-blocking.
        hid_set_nonblocking(handle, 1);
 
        // Try to read from the device. There shoud be no
        // data here, but execution should not block.
        res = hid_read(handle, buf, 17);
 
        // Send a Feature Report to the device
        buf[0] = 0x2;
        buf[1] = 0xa0;
        buf[2] = 0x0a;
        buf[3] = 0x00;
        buf[4] = 0x00;
        res = hid_send_feature_report(handle, buf, 17);
        if (res < 0) {
            printf("Unable to send a feature report.\n");
        }
 
        memset(buf,0,sizeof(buf));
 
        // Read a Feature Report from the device
        buf[0] = 0x2;
        res = hid_get_feature_report(handle, buf, sizeof(buf));
        if (res < 0) {
            printf("Unable to get a feature report.\n");
            printf("%ls", hid_error(handle));
        }
        else {
            // Print out the returned buffer.
            printf("Feature Report\n   ");
            for (i = 0; i < res; i++)
                printf("%02hhx ", buf[i]);
            printf("\n");
        }
 
        memset(buf,0,sizeof(buf));
 
        // Toggle LED (cmd 0x80). The first byte is the report number (0x1).
        buf[0] = 0x1;
        buf[1] = 0x80;
        res = hid_write(handle, buf, 17);
        if (res < 0) {
            printf("Unable to write()\n");
            printf("Error: %ls\n", hid_error(handle));
        }
 
 
        // Request state (cmd 0x81). The first byte is the report number (0x1).
        buf[0] = 0x1;
        buf[1] = 0x81;
        hid_write(handle, buf, 17);
        if (res < 0)
            printf("Unable to write() (2)\n");
 
        // Read requested state. hid_read() has been set to be
        // non-blocking by the call to hid_set_nonblocking() above.
        // This loop demonstrates the non-blocking nature of hid_read().
        res = 0;
        while (res == 0) {
            res = hid_read(handle, buf, sizeof(buf));
            if (res == 0)
                printf("waiting...\n");
            if (res < 0)
                printf("Unable to read()\n");
            usleep(500*1000);
        }
 
        printf("Data read:\n   ");
        // Print out the returned buffer.
        for (i = 0; i < res; i++)
            printf("%02hhx ", buf[i]);
        printf("\n");
 
        hid_close(handle);
 
        /* Free static HIDAPI objects. */
        hid_exit();
 
        return 0;
}

Но у меня везде, где упоминаются методы из библиотеки показывается сообщение такого вида: undefined reference to `hid_init'

Все файлы у меня находятся в одной папке и имеют следующий вид:
keykey:
| hidapi.dll
| hidapi.h
| hidapi.lib
| keykey.pro
| main.cpp

Помогите, пожалуйста, разобраться, в чем проблема. Я уже множество разных методов перепробовала: и указывать в либсе .dll, и указывать .lib, и располагать файлы в друих местах. Но что интересно, если я на F2 буду переходить по ссылкам относительно какой-то функции, то меня отправляет в файл "hidapi.h" без каких-то проблем.
Заранее извиняюсь за мое невежество: в интернете много новой и сложной для меня информации, поэтому могу жёстко "косячить"...

 24 
 : Сентября 21, 2024, 10:13 
Автор KSergeyP - Последний ответ от qate
никак, забить

но можно создать и багрепорт, это проблема qt - пусть сами и исправляют

 25 
 : Сентября 20, 2024, 11:57 
Автор denantikvar - Последний ответ от denantikvar
Куплю, обмен фунты выпущенные в Шотландии или Северной Ирландии , вышедшие из обращения Немецкие марки, Японские йены ( иены Япония ), Норвежские кроны, Датские кроны, Шведские кроны, просроченные европейские банкноты и другую редкую валюту некоторых развитых стран, которую нельзя сдать в обменник.

+79997153560  WhatsApp, Viber 

Сайт где можно сделать обмен старых просроченных банкнот https://www.skupka.kvt777.ru/skupka-banknot.html

Группа ВК для обмена старых швейцарских франков https://vk.com/obmen_frankov

Группа ВК для обмена старых английских фунтов стерлингов https://vk.com/obmen_funtov




 26 
 : Сентября 19, 2024, 11:21 
Автор KSergeyP - Последний ответ от KSergeyP
Добрый день! Собираю Qt6.7.2 из исходников под Linux.
Сборка проходит без ошибок но есть несколько предупреждений:
Warning: private/qt3dquickvaluetypes_p.h:: QColor is declared as foreign type, but cannot be found.
Warning: private/qt3dquickvaluetypes_p.h:: QMatrix4x4 is declared as foreign type, but cannot be found.
Warning: private/qt3dquickvaluetypes_p.h:: QQuaternion is declared as foreign type, but cannot be found.
Warning: private/qt3dquickvaluetypes_p.h:: QVector2D is declared as foreign type, but cannot be found.
Warning: private/qt3dquickvaluetypes_p.h:: QVector3D is declared as foreign type, but cannot be found.
Warning: private/qt3dquickvaluetypes_p.h:: QVector4D is declared as foreign type, but cannot be found.
Warning: private/qpositioningquickmodule_p.h:: QGeoAddress is declared as foreign type, but cannot be found.
Warning: private/qpositioningquickmodule_p.h:: QGeoLocation is declared as foreign type, but cannot be found.
Warning: private/qpositioningquickmodule_p.h:: QGeoPositionInfo is declared as foreign type, but cannot be found.
Warning: private/foreigntypes_p.h:: QTouch3DInputHandler is declared as foreign type, but cannot be found.
Warning: private/foreigntypes_p.h:: Refusing to generate non-lowercase name TouchInputHandler3D for unknown foreign type
qwltexturesharingextension_p.h:62:1: warning: Property declaration imageSearchPath has neither an associated QProperty<> member, nor a READ accessor function nor an associated MEMBER variable. The property will be invalid.
QTextToSpeechMockPlugin.dir/QTextToSpeechMockPlugin_autogen/mocs_compilation.cpp.o
[12338/13046] Automatic QML type registration for target WaylandCompositor
Warning: qwaylandidleinhibitv1.h:: QWaylandCompositorExtensionTemplate<QWaylandIdleInhibitManagerV1> is used but cannot be found.
Warning: qwaylandqttextinputmethodmanager.h:: QWaylandCompositorExtensionTemplate<QWaylandQtTextInputMethodManager> is used but cannot be found.
Warning: qwaylandqtwindowmanager.h:: QWaylandCompositorExtensionTemplate<QWaylandQtWindowManager> is used but cannot be found.
Warning: qwaylandtextinputmanager.h:: QWaylandCompositorExtensionTemplate<QWaylandTextInputManager> is used but cannot be found.
Warning: qwaylandtextinputmanagerv3.h:: QWaylandCompositorExtensionTemplate<QWaylandTextInputManagerV3> is used but cannot be found.

Может кто то подсказать как от них избавиться, хотя бы от каких либо из перечисленных?
Нужно доустановить какие-то dev пакеты в Linux? Понятно что для разных предупреждений какие-то свои зависимости должны быть.

 27 
 : Июля 24, 2024, 11:32 
Автор Александра - Последний ответ от kambala
Цитировать
Или его надо прописывать не так, как ниже, а именно в конструкторе класса load?
его надо прописать и так, как ниже, а также указать его как параметр конструктора в классе load, иначе просто будет ошибка компиляции.
Код
C++ (Qt)
load::load(Automat *autw, QObject *parent) : QObject(parent)
{
   connect(autw, &Automat::get_load, this, &load::load_data);
 
   // альтернативно: вместо этого connect и emit get_data() просто писать autw->load_text() в месте испускания сигнала
   connect(this, &load::get_data, autw, &Automat::load_text);
}
возможно тебе также понадобится сохранить autw в поле класса чтоб к нему был доступ вне конструктора load

в общем, надо подучить С++ Улыбающийся

 28 
 : Июля 24, 2024, 10:28 
Автор Александра - Последний ответ от Александра
выше тебе все правильно написали. Тебе нужно передать autw в объект ld (например, как параметр конструктора), а не создавать внутри load новый объект Automat.
Ну, перенесу я таким способом autw, но у меня же load.cpp не будет знать, кто это такой. Объект ld создан и находится же в mainwindow, а коннекты же прописаны в файле load.cpp, то есть у них не будет прямой связи. Разве не так?
П.с. Скорее всего, не так, но я не понимаю, как объявленный объект в конструкторе поможет объявить коннекты в другом файле. Или его надо прописывать не так, как ниже, а именно в конструкторе класса load?
mainwindow.cpp
Код:
...
autw = std::make_unique<Automat>();
ld = std::make_unique<load>(autw);
...

 29 
 : Июля 23, 2024, 20:21 
Автор SektorCT - Последний ответ от SektorCT
решение найдено, если кому пригодится то привожу пример ниже.

Код:
set_property(GLOBAL PROPERTY HEADERS_PROPERTY) # with props

function(add_headers_props)
message(STATUS "Adding headers with property ${ARGV}")

get_property(HEADERS GLOBAL PROPERTY HEADERS_PROPERTY)
set_property(GLOBAL PROPERTY HEADERS_PROPERTY ${HEADERS} ${ARGV})
endfunction()

get_property(HEADERS_PROPERTY GLOBAL PROPERTY HEADERS_PROPERTY)

Суть такая, с начала обьявляется глобальная переменная, потом черег гетер и сетер мы работаем с получением и наполнением.
Надеюсь кому то тоже может помочь.

 30 
 : Июля 23, 2024, 14:20 
Автор Александра - Последний ответ от kambala
выше тебе все правильно написали. Тебе нужно передать autw в объект ld (например, как параметр конструктора), а не создавать внутри load новый объект Automat.

Страниц: 1 2 [3] 4 5 ... 10

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