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.

5
  • 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? Commented Jun 17, 2022 at 8: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. Commented Jun 17, 2022 at 8: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. Commented Jun 17, 2022 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. Commented Jun 18, 2022 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! Commented Jan 31, 2023 at 16:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.