运行时检查失败#0 - 未正确保存ESP的值

时间:2011-12-21 20:53:29

标签: c++ excel automation runtime runtime-error

我正在尝试从C ++代码编译Excel自动化访问的示例,我收到以下错误:“运行时检查失败#0 - ESP的值未在函数调用中正确保存。这通常是结果调用使用一个调用约定声明的函数,并使用不同的调用约定声明函数指针。“

我已经在互联网上找到并阅读了大量关于此错误的信息,但仍然无法明确我应该在我的代码中修复哪些内容才能使其正常工作。请查看代码:

#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;
}

2 个答案:

答案 0 :(得分:6)

EnumChildWindows(..., (WNDENUMPROC) EnumChildProc, ...);

那个(WNDENUMPROC)演员刚刚停止编译器告诉你你做错了。它并没有阻止你做错。修正:

BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM)
{
    // etc..
}

注意添加的CALLBACK宏,它为回调选择所需的__stdcall调用约定。没有它,它默认为__cdecl,这是另一个调用约定,要求调用者在调用后清理堆栈。哪个不会发生,从而使堆栈失衡。

正确的回调签名是documented here

答案 1 :(得分:4)

BOOL EnumChildProc(HWND hwnd, LPARAM)

需要:

BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM)