0

.h file conent:

extern "C" __declspec(dllexport) double WINAPI P452Calc(int, int *);

.cpp file content:

double WINAPI P452Calc(int i, int * ii) {
    return i;
}

VBA code:

Declare PtrSafe Function P452Calc Lib "P452Lib.dll" (ByVal i As Integer, ByRef ii As Integer) As Double
Public Function Test()
    Dim i As Integer
    Dim ii As Integer
    i = 33
    ii = 2
    Test = P452Calc(i, ii)
End Function

Exception thrown at 0x00007FF9833F917F (kernel32.dll) in EXCEL.EXE: 0xC0000005: Access violation reading location 0x0000000000000021. (21h == 33 i variable value)

I can not figure out what exactly wrong.

  • The default calling convention for C++ is `__cdecl`. Did you specify that in your VB code? Or similarly, did you specify `__stdcall` in the C++ code, to match the default VB calling convention? – PaulMcKenzie Jun 17 '22 at 08:04
  • Yes, the WINAPI macro resolved to ___stdcall. I am also used __stdcall directrly in C++ code, but got the same problem, so I've reverted to this code and still stuck. – Dmitriy_ru Jun 17 '22 at 08:51
  • 2
    `Access violation reading location 0x0000000000000021` -- Well, the call believes that the first parameter is a pointer. This still looks like an issue with the incorrect calling convention being used. – PaulMcKenzie Jun 17 '22 at 12:41
  • 1
    I've installed x86 excel and make x86 dll, finally it works, with all params byref, will try to flip back to 64 later. – Dmitriy_ru Jun 18 '22 at 13:14
  • I've got exactly the same issue, though whatever is first in the parameter list is passed along just fine. I don't have the option of switching to 32-bit. I agree that it looks like calling convention, but I'm using __stdcall too. The irony is I've got a preceding function with 7 parameters that works peachy! – Danny Holstein Jan 31 '23 at 16:59

1 Answers1

0

.h file conent:

extern "C" __declspec(dllexport) double WINAPI P452Calc(int, int *);

VBA code:

Declare PtrSafe Function P452Calc Lib "P452Lib.dll" (ByVal i As Integer, ByRef ii As Integer) As Double

VBA's Integer is a 16-bit integral type, while MS C implementation uses 32-bit int. You need to use Long in VBA to match the int in .h; or alternatively, you need to use short in C to match Basic's Integer.

Mike Kaganski
  • 701
  • 6
  • 18