DirectX 11:运行简单的DirectX应用程序时运行时崩溃

时间:2014-08-29 18:40:47

标签: c++ class winapi inheritance directx

我试图从基类继承一些公共全局变量并成功启动并运行窗口并以类似的方式初始化directx - 在它自己的类中继承全局变量,例如HWND hWnd。< / p>

然而,当程序运行时,D3D11CreateDeviceAndSwapChain()失败。在进一步检查时,调试器给出:

DXGI ERROR: IDXGIFactory::CreateSwapChain: No target window specified in DXGI_SWAP_CHAIN_DESC, and no window associated with owning factory. [ MISCELLANEOUS ERROR #6: ]

DXGI_SWAP_CHAIN_DESC结构如下:

SwapChainDesc.BufferCount = 1;
SwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
SwapChainDesc.BufferDesc.Width = 1024;
SwapChainDesc.BufferDesc.Height = 768;
SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
SwapChainDesc.OutputWindow = hWnd;
SwapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
SwapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
SwapChainDesc.SampleDesc.Count = 4;
SwapChainDesc.Windowed = TRUE;
SwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

hWnd存储在:

class Infinity{
public:
    Infinity();
    ~Infinity();
    HWND hWnd;
};

并继承如下:

class Direct3D : public Infinity{
public:
    Direct3D();
    ~Direct3D();
    IDXGISwapChain          *Swapchain; //Display modes.
    ID3D11Device            *Device;
    ID3D11DeviceContext     *DeviceContext;
    ID3D11RenderTargetView  *RenderTargetView;

    void D3D_Start(int width, int height);
    void D3D_Render();
    void D3D_Terminate();
}Direct3D;

在运行时检查SwapChainDesc.OutputWindow = hWnd;的值,它为空。 (0x00000000)我认为这是导致Swapchain->GetBuffer失败的原因,因为D3D11CreateDeviceAndSwapChain需要有效HWND。如果是这样,为什么ShowWindow()成功?

修改:我还应该补充一点,ShowWindow()属于继承自class Infinity的类似类:

class Windows : public Infinity{
public:
    Windows();
    ~Windows();
    bool DisplayWindow(int width, int height, HINSTANCE hInstance);
    static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
}Windows;

1 个答案:

答案 0 :(得分:0)

请注意以下代码:

class A {
public:
    int memA;
    static int memB;
};

int A::memB = 0;

class B : public A {};

class C : public A {};

int main() {
    A a;
    B b;
    C c;

    a.memA = 4;
    b.memA = 5;
    c.memA = 6;

    A::memB = 4;
    B::memB = 5;
    C::memB = 6;

    printf("a.memA = %d\n", a.memA);
    printf("b.memA = %d\n", b.memA);
    printf("c.memA = %d\n", c.memA);

    printf("A::memB = %d\n", A::memB);
    printf("B::memB = %d\n", B::memB);
    printf("C::memB = %d\n", C::memB);

    return 0;
}

此代码的输出为:

a.memA = 4
b.memA = 5
c.memA = 6
A::memB = 6
B::memB = 6
C::memB = 6

通过使成员静态,您可以确保:A)该成员只有一个实例和B)所有子类都可以直接访问该成员(假设它不是私有的)。您的代码编写时,您的hWnd不是全局的,但是将其静态化将完成您想要的任务。

以下代码执行此操作:

//header file
class Infinity {
public:
    static HWND hWnd;
};

//cpp file
HWND Infinity::hWnd = NULL;

您的Direct3D类将能够访问Window类写入的非null hWnd。如果您打算创建一个窗口,这只是一个有效的解决方案 - 否则,您将不得不求助于两个类之间更复杂的父子关系(可能不使用继承)。