Blueeyes789
Blueeyes789

Reputation: 573

WScript.CreateObject returns empty when calling a C++ COM dll function

I have a C++ COM dll project and the following function works fine when called from its COM object in a VB Script file.

[id(1)] HRESULT ShowMessage([in] BSTR sMessage, BSTR sTitle); //<< .IDL File

STDMETHOD(ShowMessage)(BSTR sMessage, BSTR sTitle); //<< Header File

STDMETHODIMP CFoo::ShowMessage(BSTR sMessage, BSTR sTitle) //<< C++ Source File
{
    MessageBox(0, CString(sMessage), CString(sTitle), 0);
    return S_OK;
}

Above function works fine when I call it from VB Script like this:

Dim Test: Set Test = WScript.CreateObject("VbsEvents.dll")
Test.ShowMessage "Hello World!", "Windows Script Host"

However, If I declare function like below:

[id(2)] HRESULT Add([in] int Value1, int Value2, [out] int *ReturnValue); //<< .IDL File

STDMETHOD(Add)(int Value1, int Value2, int *ReturnValue); //<< Header File

STDMETHODIMP CFoo::Add(int Value1, int Value2, int *ReturnValue) //<< C++ Source File
{
    *ReturnValue = Value1 + Value2;
    return S_OK;
}

and call it from VB Script like:

Dim Return: Test.Add 1, 2, CInt(Return)
WScript.Echo CStr(Return)

I keep getting nothing echoed, and I expect this to echo 3 as result. I can't figure out why this function not working in VB Script.

Any help is appreciated to find what's the reason for this VB Script code to echo nothing.

Upvotes: 0

Views: 415

Answers (1)

Simon Mourier
Simon Mourier

Reputation: 138915

What you could do is change the IDL signature from this

[id(2)] HRESULT Add([in] int Value1, int Value2, [out] int *ReturnValue);

to this

[id(2)] HRESULT Add([in] int Value1, int Value2, [out, retval] int *ReturnValue);

which makes a lot of sense here because it is semantically a return value. See the retval attribute documentation for info on this.

Then you can call it like this in VBScript:

ret = Add(1, 2)

Otherwise, check this for more on byref in VBScript: ByRef and ByVal in VBScript

Upvotes: 1

Related Questions