Модераторы: bsa
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> VS 2010 Express + WDK и Network Monitor 3, не удаётся скомпилировать пример 
V
    Опции темы
SolRus
Дата 3.10.2011, 02:46 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 40
Регистрация: 6.8.2011

Репутация: нет
Всего: нет



Вообщем не могу скомпилировать программу. хочу запустить образец из программы microsoft network monitor 3 (3.4.2350.0)
использую visual studio 2010 express (10.0.30319.1) + windows development kit (WDK 7600.16385.1)

значит что я делаю:
скачал wdk установил в "C:\WinDDK\" и проверил согласно файлу install.htm - с build -cZ (в конце командной строки вроде как все ок):
Цитата
BUILD: Done
    2,548 files compiled
    119 libraries built
    296 executables built
C:\WinDDK>

по alt-f7 в страницах свойств

слева "свойства конфигурации" - в "каталоги vc++" добавляю
каталоги включения: C:\WinDDK\inc\api;C:\WinDDK\inc\ddk;C:\Program Files\Microsoft Network Monitor 3\API;
каталоги библиотек: C:\Program Files\Microsoft Network Monitor 3\API

слева "свойства конфигурации" - в "компоновщик"-"ввод" добавляю
дополнительные зависимости: Nmapi.lib;

сначала вставил по образцу как в справке Network Monitor 3 примере код, а потом просто обычный main с cout hello world - все равно ошибки

Цитата
1>C:\Program Files\Microsoft Visual Studio 10.0\VC\include\iosfwd(19): error C2146: синтаксическая ошибка: отсутствие ";" перед идентификатором "streamoff"
1>C:\Program Files\Microsoft Visual Studio 10.0\VC\include\iosfwd(19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
--- и т.п. ---
1>C:\Program Files\Microsoft Visual Studio 10.0\VC\include\iosfwd(503): fatal error C1003: число ошибок превышает 100; остановка компиляции
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========


вроде все просто, а оно чет что-то нетак. подскажите)   smile 
PM MAIL Skype   Вверх
bsa
Дата 3.10.2011, 12:44 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Модератор
Сообщений: 9185
Регистрация: 6.4.2006
Где: Москва, Россия

Репутация: 85
Всего: 196



такое ощущение, что ты собираешь программу на C++ компилятором C.
PM   Вверх
SolRus
  Дата 3.10.2011, 14:52 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 40
Регистрация: 6.8.2011

Репутация: нет
Всего: нет



Цитата(bsa @ 3.10.2011,  12:44)
такое ощущение, что ты собираешь программу на C++ компилятором C.

ну даже такая программа не компилируется, использую visual c++ (примеры в network monitor подписаны как с++ в справке их)
Код
#include <iostream>
int main() { 
    std::cout << "1111" << std::endl;
    std::cin.ignore(std::cin.gcount()).get(); //ждем ввод
    return 0;
}

вот чем собирал WDK (вводил "build -cZ" согласно файлу install.htm который в поставке с wdk)
Цитата
x86 Checked Build Environment
(C:\Windows\System32\cmd.exe /k C:\WinDDK\bin\setenv.bat C:\WinDDK\ chk x86 WIN7)

Launching OACR monitor

C:\WinDDK>build /?

BUILD: Version 6.1.7063.0

Usage: BUILD [-?] display this message
        [/#] force _objects.mac to be regenerated
        [/0] pass 0 generation only, no compile, no link
        [/2] same as old /Z (only do a 2 pass build - no pass 0)
        [/3] same as /Z
        [/a] allows synchronized blocks and drains during link pass
        [/b] displays full error message text (doesn't truncate)
        [/B [baseline]] Checks the build failures against a baseline
                If there is no baseline,terminates the build on the first erro
        [/c] deletes all object files
        [/C] deletes all .lib files only
        [/D] check dependencies before building (on by default if BUILD_PRODUC
!= NT)
        [/e] generates build.log, build.wrn & build.err files
        [/E] always keep the log/wrn/err files (use with /z)
        [/f] force rescan of all source and include files
        [/F] when displaying errors/warnings to stdout, print the full path
        [/g] Display warnings/errors/summary in color
        [/h] Hide console output
        [/G] enables target specific dirs files iff one target
        [/i] ignore extraneous dependency warning messages
        [/I] do not display thread index if multiprocessor build
        [/j filename] use L'filename' as the name for log files
        [/k] keep (don't delete) out-of-date targets
        [/l] link only, no compiles
        [/L] compile only, no link phase
        [/m] run build in the idle priority class
        [/M [n]] Multiprocessor build (for MP machines. Max. 64)
        [/n] No SYNCHRONIZE_BLOCK and SYNCHRONIZE_DRAIN directives
        [/o] display out-of-date files
        [/O] generate $(O)\_objects.mac file for current directory
        [/p] pause' before compile and link phases
        [/P] Print elapsed time after every directory
        [/q] query only, don't run NMAKE
        [/r dirPath] restarts clean build at specified directory path
        [/s] display status line at top of display
        [/S] display status line with include file line counts
        [/t] display the first level of the dependency tree
        [/T] display the complete dependency tree
        [/$] display the complete dependency tree hierarchically
        [/u] display unused BUILD_OPTIONS
        [/v] enable include file version checking
        [/w] show warnings on screen
        [/x filename] exclude include file from dependency checks
        [/X] generates XML log file
        [/y] show files scanned
        [/Z] no dependency checking or scanning of source files -
                three passes
        [/z] same as /Z
        [/why] list reasons for building targets
        [/sharedpch] ignore pch time stamp during dependency check-
                     has no effect with /clean

        [/386] build targets for 32-bit Intel
        [/x86] Same as /i386
        [/ia64] build targets for IA64
        [/amd64] build targets for AMD64
        [/arm] build targets for ARM

        [/jpath pathname] use L'pathname' as the path for log files instead of
."
        [/nmake arg] argument to pass to NMAKE
        [/getperf] do not generate the build performance
        [/findBottleNecks] Finds perf bottlesnecks during build and logs the
                        state of build during these bottlenecks
        [/getslowestdirs] [N] Gives the N slowest dirs in the tree.If N is
                                 not provided it defaults to 10
        [/skiptestcode] Skips sources marked as TEST_CODE=1
                Can also be set by defining BUILD_SKIP_TEST_CODE=1
        [/DirInclude:[!]<type>,<type>]. Build includes (or excludes)
                directories of the types listed in <type>.
                Types are specified in dirs files.
                Valid types are Product, Test, Tool
                /DirInclude:!Test,Tool = Build all but Test & Tool
                /DirInclude:Test = Build only test
                Can also be set using BUILD_DIRINCLUDE=
        [/ManifestCompilation] Just compiles and validates manifests
        [/nosqm] Do not report build usage data to Microsoft.
        [/VerifySync] Validates synchronization. Detects duplicate or
                 non-existent produce macros, wrong ordering, etc.
        Non-switch parameters specify additional source directories
        * builds all optional source directories
        ~<DirName> Excludes all the directories with name equal to DirName
        !<Relative path\DirName> Excludes just the exact directory specified
.        The path given is relative to Dir from where build.exe is launched

C:\WinDDK>

компилятор wdk С, или че?) я просто в этом слабенько соображаю..(
если я wdk собрал С компилятором, то как его в С++ построить?  smile 
____________

проверил это .... и оно скомпилировалось, и код network monitor тоже
Код

#include "stdio.h"
int main() { 
    wprintf(L"1111\n");
    return 0;
}

использую с++, как его заставить понимать iostream? cout/cin

Это сообщение отредактировал(а) SolRus - 3.10.2011, 15:07
PM MAIL Skype   Вверх
bsa
Дата 3.10.2011, 15:29 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Модератор
Сообщений: 9185
Регистрация: 6.4.2006
Где: Москва, Россия

Репутация: 85
Всего: 196



вообще-то, есть подозрение, что далеко не все части network monitor надо собирать с использованием WDK (Windows Driver Development Kit). Все-таки std::streamoff - это часть стандартной библиотеки С++. Я уверен, что при написании драйверов пользоваться ей нельзя.
Может ты WDK с SDK перепутал?

Это сообщение отредактировал(а) bsa - 3.10.2011, 15:30
PM   Вверх
SolRus
Дата 3.10.2011, 16:07 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 40
Регистрация: 6.8.2011

Репутация: нет
Всего: нет



Цитата(bsa @ 3.10.2011,  15:29)
вообще-то, есть подозрение, что далеко не все части network monitor надо собирать с использованием WDK (Windows Driver Development Kit). Все-таки std::streamoff - это часть стандартной библиотеки С++. Я уверен, что при написании драйверов пользоваться ей нельзя.
Может ты WDK с SDK перепутал?

примеры работают, но cout/cin и прочее не могу использовать... нет не перепутал, вот:
Цитата("цитата из справки network monitor 3")

When developing with Microsoft Visual Studio 2005 or Visual Studio 2008, you must add some directory paths for your global options, as well as modify your projects settings to include the Nmapi.lib. The Windows Driver Kit (WDK) is required.


вот один из примеров в справке - открывает и парсит уже готовый сниф файл (*.cap)
Код

// LoadCapAndFilter.cpp : Defines the entry point for the console
// application.

#include "windows.h"
#include "stdio.h"
#include "stdlib.h"
#include "objbase.h"
#include "ntddndis.h"
#include "NMApi.h"

HANDLE myNplParser = INVALID_HANDLE_VALUE;
HANDLE myFrameParserConfig = INVALID_HANDLE_VALUE;

ULONG myHTTPFilterID = 0;    // Global for the Filter.
ULONG myHTTPFieldID = 0;     // Global ID for the HTTP data field.

void __stdcall
MyParserBuild(PVOID Context, ULONG StatusCode, LPCWSTR lpDescription, ULONG ErrorType)
{
    wprintf(L"%s\n", lpDescription);
}

// Returns a frame parser with a filter and one data field.
// INVALID_HANDLE_VALUE indicates failure.
HANDLE
MyLoadNPL(void)
{
    HANDLE myFrameParser = INVALID_HANDLE_VALUE;
    ULONG ret;

    // Use NULL to load default NPL set.
    ret = NmLoadNplParser(NULL, NmAppendRegisteredNplSets, MyParserBuild, 0, &myNplParser);

    if(ret == ERROR_SUCCESS){
        ret = NmCreateFrameParserConfiguration(myNplParser, MyParserBuild, 0, &myFrameParserConfig);

        if(ret == ERROR_SUCCESS)
        {

            ret = NmAddFilter(myFrameParserConfig, L"http.request.command == \"GET\"", &myHTTPFilterID);
            if(ret != 0)
            {
                wprintf(L"Failed to add fitler, error 0x%X\n", ret);
            }

            ret = NmAddField(myFrameParserConfig, L"http.request.uri", &myHTTPFieldID);
            if(ret != ERROR_SUCCESS)
            {
                wprintf(L"Failed to add field, error 0x%X\n", ret);
            }

            ret = NmCreateFrameParser(myFrameParserConfig, &myFrameParser);

            if(ret != ERROR_SUCCESS)
            {
                wprintf(L"Failed to create frame parser, error 0x%X\n", ret);
                NmCloseHandle(myFrameParserConfig);
                NmCloseHandle(myNplParser);
                return INVALID_HANDLE_VALUE;
            }
        }
        else
        {
            wprintf(L"Unable to load parser config, error 0x%X\n", ret);
            NmCloseHandle(myNplParser);
            return INVALID_HANDLE_VALUE;
        }

    }
    else
    {
        wprintf(L"Unable to load NPL\n");
        return INVALID_HANDLE_VALUE;
    }

    return(myFrameParser);
}

void
UnLoadNPL(void)
{
    NmCloseHandle(myNplParser);
    NmCloseHandle(myFrameParserConfig);
}

int __cdecl wmain(int argc, WCHAR* argv[])
{
    ULONG ret = ERROR_SUCCESS;
    // The first paramryrt should be a file.
    if(argc <= 1){
        wprintf(L"Expect a file name as the only command line parameter\n");
        return -1;
    }

    // Open the specified capture file.
    HANDLE myCaptureFile = INVALID_HANDLE_VALUE;
    if(ERROR_SUCCESS == NmOpenCaptureFile(argv[1], &myCaptureFile))
    {
        // Initialize the parser engine and return a frame parser.
        HANDLE myFrameParser = MyLoadNPL();
        if(myFrameParser != INVALID_HANDLE_VALUE)
        {
            ULONG myFrameCount = 0;
            ret = NmGetFrameCount(myCaptureFile, &myFrameCount); 
            if(ret == ERROR_SUCCESS)
            {
                HANDLE myRawFrame = INVALID_HANDLE_VALUE;
                for(ULONG i = 0; i < myFrameCount; i++)
                {
                    HANDLE myParsedFrame = INVALID_HANDLE_VALUE;
                    ret = NmGetFrame(myCaptureFile, i, &myRawFrame); 
                    if(ret == ERROR_SUCCESS)
                    {
                        // The last parameter is for the API to return
                        // the reassembled frame if enabled.
                        // NULL indicates that the API discards the
                        // reassembled frame.
                        ret = NmParseFrame(myFrameParser, myRawFrame, i, 0, &myParsedFrame, NULL); 
                        if(ret == ERROR_SUCCESS)
                        {
                            // Test to see if this frame passed the filter.
                            BOOL passed = FALSE;
                            ret = NmEvaluateFilter(myParsedFrame, myHTTPFilterID, &passed);
                            if((ret == ERROR_SUCCESS) && (passed == TRUE))
                            {
                                // Obtain the value of http.request.uri from
                                // the frame. Strings are passed as a word
                                // pointer to a Unicode string in the
                                // variant.
                                WCHAR value[256];
                                ret = NmGetFieldValueString(myParsedFrame, myHTTPFieldID, 256, (LPWSTR)value);
                                if(ret == ERROR_SUCCESS)
                                {
                                    // Cast to WCHAR *.
                                    wprintf(L"Frame %d: HTTP: %s\n", i+1, (LPWSTR)value);
                                }
                            }

                            // Release the current parsed frame.
                            NmCloseHandle(myParsedFrame);
                        }
                        else
                        {
                            // Print an error, but continue to loop.
                            wprintf(L"Error: 0x%X, trying to parse frame %d\n", ret, i+1);
                        }

                        // Release the current raw frame.
                        NmCloseHandle(myRawFrame);
                    }
                    else
                    {
                        // Print an error, but continue to loop.
                        wprintf(L"Errors getting raw frame %d\n", i+1);
                    }
                }
            }

            NmCloseHandle(myFrameParser);
        }
        else
        {
            wprintf(L"Errors creating frame parser\n");
        }

        NmCloseHandle(myCaptureFile);
    }
    else
    {
        wprintf(L"Errors openning capture file\n");
    }

    // Release global handles.
    UnLoadNPL();

    return 0;
}

"NMApi.h" и NmApi.lib - с network monitor
"objbase.h" и "ntddndis.h" - с wdk

есть предположение как это перевести в С++ - использовать <iostream>?
PM MAIL Skype   Вверх
bsa
Дата 3.10.2011, 16:21 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Модератор
Сообщений: 9185
Регистрация: 6.4.2006
Где: Москва, Россия

Репутация: 85
Всего: 196



Цитата(SolRus @  3.10.2011,  17:07 Найти цитируемый пост)
cout/cin и прочее не могу использовать

так как они входят в состав стандартной библиотеки С++. А драйвера, обычно, на С пишут. В примере из справки тоже С используется.
PM   Вверх
SolRus
  Дата 3.10.2011, 16:40 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 40
Регистрация: 6.8.2011

Репутация: нет
Всего: нет



Цитата(bsa @ 3.10.2011,  16:21)
Цитата(SolRus @  3.10.2011,  17:07 Найти цитируемый пост)
cout/cin и прочее не могу использовать

так как они входят в состав стандартной библиотеки С++. А драйвера, обычно, на С пишут. В примере из справки тоже С используется.

т.е. при wdk использовать iostream не получится?
только printf? почему нельзя использовать стандартную библиотеку С++?

 че писать драйвера на с++ нельзя?  smile 
PM MAIL Skype   Вверх
bsa
Дата 3.10.2011, 22:51 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Модератор
Сообщений: 9185
Регистрация: 6.4.2006
Где: Москва, Россия

Репутация: 85
Всего: 196



Цитата(SolRus @  3.10.2011,  17:40 Найти цитируемый пост)
че писать драйвера на с++ нельзя?

Может и можно... Но на 99% уверен, что о стандартной библиотеке С++ можно забыть.
PM   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "C/C++: Для новичков"
JackYF
bsa

Запрещается!

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми компонентами

  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Вопросы по реализации алгоритмов рассматриваются здесь


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, JackYF, bsa.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C/C++: Для новичков | Следующая тема »


 




[ Время генерации скрипта: 0.0766 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.