Thanks for sharing the details and updated sample!
The exception occurs because of stack alignment and mixed-mode issues on x64 when calling unmanaged functions from VBA under a debugger. Here’s how to resolve it:
Root Cause
- On 64-bit Office,
__stdcallis ignored; all functions use the Microsoft x64 calling convention. - Mixed-mode (C++/CLI) DLLs can introduce alignment problems if unmanaged entry points aren’t fully isolated.
- VBA
Longis always 32-bit, even in 64-bit Office, so argument size mismatch can corrupt the stack. - Debugger attachment triggers VBE logging routines, which can misinterpret arguments.
Solution
- Remove
__stdcall(you already did this). - Force unmanaged context for exported functions:
#pragma managed(push, off) extern "C" __declspec(dllexport) int CalcIntByVal(int value) { return 42 + value; } extern "C" __declspec(dllexport) double CalcDoubleByVal(double value) { return 3.14 + value; } #pragma managed(pop)
#pragma managed(push, off)
extern "C" declspec(dllexport) int CalcIntByVal(int value) { return 42 + value; }
extern "C" declspec(dllexport) double CalcDoubleByVal(double value) { return 3.14 + value; }
#pragma managed(pop)
- Compile the DLL as pure x64 native (or move these functions into a separate native DLL).
- Ensure VBA declarations match types:
Private Declare PtrSafe Function CalcIntByVal Lib "MixedLibrary.dll" (ByVal value As Long) As Long Private Declare PtrLongin VBA = 32-bit → matchesintin C++.-
Doublematches correctly.
-
Private Declare PtrSafe Function CalcIntByVal Lib "MixedLibrary.dll" (ByVal value As Long) As Long
Private Declare Ptr
- If the crash only occurs when the debugger is attached, it’s related to VBE logging and not the function itself. Test without debugger to confirm.
- For maximum stability, consider:
- Wrapping calls in COM.
- Using SafeArray or Variant for ByVal arguments.
- Wrapping calls in COM.
Reference
- 64-bit VBA and API declarations.
https://learn.microsoft.com/en-us/office/vba/library-reference/concepts/64-bit-support
Let us know if the issue persists after following these steps. I’ll be happy to assist further if needed. If the issue has been resolved, please click "Accept Answer".