December 01, 2024, 10:53:40 AM

News:

Own IWBasic 2.x ? -----> Get your free upgrade to 3.x now.........


Math evaluator

Started by sapero, May 05, 2008, 05:44:31 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

sapero

While writing software for some bux service, I needed to automate a simple but annoying "anti cheat" expression: what is x+y?
Here is the result:
#include "MSScriptControl.inc"

sub main()
{
BSTR    bstrResult;
string szResult;
LPWSTR  evaluate = L"2 + 2 * 2";

HRESULT hr = Eval(evaluate, &bstrResult);
if (!hr)
{
wsprintf(szResult, "%S = %S", evaluate, bstrResult);
SysFreeString(bstrResult);
}
else
{
wsprintf(szResult, "something failed with msscript.ocx, error: 0x%.8x", hr);
}
MessageBox(0, szResult, "eval example");
}


//------------------ msscript.ocx
#asm
align 4
CLSID_Module       dd 0xE59F1D5, 0x11D01FBE, 0xA000F28F, 0xBC3800D1 ; {0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC}
IID_IScriptControl dd 0xE59F1D3, 0x11D01FBE, 0xA000F28F, 0xBC3800D1 ; {0E59F1D3-1FBE-11D0-8FF2-00A0D10038BC}
#endasm

declare CLSID_Module();
declare IID_IScriptControl();

sub Eval(wstring *expression, BSTR *ppv),HRESULT
{
CoInitialize(0);
IScriptControl *script;
VARIANT v;
v.vt      = VT_EMPTY;
v.bstrVal = NULL;
HRESULT hr = CoCreateInstance(&CLSID_Module, 0, CLSCTX_INPROC_SERVER, &IID_IScriptControl, &script);
if (!hr)
{
// set language: JScript or VBScript
BSTR bstrLang = SysAllocString(L"JScript");
hr = script->put_Language(bstrLang);
SysFreeString(bstrLang);
if (!hr)
{
script->put_UseSafeSubset(VARIANT_FALSE);

BSTR bstrExp = SysAllocString(expression);
hr = script->Eval(bstrExp, &v);
SysFreeString(bstrExp);

if (!hr)
// change type to string
hr = VariantChangeType(&v, &v, 0, VT_BSTR);

script->Release();
}
}
CoUninitialize();
*ppv = v.bstrVal;
return hr;
}