Introduction
While we were designing the plugin architecture for epAssist, we discovered an interesting problem with the MFC implementation of CString::LoadString()
. The string resource will not load under certain conditions.
Our plugin architecture is basically re-named DLLs with a standardized interface where the plugins provide a dictionary, grammar, and actions for the main language parser to parse sentences. On a successful parsing match, the program will invoke the proper action.
The main application loads the plugins (DLLs) using LoadLibrary
, then locates and calls a function to get the description, copyright, and so forth.
The Problem
All the plugins are created with a Visual Studio AppWizard. Resources are already in place with strings for description, copyright, etc. Thus, every plugin has the same ID for the string.
CString::LoadString
will first use the instance handle of the main application to search for a string with the given ID. Failing that, it will look in DLLs in the order they were loaded until there is a match.
If DLL A is loaded, then B and C, calling LoadString
from DLL C will first find a matching resource in DLL A before finding its own resource.
The end result of this is that all plugins show the same description and other properties.
The Solution
The function LoadStringFromDLL()
was created. It takes an instance handle (can be the main application, any DLL, or any other application) and the resource ID.
Using this as a starting point, you can also create LoadIconFromDLL
, or any other resource type.
There is an artificial limit of 255 characters for the string resource. You can change the memory allocation scheme to suit your own needs.
#pragma once
#ifndef RESOURCE_TO_CSTRING
#define RESOURCE_TO_CSTRING
inline CString LoadStringFromDLL(HINSTANCE hInst, int ids)
{
if (!hInst) {
ASSERT(0);
return "Error loading resource.";
}
CString str;
TCHAR szTemp[256];
int nLen;
LPCTSTR lpszName = MAKEINTRESOURCE((ids>>4)+1);
if (::FindResource(hInst, lpszName, RT_STRING) != NULL &&
(nLen = ::LoadString(hInst, ids, szTemp, 255) != 0)) {
str = szTemp;
}
return str;
}
#endif
Jim is the President of Golden Crater Corp. (formerly Golden Crater Software) which produces:
Tiny eBook Reader - Read eBooks anywhere, on any web enabled device or phone.
Doberman BMS - Home Automation and Building Management System bridging and enhancing several automation hardware platforms.