I am using the GLFW and only want to open a empty windows.
I downloaded the GLFW for Windows 32.
Created an empty console project and wrote this code:
#include "main.h"
#pragma comment (lib, "glfw3dll")
#pragma comment (lib, "OpenGL32")
#define GLFW_DLL
#include <glfw3.h>
#include <chrono>
#include <iostream>
using namespace std::chrono;
GLFWwindow* window;
bool running = true;
bool initialise(){
return true;
}
void update(double deltaTime){
}
void render(){
}
int main(int argc, char **argv) {
if (!glfwInit)
return -1;
window = (glfwCreateWindow(800, 600, "Hello World", nullptr, nullptr));
if (window == nullptr){
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if (!initialise()){
glfwTerminate();
return -1;
}
auto currentTimeStamp = system_clock::now();
auto prevTimeStamp = system_clock::now();
while (running)
{
currentTimeStamp = system_clock::now();
auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp);
auto seconds = double(elapsed.count()) / 1000.0;
update(seconds);
render();
glfwPollEvents();
prevTimeStamp = currentTimeStamp;
}
glfwTerminate();
return -1;
}
And I think I added the library and the header correctly.
But everytime the programm exits with -1 after the glfwCreateWindow(..) function, because this functions return null.
Can somebody help me?
if (!glfwInit)
return -1;
I'm not sure why glfwInit would be NULL unless something truly terrible happened during DLL load.
Try calling glfwInit() instead:
if( !glfwInit() )
return -1;
Related
I'm trying make simple code call an enclave field and just add 1.
I'm reference this site : https://software.intel.com/en-us/articles/getting-started-with-sgx-sdk-f...
After it finishes, there is no error, but the enclave code is not working.
Here is my project.zip code with Visual Studio 2017 https://drive.google.com/open?id=13trTAamhNWaz2Q2BRDtUFP5qCX8Syyuc
app.cpp
#include <stdio.h>
#include <Windows.h>
#include <tchar.h>
#include "sgx_urts.h"
#include "Enclave1_u.h"
#define ENCLAVE_FILE _T("Enclave1.signed.dll")
int main() {
int a = 1;
int i = 0;
sgx_enclave_id_t eid;
sgx_status_t ret = SGX_SUCCESS;
sgx_launch_token_t token = { 0 };
int updated = 0;
ret = sgx_create_enclave(ENCLAVE_FILE, SGX_DEBUG_FLAG, &token, &updated, &eid, NULL);
if (ret != SGX_SUCCESS)
{
printf("APP error%#x, failed to create enclave. \n", ret);
return -1;
}
int *ptr = &a;
printf("%d\n",*ptr);
while (i<5) {
foo(eid, ptr);
printf("%d\n", *ptr);
Sleep(1000);
i++;
}
if (SGX_SUCCESS != sgx_destroy_enclave(eid))
return -1;
}
Enclave1.edl
enclave {
from "sgx_tstdc.edl" import *;
trusted {
/* define ECALLs here. */
public void foo([in, size = 4]int *ptr);
};
untrusted {
/* define OCALLs here. */
};
};
Enclave1.cpp
#include "Enclave1_t.h"
#include "sgx_trts.h"
#include <string.h>
void foo(int *ptr)
{
if (*ptr == 1) *ptr == 43971;
*ptr += 1;
}
I expected it to print:
43971, 43972, 43973, 43974 .....
But the result is:
1, 1, 1, .........
What did I miss?
i solved this problem.
foo needs [out] instad of [in] so Enclave1.edl should
enclave { from "sgx_tstdc.edl" import *;
trusted {
/* define ECALLs here. */
public void foo([out, size = 4]int *ptr);
};
untrusted {
/* define OCALLs here. */
};
};
project1.signed.dll file is not updated on debug folder. so i try rebuild project and it updated. I'm realized this file is enclave field itself
IF state grammar is wrong. it should be if (*ptr == 1) *ptr = 43971;
I'm writing a thumbnail handler for a custom file type. When I register it, it returns with a success message. The "thumbnail" is shown as completely blank, but it does not say "no thumbnail available". The problem is, the actual thumbnail handler never gets called. I know this, because I put a series of statements in my handler under handler::initialize, handler::queryinterface and handler::getthumbnail. I have gone through most of this documentation., but all I can find is that I need to use initialize and getthumbnail. Here is my code:
Header:
#pragma once
#include <windows.h>
#include <thumbcache.h> // For IThumbnailProvider
#include <wincodec.h> // Windows Imaging Codecs
#include <fstream>
#include <iostream>
#pragma comment(lib, "windowscodecs.lib")
class ThumbnailProvider :
public IInitializeWithStream,
public IThumbnailProvider
{
public:
// IUnknown
IFACEMETHODIMP QueryInterface(REFIID riid, void **ppv);
IFACEMETHODIMP_(ULONG) AddRef();
IFACEMETHODIMP_(ULONG) Release();
// IInitializeWithStream
IFACEMETHODIMP Initialize(IStream *pStream, DWORD grfMode);
// IThumbnailProvider
IFACEMETHODIMP GetThumbnail(UINT cx, HBITMAP *phbmp, WTS_ALPHATYPE *pdwAlpha);
ThumbnailProvider();
protected:
~ ThumbnailProvider();
private:
// Reference count of component.
long m_cRef;
// Provided during initialization.
IStream *m_pStream;
std::ofstream output;
void stripImageFrom (IStream *stream, HBITMAP *phbmp);
};
Body:
#include " ThumbnailProvider.h"
#include <Shlwapi.h>
#include <Wincrypt.h> // For CryptStringToBinary.
#include <msxml6.h>
#include <atlimage.h>
#include <fstream>
#pragma comment(lib, "Shlwapi.lib")
#pragma comment(lib, "Crypt32.lib")
#pragma comment(lib, "msxml6.lib")
extern HINSTANCE g_hInst;
extern long g_cDllRef;
ThumbnailProvider:: ThumbnailProvider() : m_cRef(1), m_pStream(NULL)
{
std::ofstream st;
st.open("C:\\Users\\labs\\Desktop\\Output\\out.txt", std::ios_base::app);
st << "Made provider";
st.close();
InterlockedIncrement(&g_cDllRef);
}
ThumbnailProvider::~ ThumbnailProvider()
{
InterlockedDecrement(&g_cDllRef);
}
#pragma region IUnknown
// Query to the interface the component supported.
IFACEMETHODIMP ThumbnailProvider::QueryInterface(REFIID riid, void **ppv)
{
std::ofstream st;
st.open("C:\\Users\\labs\\Desktop\\Output\\out.txt", std::ios_base::app);
st << "Querying interface";
st.close();
static const QITAB qit[] =
{
QITABENT( ThumbnailProvider, IThumbnailProvider),
QITABENT( ThumbnailProvider, IInitializeWithStream),
{ 0 },
};
return QISearch(this, qit, riid, ppv);
}
// Increase the reference count for an interface on an object.
IFACEMETHODIMP_(ULONG) ThumbnailProvider::AddRef()
{
return InterlockedIncrement(&m_cRef);
}
// Decrease the reference count for an interface on an object.
IFACEMETHODIMP_(ULONG) ThumbnailProvider::Release()
{
ULONG cRef = InterlockedDecrement(&m_cRef);
if (0 == cRef)
{
delete this;
}
return cRef;
}
#pragma endregion
#pragma region IInitializeWithStream
// Initializes the thumbnail handler with a stream.
IFACEMETHODIMP ThumbnailProvider::Initialize(IStream *pStream, DWORD grfMode)
{
std::ofstream st;
st.open("C:\\Users\\labs\\Desktop\\Output\\out.txt", std::ios_base::app);
st << "Got to initialization";
st.close();
// A handler instance should be initialized only once in its lifetime.
HRESULT hr = HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED);
if (m_pStream == NULL)
{
// Take a reference to the stream if it has not been initialized yet.
hr = pStream->QueryInterface(&m_pStream);
}
return hr;
}
#pragma endregion
#pragma region IThumbnailProvider
// Gets a thumbnail image and alpha type. The GetThumbnail is called with the
// largest desired size of the image, in pixels. Although the parameter is
// called cx, this is used as the maximum size of both the x and y dimensions.
// If the retrieved thumbnail is not square, then the longer axis is limited
// by cx and the aspect ratio of the original image respected. On exit,
// GetThumbnail provides a handle to the retrieved image. It also provides a
// value that indicates the color at of the image and whether it has
// valid alpha in ation.
IFACEMETHODIMP ThumbnailProvider::GetThumbnail(UINT cx, HBITMAP *phbmp,
WTS_ALPHATYPE *pdwAlpha) {
std::ofstream st;
st.open("C:\\Users\\labs\\Desktop\\Output\\out.txt", std::ios_base::app);
st << "Getting thumbnail";
st.close();
ThumbnailProvider::stripImageFrom (m_pStream, phbmp);
cx = 1024 * 1024;
*pdwAlpha = WTSAT_UNKNOWN;
return S_OK;
}
#pragma endregion
#pragma region Helper Functions
// The PNG signature is 137 80 78 71 13 10 26 10. This does not make sense to do backward. I will do it forward.
void ThumbnailProvider::stripImageFrom (IStream *stream, HBITMAP *phbmp) {
unsigned long numBytes = 0;
unsigned long *numBytesPtr = &numBytes;
char *chptr = nullptr;
byte vals[8] = { 0 };
STATSTG *stat = nullptr;
DWORD temp = NULL;
stream->Stat(stat, temp);
unsigned long long length = stat->cbSize.QuadPart;
unsigned long long i;
for (i = 0; i<length; i++) {
stream->Read(chptr, 1, numBytesPtr);
if (*chptr == 137) {
vals[0] = 1;
}
else if (*chptr == 80 && vals[0]) {
vals[1] = 1;
}
else if (*chptr == 78 && vals[1]) {
vals[2] = 1;
}
else if (*chptr == 71 && vals[2]) {
vals[3] = 1;
}
else if (*chptr == 13 && vals[3]) {
vals[4] = 1;
}
else if (*chptr == 10 && vals[4] && !vals[5]) {
vals[5] = 1;
}
else if (*chptr == 26 && vals[5]) {
vals[6] = 1;
}
else if (*chptr == 10 && vals[6]) {
vals[7] = 1;
i -= 7;
break;
}
else {
memset(vals, 0, 8 * sizeof(vals[0]));
}
}
if (vals[7]) {
IStream *imgstream = nullptr;
stream->Read(imgstream, length-i, numBytesPtr);
CImage *img = nullptr;
img->Load(imgstream);
*phbmp = *img;
}
}
#pragma endregion
Everything else is just edited from one of Microsoft's examples, so I am pretty sure that is ok. The example is here.
If you're having this problem, make sure you're building for the right architecture. That solved it for me.
Something wrong with next ReadFile/WriteFile code.
I need to use copy file by using this functions (yes, it's better to use CopyFile, but now I need it), but it crashed at read/write loop.
What can be wrong?
PS C:\Users\user\Documents\SysLab1\dist\Debug\MinGW-Windows> g++ --version
g++.exe (x86_64-posix-sjlj-rev0, Built by MinGW-W64 project) 4.8.3
I used next code :
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define BLOCK_SIZE 1024
uint32_t copy_c(char* source, char* destination) {...}
uint32_t copy_api_readwrite(char* source, char* destination) {
bool result;
HANDLE input = CreateFile(source, GENERIC_READ, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (input!=INVALID_HANDLE_VALUE) {
HANDLE output = CreateFile(destination, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(output!=INVALID_HANDLE_VALUE) {
DWORD readed;
char block[BLOCK_SIZE];
while(ReadFile(input, block, BLOCK_SIZE * sizeof(char), &readed, NULL)>0) {
WriteFile(output, block, readed, NULL, NULL);
}
if(GetLastError()==ERROR_HANDLE_EOF) {
result = true;
}
else {
result = false;
}
CloseHandle(output);
}
else {
result = false;
}
CloseHandle(input);
}
else {
result = true;
}
if(result) {
return 0;
}
else {
return GetLastError();
}
return result;
}
uint32_t copy_api(char* source, char* destination) {...}
#define COPY_READWRITE
#ifdef COPY_C
#define COPY copy_c
#else
#ifdef COPY_READWRITE
#define COPY copy_api_readwrite
#else
#ifdef COPY_API
#define COPY copy_api
#endif
#endif
#endif
int main(int argc, char** argv) {
if(argc<3) {
std::cout << "Bad command line arguments\n";
return 1;
}
uint32_t result = COPY(argv[1], argv[2]);
if(result==0) {
std::cout << "Success\n";
return 0;
}
else {
std::cout << "Error : " << result << "\n";
return 2;
}
}
From the documentation of WriteFile:
lpNumberOfBytesWritten
This parameter can be NULL only when the lpOverlapped parameter is not NULL.
You are not meeting that requirement. You will have to pass the address of a DWORD variable into which the number of bytes written will be stored.
Another mistake is in the test of the return value of ReadFile. Instead of testing ReadFile(...) > 0 you must test ReadFile(...) != 0, again as described in the documentation.
You don't check the return value of WriteFile which I also would regard as a mistake.
By definition, sizeof(char) == 1. It is idiomatic to make use of that.
When dealing with binary data, as you are, again it is idiomatic to use unsigned char.
More idiom. Write the assignment of result like this:
result = (GetLastError() == ERROR_HANDLE_EOF);
I spent much time to capture unhandled exceptions in my process (win32) using API so called setunhandledexceptionfilter().
But I haven't captured exception when WER(Windows Error Report - which is well know for DR.watson) is showed.
Is impossible to catch all of exceptions without third-party in my APP?
I think that there is method for handling, but I don't get it.
I am not accustomed to Windows DEV environment. that's why I lost my mental in googling.
Below is my test-case in vc110(Visual Studio 2012).
chat test[65];
int main() {
// after attaching unhandled exception call-back using setunhandledexceptionfilter()
// die point (ACCESS_VIOLATION c0000005)
for (int k=0; k<1000000; k++)
test[k]=65;
My callback isn't called after WER(windows Error Report) occurs. It doesn't work as my intend.
*But strcpy(NULL, "TEST") which is okay (SUCCESS)*
Below is my source code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <assert.h>
#include <process.h>
#include <direct.h>
#include <conio.h>
#include <time.h>
#include <Windows.h>
#include <tchar.h>
#include <dbghelp.h>
#include <stdio.h>
#include <crtdbg.h>
#include <WinBase.h>
#pragma comment ( lib, "dbghelp.lib" )
void CreateMiniDump( EXCEPTION_POINTERS* pep );
BOOL CALLBACK MyMiniDumpCallback(
PVOID pParam,
const PMINIDUMP_CALLBACK_INPUT pInput,
PMINIDUMP_CALLBACK_OUTPUT pOutput
);
///////////////////////////////////////////////////////////////////////////////
// Minidump creation function
//
#if 0
LONG WINAPI lpTopLevelExceptionFilter(EXCEPTION_POINTERS* ExceptionInfo);
#endif
void CreateMiniDump( EXCEPTION_POINTERS* pep )
{
time_t t;
struct tm *tinfo;
wchar_t dump_name[128];
HANDLE hFile;
time(&t);
tinfo = localtime(&t);
wcsftime(dump_name, 128, L"MiniDump[%Y%m%d][%H_%M_%S].dmp", tinfo);
// file format MiniDump[YYYYMMDD][HH_MM_SEC]
hFile = CreateFile(dump_name, GENERIC_READ | GENERIC_WRITE,
0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
if( ( hFile != NULL ) && ( hFile != INVALID_HANDLE_VALUE ) )
{
// Create the minidump
MINIDUMP_EXCEPTION_INFORMATION mdei;
MINIDUMP_CALLBACK_INFORMATION mci;
MINIDUMP_TYPE mdt;
BOOL rv;
mdei.ThreadId = GetCurrentThreadId();
mdei.ExceptionPointers = pep;
mdei.ClientPointers = FALSE;
mci.CallbackRoutine = (MINIDUMP_CALLBACK_ROUTINE)MyMiniDumpCallback;
mci.CallbackParam = 0;
mdt = (MINIDUMP_TYPE)(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory| MiniDumpWithThreadInfo);
rv = MiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
hFile, mdt, (pep != 0) ? &mdei : 0, 0, &mci );
if( !rv )
_tprintf( _T("MiniDumpWriteDump failed. Error: %u \n"), GetLastError() );
else
_tprintf( _T("Minidump created.\n") );
// Close the file
CloseHandle( hFile );
}
else
{
_tprintf( _T("CreateFile failed. Error: %u \n"), GetLastError() );
}
}
///////////////////////////////////////////////////////////////////////////////
// Custom minidump callback
//
BOOL CALLBACK MyMiniDumpCallback(
PVOID pParam,
const PMINIDUMP_CALLBACK_INPUT pInput,
PMINIDUMP_CALLBACK_OUTPUT pOutput
)
{
BOOL bRet = FALSE;
// Check parameters
if( pInput == 0 )
return FALSE;
if( pOutput == 0 )
return FALSE;
// Process the callbacks
switch( pInput->CallbackType )
{
case IncludeModuleCallback:
{
// Include the module into the dump
bRet = TRUE;
}
break;
case IncludeThreadCallback:
{
// Include the thread into the dump
bRet = TRUE;
}
break;
case ModuleCallback:
{
// Does the module have ModuleReferencedByMemory flag set ?
if( !(pOutput->ModuleWriteFlags & ModuleReferencedByMemory) )
{
// No, it does not - exclude it
wprintf( L"Excluding module: %s \n", pInput->Module.FullPath );
pOutput->ModuleWriteFlags &= (~ModuleWriteModule);
}
bRet = TRUE;
}
break;
case ThreadCallback:
{
// Include all thread information into the minidump
bRet = TRUE;
}
break;
case ThreadExCallback:
{
// Include this information
bRet = TRUE;
}
break;
case MemoryCallback:
{
// We do not include any information here -> return FALSE
bRet = FALSE;
}
break;
case CancelCallback:
break;
}
return bRet;
}
LONG WINAPI exception_filter_func(EXCEPTION_POINTERS* pep)
{
if (pep == NULL) {
return EXCEPTION_EXECUTE_HANDLER;
}
if (pep->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW) {
HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CreateMiniDump, pep, 0, NULL);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
} else {
CreateMiniDump(pep);
}
return EXCEPTION_EXECUTE_HANDLER;
}
char test[65];
int main(int argc, char **argv)
{
int k;
SetUnhandledExceptionFilter(exception_filter_func);
// exception occured (ACCESS_VIOLATION)
for (k=0; k<1000000; k++)
test[k]=65;
}
In Qt Creator, I could view the qDebug(), qWarning() etc. output directly in the IDE. How could I do this in Visual Studio?
There is an easier way:
Go to Project Properties > Linker > System : set SubSystem to "SUBSYSTEM:CONSOLE"
You will now get a console when you run your program and qDebug() will be redirected to it. (You can also use std::cout)
When you run the program with an attached debugger, it will show in the Output Window of Visual Studio, but for Debug purposes i often redirect the debug output to some kind of nice log window, which you can do by using the function qInstallMsgHandler:
the code that i use:
#include <qapplication.h>
#include <qwidget.h>
#include <qplaintextedit.h>
#include <qmetaobject.h>
#include <qthread.h>
#include <qboxlayout.h>
#include <qdatetime.h>
#include <qdebug.h>
#include <cstdio>
#include <cassert>
QWidget *DEBUG_MESSAGE_DISPLAY_WIDGET = NULL;
QPlainTextEdit *DEBUG_MESSAGE_DISPLAY_TEXTEDIT = NULL;
void setupDebugDisplay();
void debugMessageDisplayFunc(QtMsgType type, const char *msg);
int main( int argc, char* argv[] )
{
QApplication a( argc, argv );
a.setQuitOnLastWindowClosed( true );
setupDebugDisplay();
// your code here.... e.g:
// YourMainWindow mainWindow;
int ret = a.exec();
delete DEBUG_MESSAGE_DISPLAY_WIDGET;
return ret;
}
void setupDebugDisplay()
{
QWidget *widget = new QWidget();
widget->setWindowTitle( "Debug Log" );
widget->setAttribute( Qt::WA_QuitOnClose, false ); //quit only when mainwindow is closed
QBoxLayout* layout = new QVBoxLayout();
widget->setLayout( layout );
QPlainTextEdit *textEdit = new QPlainTextEdit( widget );
QFont font = QFont( "Monospace" );
font.setStyleHint(QFont::TypeWriter);
textEdit->setFont( font );
textEdit->setReadOnly(true);
layout->addWidget( textEdit );
widget->show();
DEBUG_MESSAGE_DISPLAY_WIDGET = widget;
DEBUG_MESSAGE_DISPLAY_TEXTEDIT = textEdit;
qInstallMsgHandler(debugMessageDisplayFunc);
}
void debugMessageDisplayFunc(QtMsgType type, const char *msg)
{
bool do_abort = false;
const char* msgTypeStr = NULL;
switch (type) {
case QtDebugMsg:
msgTypeStr = "Debug";
break;
case QtWarningMsg:
msgTypeStr = "Warning";
break;
case QtCriticalMsg:
msgTypeStr = "Critical";
break;
case QtFatalMsg:
msgTypeStr = "Fatal";
do_abort = true;
default:
assert(0);
return;
}
QTime now = QTime::currentTime();
QString formattedMessage =
QString::fromLatin1("%1 %2 %3")
.arg(now.toString("hh:mm:ss:zzz"))
.arg(msgTypeStr).arg(msg);
// print on console:
fprintf( stderr, "%s\n", formattedMessage.toLocal8Bit().constData() );
// print in debug log window
{
bool isMainThread = QThread::currentThread() == QApplication::instance()->thread();
if(DEBUG_MESSAGE_DISPLAY_TEXTEDIT)
{
if( isMainThread )
DEBUG_MESSAGE_DISPLAY_TEXTEDIT->appendPlainText( formattedMessage );
else // additional code, so that qDebug calls in threads will work aswell
QMetaObject::invokeMethod( DEBUG_MESSAGE_DISPLAY_TEXTEDIT, "appendPlainText", Qt::QueuedConnection, Q_ARG( QString, formattedMessage ) );
}
}
}
It redirect to Output windows of visual studio.
You may as well use DebugView++ for QDebug it still works with it
https://github.com/CobaltFusion/DebugViewPP
OutputDebugString is key to do that.
How I do with Qt 5.15:
#if defined(Q_OS_WIN) && defined(QT_DEBUG)
qInstallMessageHandler([](QtMsgType type, const QMessageLogContext &ctx, const QString &message) {
const QString msg = qFormatLogMessage(type, ctx, message);
// write logs to Output window of Visual Studio
{
QString prefix;
switch (type) {
case QtWarningMsg:
prefix = "[WARNING] ";
break;
case QtCriticalMsg:
prefix = "[CRITICAL ERROR] ";
break;
case QtFatalMsg:
prefix = "[FATAL ERROR] ";
break;
}
auto msgW = QString(prefix + message).toStdWString();
msgW.append(L"\n");
OutputDebugString(msgW.c_str());
}
});
#endif