native icon indicating copy to clipboard operation
native copied to clipboard

[ffigen] Context field for ObjC blocks/protocols

Open liamappelbe opened this issue 1 year ago • 2 comments

ObjC implementation of jnigen's context proposal for interface implementation. The idea is that this context map would be stored on the native side as a map of weak references, to break Dart <-> Java/ObjC reference cycles that cause memory leaks.

Java doesn't have lambdas, so they only have to worry about interface implementation. But in the ObjC case we'll need to apply this to both blocks and protocols.

liamappelbe avatar Feb 17 '25 23:02 liamappelbe

Related: https://github.com/dart-lang/native/issues/1510

liamappelbe avatar Feb 26 '25 23:02 liamappelbe

Does every block/protocol method need to have a context object, even if they're not going to use it? This would add a small memory and performance overhead, as well as being a bit annoying for users.

I think it would make more sense to have separate constructors for capturing and non-capturing blocks/protocols:

// Making a block without context.
final block = VoidBlock.listener(() {
  // Do stuff...
});

// Making a block with context.
final block = VoidBlock.listenerWithContext((context) {
  // Do stuff...
}, context: {'foo': foo});

This also has the advantage that existing blocks/protocols don't need to be changed, making it a non-breaking change that we can punt until after ffigen 20.

liamappelbe avatar Oct 17 '25 01:10 liamappelbe