haxiomic / haxe-c-bridge

Easily interact with haxe classes from C with an automatically generated C header
MIT License
51 stars 5 forks source link

Dynamic type #46

Open Ilir-Liburn opened 2 years ago

Ilir-Liburn commented 2 years ago

Hello,

I tried using Dynamic type via haxe-c-bridge and it works! The most interesting part is happening due to memory alignment ( see printDynamicType function ).

Now I wonder if there is a better way to get ValueType ( outside of the Haxe code or by reducing the Haxe code ).

Edit:

I tested this using Win32 because I don't have 64 bit version of cl, can't compile 64bit version even gcc 64 bit version is used ( see https://github.com/haxiomic/haxe-c-bridge/issues/38 )

[ add to src/Main.hx at Main class ]

    static public function getDynamicInt() {
        var val:Int = -1; 
        var dyn:Any = val;
        return dyn;
    }

    static public function getDynamicFloat() {
        var val:Float = 99234234.99234234; 
        var dyn:Any = val;
        return dyn;
    }

    static public function getDynamicType(dyn:Any) {
        var idx = Type.typeof(dyn).getIndex();
        var arr = Type.getEnumConstructs(Type.ValueType);
        trace("HaxeEnumType = " + arr[idx]);
        return idx; 
    }

[ add to App.c ]

enum HaxeValueType
{
    TNull = 0,
    TInt = 1,
    TFloat = 2,
    TBool = 3,
    TObject = 4,
    TFunction = 5,
    TClass = 6,
    TEnum = 7,
    TUnknown = 8
};

void printDynamicType(enum HaxeValueType en,HaxeObject *obj) {
    switch (en) {
        default :
            printf("HaxeDynamicValue = Unknown (temporary:)\n");
            break ;
        case TInt :
            printf("HaxeDynamicValue = %d\n",((int *)obj)[1]);
            break ;
        case TFloat :
            printf("HaxeDynamicValue = %f\n",((double *)obj)[1]);
            break ;
    }
}

    HaxeObject int_obj = HaxeLib_Main_getDynamicInt();
    enum HaxeValueType int_en = HaxeLib_Main_getDynamicType(int_obj);
    printDynamicType(int_en,int_obj);

    HaxeObject float_obj = HaxeLib_Main_getDynamicFloat();
    enum HaxeValueType float_en = HaxeLib_Main_getDynamicType(float_obj);
    printDynamicType(float_en,float_obj);