Sub test_Toymath3()
'late-binding
'Dim Calc As ToymathLib3.Calculator
'Set Calc = CreateObject("Toymath3.Calculator.1")
'early-binding
Dim Calc As New ToymathLib3.Calculator
X = Calc.Add(100, 200)
Debug.Print X
Debug.Assert Calc.Add(10, 20) = 30
Debug.Assert Calc.Sub(10, 20) = -10
Debug.Assert Calc.Mul(10, 20) = 200
Debug.Assert Calc.Div(10, 20) = 0
End Sub
#ifndef CALCULATOR_H
#define CALCULATOR_H
#include "toymath3.h"
class Calculator : public ICalculator {
public:
Calculator(void);
protected:
virtual ~Calculator(void);
public:
STDMETHODIMP QueryInterface(REFIID riid, void **ppv);
STDMETHODIMP_(ULONG) AddRef(void);
STDMETHODIMP_(ULONG) Release(void);
STDMETHODIMP Add(long x, long y, long *result);
STDMETHODIMP Sub(long x, long y, long *result);
STDMETHODIMP Mul(long x, long y, long *result);
STDMETHODIMP Div(long x, long y, long *result);
private:
LONG m_cRef;
};
#endif // CALCULATOR_H
calculator.cpp
#include "calculator.h"
#include "modulelock.h"
#include <objbase.h>
extern IID const IID_ICalculator;
Calculator::Calculator(void) : m_cRef{0} {}
Calculator::~Calculator(void) {}
STDMETHODIMP Calculator::QueryInterface(REFIID riid, void **ppv) {
if (riid == IID_IUnknown) {
*ppv = static_cast<IUnknown *>(this);
} else if (riid == IID_ICalculator) {
*ppv = static_cast<ICalculator *>(this);
} else {
*ppv = nullptr;
return E_NOINTERFACE;
}
reinterpret_cast<IUnknown *>(*ppv)->AddRef();
return S_OK;
}
STDMETHODIMP_(ULONG) Calculator::AddRef(void) {
if (m_cRef == 0) {
LockModule();
}
return InterlockedIncrement(&m_cRef);
}
STDMETHODIMP_(ULONG) Calculator::Release(void) {
LONG res = InterlockedDecrement(&m_cRef);
if (res == 0) {
delete this;
UnlockModule();
}
return res;
}
STDMETHODIMP Calculator::Add(long x, long y, long *result) {
*result = x + y;
return S_OK;
}
STDMETHODIMP Calculator::Sub(long x, long y, long *result) {
*result = x - y;
return S_OK;
}
STDMETHODIMP Calculator::Mul(long x, long y, long *result) {
*result = x * y;
return S_OK;
}
STDMETHODIMP Calculator::Div(long x, long y, long *result) {
*result = x / y;
return S_OK;
}
import "unknwn.idl";
[object, uuid(1dc508ef-d0eb-420a-b213-dd16aa0dfee0)]
interface ICalculator : IUnknown {
HRESULT Add([in] long x, [in] long y, [out, retval] long *result);
HRESULT Sub([in] long x, [in] long y, [out, retval] long *result);
HRESULT Mul([in] long x, [in] long y, [out, retval] long *result);
HRESULT Div([in] long x, [in] long y, [out, retval] long *result);
}
[
uuid(f90bdc34-89b3-46dd-b262-edf4aba3a935),
lcid(0),
version(1.0),
helpstring("Toymath Library 3")
]
library ToymathLib3 {
importlib("stdole32.tlb");
[uuid(957E455A-8FD1-4D33-8057-462897B00888)]
coclass Calculator {
[default] interface ICalculator;
}
}