博客园  :: 首页  :: 联系 :: 管理

Debugging a C++ DLL from VBA

Posted on 2012-06-06 15:42  sunrack  阅读(353)  评论(0编辑  收藏  举报

Here's the answer(s).
I managed to figure out a way of doing it.   Include assert.h and place an assertion at the top of your function call.  Like this:

Code Block

#include "stdafx.h" #include <assert.h>
BOOL APIENTRY DllMain( HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved ) {     return TRUE; }
long __stdcall sumLongs2D( long *arrayOfLongs, long N1, long N2 ) {     assert( false );
    long sum = 0;
    for (int i=0; i < N1; i++)         for (int j=0; j < N2; j++)             sum += *(arrayOfLongs + i*sizeof(long) + j);
     return sum; }

You can leave Visual Studio running if you like.
Next run Excel and load the spreadsheet that contains the VBA function that calls this function.   Run the function.   The assert will cause a SIGABRT to be raised.   You have a few dialogs to click through, which should be fairly obvious to navigate ("Do you want to debug the program?").  You'll be dumped into the code for assert().    Click "step out" to leave the stack frame for assert() and you're dumped into your DLL function and can perform debugging to your heart's content.
You can write a little macro function that gets defined whenever you set /D DEBUGDLL so that the assert is called only when you want to debug the DLL but gets left out of the code otherwise.   With the code snippet below, you'd replace the call to assert() with BREAK_IF_DEBUG.
Code Block

#pragma once
#ifdef DEBUGDLL #include <assert.h>
#define BREAK_IF_DEBUG assert(false); #else #define BREAK_IF_DEBUG #endif

It's a total hack, and aesthetically ugly, but convenient.    This method is the "real" method, is more elegant but a little less convenient.
1. Set: Project Properties | Debugging | Command = C:\Program Files\Microsoft Office\OFFICE11\EXCEL.EXE 2. Make sure you're using the debug configuration so that the symbol table is generated. 3. Set Project Properties | C/C++ | Browse Information | Enable Browse Info = Include All Browse Information (/FR) 4. Put your cursor somewhere in the C++ DLL function that you want to debug.   Set a breakpoint somewhere. 5. Run it (F5).   Excel will run. 6. From Excel, load the spreadsheet that contains the VBA function that calls your C++ DLL function. 7. Run the VBA function that calls the C++ DLL function.
You'll be debugging the C++ DLL.   This method is a little less convenient than my method because eveytime you want to debug the DLL, Excel will run and you need to reload your spreadsheet, view the VBA code editor, navigate to your function, and run the VBA function.   In my method, the VBA code window stays open always.
So there you go.  Two ways to debug the C++ code in a DLL that's called by VBA.   Hope this is useful.
Pete