'Declare DLL functions with PtrSafe
Declare PtrSafe Sub vba_sample_initialize Lib "vba_sample_win64.dll" ()
Declare PtrSafe Sub vba_sample_step Lib "vba_sample_win64.dll" ()
Declare PtrSafe Sub vba_sample_terminate Lib "vba_sample_win64.dll" ()
'Declare external input structure
Public Type ExtU
Inport1 As Double
Inport2 As Double
End Type
'Declare external output structure
Public Type ExtY
Outport1 As Double
End Type
'Declare external input and output variables
Public rtU As ExtU
Public rtY As ExtY
'Declare functions to get the addresses of external input and output variables with PtrSafe
Declare PtrSafe Function get_rtU_address Lib "vba_sample_win64.dll" () As LongPtr
Declare PtrSafe Function get_rtY_address Lib "vba_sample_win64.dll" () As LongPtr
'Declare CopyMemory function with PtrSafe (Windows API)
Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
Sub CallSimulinkModel()
'Initialize
vba_sample_initialize
'Set inputs from Excel cells
rtU.Inport1 = Sheets("Sheet1").Range("A1").Value
rtU.Inport2 = Sheets("Sheet1").Range("A2").Value
'Pass the address of rtU to the DLL
Dim rtUAddress As LongPtr
rtUAddress = get_rtU_address()
CopyMemory ByVal rtUAddress, rtU, LenB(rtU)
'Execute one step
vba_sample_step
'Get output values from the address of rtY
Dim rtYAddress As LongPtr
rtYAddress = get_rtY_address()
CopyMemory rtY, ByVal rtYAddress, LenB(rtY)
'Display the result
MsgBox "The result of adding " & rtU.Inport1 & " and " & rtU.Inport2 & " is " & rtY.Outport1
'Terminate
vba_sample_terminate
End Sub