I am trying to compile example of Excel automation access from C++ code and I get the following error: “Run-Time Check Failure #0 – The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.”
I’ve already found and read tons of info about this error in internet, but still can’t get the point what exactly should I fix in my code to make it work. Please review the code:
#include <windows.h>
#include <oleacc.h>
#import "C:\Program Files (x86)\Common Files\microsoft shared\OFFICE14\MSO.DLL" no_implementation rename("RGB", "ExclRGB") rename("DocumentProperties", "ExclDocumentProperties") rename("SearchPath", "ExclSearchPath")
#import "C:\Program Files (x86)\Common Files\microsoft shared\VBA\VBA6\VBE6EXT.OLB" no_implementation
#import "C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE" rename("DialogBox", "ExclDialogBox") rename("RGB", "ExclRGB") rename("CopyFile", "ExclCopyFile") rename("ReplaceText", "ExclReplaceText")
BOOL EnumChildProc(HWND hwnd, LPARAM)
{
WCHAR szClassName[64];
if(GetClassNameW(hwnd, szClassName, 64))
{
if(_wcsicmp(szClassName, L"EXCEL7") == 0)
{
//Get AccessibleObject
Excel::Window* pWindow = NULL;
HRESULT hr = AccessibleObjectFromWindow(hwnd, OBJID_NATIVEOM, __uuidof(Excel::Window), (void**)&pWindow);
if(hr == S_OK)
{
//Excel object is now in pWindow pointer, from this you can obtain the document or application
Excel::_Application* pApp = NULL;
pApp = pWindow->GetApplication();
pWindow->Release();
}
return false; // Stops enumerating through children
}
}
return true;
}
int main( int argc, CHAR* argv[])
{
//The main window in Microsoft Excel has a class name of XLMAIN
HWND excelWindow = FindWindow(L"XLMAIN", NULL);
//Use the EnumChildWindows function to iterate through all child windows until we find _WwG
EnumChildWindows(excelWindow, (WNDENUMPROC) EnumChildProc, (LPARAM)1);
return 0;
}
That (WNDENUMPROC) cast just stopped the compiler from telling you that you were doing it wrong. It didn’t stop you from doing it wrong. Fix:
Note the added CALLBACK macro, it selects the required __stdcall calling convention for the callback. Without it, it defaults to __cdecl, another calling convention that requires the caller to cleanup the stack after the call. Which won’t happen and thus imbalances the stack.
The proper callback signature is documented here.