NULL指针,以为它似乎被初始化了

时间:2013-05-30 14:51:53

标签: c++ com directx smart-pointers directx-10

我得到了

Debug assertion failed.
p!=0

并指出:

    _NoAddRefReleaseOnCComPtr<T>* operator->() const throw()
    {
        ATLASSERT(p!=NULL);
        return (_NoAddRefReleaseOnCComPtr<T>*)p;
    }

在'atlcomcli.h'

根据我的理解,这意味着我忘了在某处初始化指针,但所有似乎都要初始化。

当我使用普通指针而不是'CComPtr'时,它会在D3DFont.cpp中的'D3DFont :: Draw'中的'font-&gt; DrawTextA'中抛出'Access Violation Reading Location'

//D3DFont.h:
#include <D3DX10.h>
#include <atlbase.h>
#include <string>

class D3DFont
{
public:
    D3DFont(void);
    ~D3DFont(void);

    bool Create(ID3D10Device *device, std::string name, int width,
        int height, int weight, int mipLevels, bool italic, BYTE charset,
        BYTE quality, BYTE pitchAndFamily);
    void Draw(LPD3DX10SPRITE sprite, std::string text, int charCount,
        LPRECT rect, UINT format, D3DXCOLOR color);

private:
    CComPtr<ID3DX10Font> font;
};

//D3DFont.cpp:
#include "D3DFont.h"

D3DFont::D3DFont(void){} 
D3DFont::~D3DFont(void){}

bool D3DFont::Create( ID3D10Device *device, std::string name,
    int width, int height, int weight, int mipLevels, bool italic,
    BYTE charset, BYTE quality, BYTE pitchAndFamily )
{
    D3DX10_FONT_DESC fd;
    ZeroMemory(&fd, sizeof(D3DX10_FONT_DESC));

    fd.Height = height;
    fd.Width = width;
    fd.Weight = weight;
    fd.MipLevels = mipLevels;
    fd.Italic = italic;
    fd.CharSet = charset;
    fd.Quality = quality;
    fd.PitchAndFamily = pitchAndFamily;

    strcpy_s(fd.FaceName, name.c_str());

    // INITIALIZING FONT HERE
    D3DX10CreateFontIndirect(device, &fd, &font);

    return true;
}

void D3DFont::Draw( LPD3DX10SPRITE sprite, std::string text,
    int charCount, LPRECT rect, UINT format, D3DXCOLOR color )
{
    // ERROR HERE
    font->DrawTextA(sprite, text.c_str(), charCount, rect, format, color); 
}

我使用上述功能:

if( !font.Create(d3d.GetDevice(), "Impact", 0, 175, 0, 1, false,
    OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE) )
{
    MessageBox(0, "Could not create font.", "Error!", MB_OK | MB_ICONERROR);
}

// later on...

RECT r = {35, 50, 0, 0};
font.Draw(0, "Test", -1, &r, DT_NOCLIP, d3d.GetColorObj(1.0f, 1.0f, 0.0f, 1.0f));

我能错过什么?


'D3DX10CreateFontIndirect'抛出0x8876086C 找不到它的意思,但有些谷歌线程与d3dDevice有关,所以我猜它必须与它有关。当我有更多信息时会更新。

1 个答案:

答案 0 :(得分:3)

调用D3DX10CreateFontIndirect实际上并不能保证你的指针会被初始化。

经验法则:在使用初始化指针的DirectX函数时,务必检查HRESULT

HRESULT hr = D3DX10CreateFontIndirect(device, &fd, &font);

if(FAILED(hr)){
    //Get the last error, display a message, etc.
    //Eventually propagate the error if the code can't continue 
    //with the font pointer uninitialized.
}

当函数返回E_FAIL时,请勿尝试使用指针。很有可能参数的值很不正确(这里,您的设备指针可能为null或您的字体描述可能不正确)。