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

How to make GC not recycle a variable #29

Closed rainyt closed 3 years ago

rainyt commented 3 years ago

Hi, this question has nothing to do with the haxe-c-bridge, but I'd like to know the answer. I'm using the static library file (. A) on the openfl thread now, but I find that the address error often occurs. I guess it's caused by GC, so is there a way not to be recycled by GC. @haxiomic

haxiomic commented 3 years ago

In haxe-c-bridge I simply store that object in a map so haxe won't clear it because it's still referenced

However from reading the hxcpp source suspect there's another native approach using the hxcpp internal API, I just decided this one way more future proof and portable

https://github.com/haxiomic/haxe-c-bridge/blob/10a64714df32e1a093bec25f068f73f507e83460/HaxeCBridge.hx#L1728

I use the object's pointer as the map key so that when the user is finished with the object, they can call release(obj) to enable GC again and we can easily and efficiently remove the entry from the map

https://github.com/haxiomic/haxe-c-bridge/blob/10a64714df32e1a093bec25f068f73f507e83460/HaxeCBridge.hx#L1740

rainyt commented 3 years ago
public static function initKengSDK(appid:String):Dynamic {
        log("initKengSDK:" + appid);
        _kengAppId = appid;
        Cmnt.init(appid, null, "test");
        var kengsdk = new KengSDKCpp();
        if(Internal.gcRetainMap == null){
            trace("gcRetainMap is null");
        }
        else
            Internal.gcRetainMap.set(1,kengsdk);
        return kengsdk;
    }

I also implemented an internal. Gcretainmap object, but found that it was null. Do I need a method to start it boot() and register()?

Log: src/KengSDKHaxe.hx:34: gcRetainMap is null
haxiomic commented 3 years ago

You can initialize it in a static and it will be created during boot I think https://github.com/haxiomic/haxe-c-bridge/blob/10a64714df32e1a093bec25f068f73f507e83460/HaxeCBridge.hx#L1775

If you use pointers for keys you cannot use Map<Int64, Any> because hxcpp doesn't yet support Int64 maps, I've implemented one here https://github.com/haxiomic/haxe-c-bridge/blob/10a64714df32e1a093bec25f068f73f507e83460/HaxeCBridge.hx#L1783

rainyt commented 3 years ago

thank you! I understand that it's because there is no boot () process. Now I need to use a new way to implement it!

haxiomic commented 3 years ago

Sweet :), good luck!

Still recommend giving this lib another look, it’s the result of a couple years working with haxe from C and learning the pitfalls and edge cases. In the future it would be nice if some of these stuff was merged into the compiler so we don’t need a lib

It’s a single file so you can copy and paste into your project to keep things simple