I'm working with the CScriptAny class and have run into behavior I can't understand.
Two problems:
- When a float is stored in an any, any.GetTypeId() returns a different result than GetTypeIdByDecl(). 11 (double) and 10 (float) respectively.
- When the correct type (10 for float) is used in any.Retrieve, an assert fails. When the incorrect type is used (11 for double) the result is garbage
My goal is to (in script) store a float into an any object, then pass it to c++ via a function call.
What am I missing here? Code below.
Script Code:
void main()
{
float f1, f2;
any a1;
f1 = 11.11;
f2 = 22.22;
a1.store(f1);
takeany(a1);
}
Registration of takeany in c++:
RegisterGlobalFunction("void takeany(any &)", asFUNCTION(takeany), asCALL_CDECL);
function takeany() in c++: (please forgive my use of printf, i find it easier to use when looking at pointers)
void takeany(CScriptAny &a)
{
float value;
int type_id;
void *val_ptr = operator new(4); //4 bytes for float
asIScriptContext *ctx = asGetActiveContext();
asIScriptEngine* engine = ctx->GetEngine();
cout<<"in takeany\n";
printf("value of val_ptr: %i \n", *static_cast<int*>(val_ptr));
type_id = a.GetTypeId();
cout<<"typeid is: "<<type_id<<endl;
type_id = engine->GetTypeIdByDecl("float");
cout<<"typeid is: "<<type_id<<endl;
//method 1
a.Retrieve(val_ptr, type_id);
printf("value at val_ptr: %f \n", *static_cast<float*>(val_ptr));
//method 2
a.Retrieve(static_cast<void*>(&value),type_id);
printf("value of value: %f \n", value);
value = *static_cast<float*>(val_ptr);
cout<<value<<endl;
}
This produces the following on the terminal:
in takeany
value of val_ptr: 438831032
typeid is: 11
typeid is: 10
better_print_2: ../../sdk/add_on/scriptany/scriptany.cpp:329: bool CScriptAny::Retrieve(void*, int) const: Assertion `refTypeId > asTYPEID_DOUBLE || refTypeId == asTYPEID_BOOL || refTypeId == asTYPEID_INT64 || refTypeId == asTYPEID_DOUBLE' failed.
Aborted
Note that type 10 corresponds to a float, type 11 corresponds to a double.