为什么PrivateFontCollection AddFontFile引发访问冲突异常?

时间:2019-07-04 16:48:28

标签: c++ mfc gdi+

尝试使用以下代码向C ++ MFC应用程序添加自定义字体:

void CMFCApplication1View::OnInitialUpdate()
{
    CFormView::OnInitialUpdate();

    // ...

    // dynamic path 
    std::string test = std::string("Oswald.ttf");
    std::string path = this->ExePath() + test;
    std::wstring widestr = std::wstring(path.begin(), path.end());
    const wchar_t* widecstr = widestr.c_str();

    // hardcoded path
    std::string s = R"(D:\DEV\C\CTests\MFCApplication1\Debug\Oswald.ttf)";
    std::wstring r = std::wstring(s.begin(), s.end());
    const wchar_t* t = r.c_str();

    Gdiplus::PrivateFontCollection m_fontcollection;
    Gdiplus::Status nResults = m_fontcollection.AddFontFile(t); // access violation exception thrown here

    // ...
}

std::string CMFCApplication1View::ExePath() {
    char buffer[MAX_PATH];
    GetModuleFileNameA(NULL, buffer, MAX_PATH);
    std::string::size_type pos = std::string(buffer).find_last_of("\\/");
    return std::string(buffer).substr(0, pos + 1);
}

我是C ++的新手(来自C#)。调用AddFontFile时,该代码将引发访问冲突异常(具有硬编码和动态版本),但是路径的值正确。

我缺少明显的东西吗?


更新

根据评论,这就是我现在所做的。它似乎正在运行,并且没有更多的转换功能,但是正如我所说,要确定自己做得对,还需要一段时间。

void CMFCApplication1View::OnInitialUpdate()
{
    CFormView::OnInitialUpdate();

    // ...

    // font path 
    // const wchar_t* path = (this->ExePath() + std::wstring(L"Oswald.ttf")).c_str();
    const wchar_t* path = &(this->ExePath() + std::wstring(L"Oswald.ttf"))[0];

    // Gdiplus init
    ULONG_PTR gdiplusToken; 
    Gdiplus::GdiplusStartupInput gdiplusStartupInput;
    Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

    // Gdiplus font
    Gdiplus::PrivateFontCollection m_fontcollection;
    Gdiplus::Status nResults = m_fontcollection.AddFontFile(path);

    // ...
}

std::wstring CMFCApplication1View::ExePath() {
    wchar_t buffer[MAX_PATH];
    GetModuleFileNameW(NULL, buffer, MAX_PATH);
    std::wstring::size_type pos = (std::wstring(buffer)).find_last_of(L"\\/");
    return std::wstring(buffer).substr(0, pos + 1);
}

以上使用c_str()或分配&wstring [0]的转换基于以下答案: https://stackoverflow.com/a/16113660/2983568

0 个答案:

没有答案