我无法执行一些winapi代码。我不知道原因是因为我在编译过程中遗漏了什么,或者测试程序是否错误;但是当我执行程序时,Bitmap定义行会给出 segfault 。
这是测试程序
#include <windows.h>
#include <gdiplus.h>
int WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
Gdiplus::PixelFormat* pf = new Gdiplus::PixelFormat();
Gdiplus::Bitmap* bitmap = new Gdiplus::Bitmap(100, 100, *pf);
return 0;
}
这是编译指令:
> mingw32-g++ main.cpp -lgdiplus -o main.exe
当我执行时,我有这个:
Program received signal SIGSEGV, Segmentation fault.
0x00403da3 in Gdiplus::Image::Image (this=0x0, image=0x0, status=Gdiplus::Ok) at c:/mingw/include/gdiplus/gdiplusheaders.h:142
142 nativeImage(image), lastStatus(status) {}
我做了一些winapi教程并创建了一个窗口,所以我觉得我的MinGW安装没有错。
可能是什么问题?
答案 0 :(得分:1)
错误是因为GDI +未被初始化。您最后可以在Gdiplus::GdiplusStartup
和main
的顶部调用Gdiplus::GdiplusShutdown
,但是通过将其包装在一个类中,我们可以使用advantage of RAII并自动执行初始化和释放如果出现任何问题,应该少搞麻烦。
#include <stdexcept>
#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
// GDI+ wrapper class
class GdiplusRAII
{
ULONG_PTR gdiplusToken;
public:
GdiplusRAII()
{
Gdiplus::GdiplusStartupInput input;
Gdiplus::Status status = Gdiplus::GdiplusStartup(&gdiplusToken, &input, NULL);
if (status != Gdiplus::Ok)
{
throw std::runtime_error("Could not initialize GDI+");
}
}
~GdiplusRAII()
{
Gdiplus::GdiplusShutdown(gdiplusToken);
}
};
int WinMain(HINSTANCE ,
HINSTANCE ,
LPSTR ,
int ) // not using the parameters so I left them out.
{
GdiplusRAII raii; // initialize GDI+
// no need to new a PixelFormat. It is just an int associated with a
// collection of defined constants. I'm going to pick one that sounds
// reasonable to minimize the potential for a nasty surprise and use it
// directly in the Gdiplus::Bitmap constructor call.
// Probably no need to new the bitmap. In fact you'll find that most of
// the time it is better to not new at all.
Gdiplus::Bitmap bitmap(100, 100, PixelFormat32bppARGB);
return 0;
// GDI+ will be shutdown when raii goes out of scope and its destructor runs.
}