这是代码。
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
int _tmain(int argc, _TCHAR* argv[])
{
auto f = CreateFile(L"file.txt", GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
struct overlapped_buffer
{
OVERLAPPED o;
char b[64];
};
overlapped_buffer ob = {};
ReadFileEx(f, ob.b, sizeof(ob.b), &ob.o, [] (DWORD e, DWORD c, OVERLAPPED * o)
{
if( ERROR_SUCCESS == e ) printf("Error");
else {
auto ob = reinterpret_cast<overlapped_buffer *>(o);
printf("> %.*s\n", c, ob->b);
}
} );
SleepEx( 1000, TRUE );
CloseHandle( f );
printf("read file");
return 0;
}
问题是我不知道如何解决智能感知错误。
2 IntelliSense: no suitable conversion function from "lambda []void (DWORD e, DWORD c, OVERLAPPED *o)->void" to "LPOVERLAPPED_COMPLETION_ROUTINE" exists c:\kombea\portaudiofastplayer\test_lambda\test_lambda.cpp 19 43 test_lambda
我是否能够创建一个lambda函数并在这种情况下将其用作CALLBACK函数?
答案 0 :(得分:0)
在Mingw 4.8.1和VS2013中工作良好..:
创建了一个名为“file.txt”的文件。添加“Hello World”并保存。然后我运行以下内容并打印“&gt; Hello World”。
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
int _tmain(int argc, _TCHAR* argv[])
{
auto f = CreateFile("file.txt", GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
struct overlapped_buffer
{
OVERLAPPED o;
char b[64];
};
overlapped_buffer ob = {};
ReadFileEx(f, ob.b, sizeof(ob.b), &ob.o, [] (DWORD e, DWORD c, OVERLAPPED * o)
{
auto ob = reinterpret_cast<overlapped_buffer*>(o);
printf("> %.*s\n", c, ob->b);
});
SleepEx(1000, TRUE);
CloseHandle(f);
return 0;
}
在VS2010中,以下内容至少编译:
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
int main()
{
auto f = CreateFile(L"C:/Users/Brandon/Desktop/file.txt", GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
struct overlapped_buffer
{
OVERLAPPED o;
char b[64];
};
overlapped_buffer ob = {};
ReadFileEx(f, ob.b, sizeof(ob.b), &ob.o, (LPOVERLAPPED_COMPLETION_ROUTINE) &[&] (DWORD e, DWORD c, OVERLAPPED* o)
{
std::cout<<"HERE\n"<<std::endl; //not being called.. already tried std::function..
});
//SleepEx(1000, TRUE);
SleepEx(1000, false);
CloseHandle(f);
std::cin.get();
return 0;
}
使用参数TRUE的SleepEx会导致它抛出..我不知道为什么......
即使这会在它遇到SleepEx时抛出,但是上面和下面都有“Hello World”存储在重叠缓冲区中。
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
int main()
{
auto f = CreateFile(L"file.txt", GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
struct overlapped_buffer
{
OVERLAPPED o;
char b[64];
};
overlapped_buffer ob = {};
struct cb
{
static void callback(DWORD e, DWORD c, OVERLAPPED* o)
{
auto ptr = reinterpret_cast<overlapped_buffer*>(o);
std::cout<<ptr->b<<"\n";
}
};
ReadFileEx(f, ob.b, sizeof(ob.b), &ob.o, (LPOVERLAPPED_COMPLETION_ROUTINE) cb::callback);
SleepEx(1000, TRUE);
CloseHandle(f);
std::cin.get();
return 0;
}