Skip to content

Conversation

@simonrozsival
Copy link
Member

Fixes #10472
Supersedes #10493 and dotnet/java-interop#1364

The problem is that the Marshal.GetFunctionPointerForDelegate method does not work with delegates with generic types, such as Action<...> or Func<...> (context: dotnet/runtime#32963), which was the case of all the delegates created in Mono.Android.Export through DynamicMethod.

This PR replaces the use of these generic delegate types with dynamically built non-generic types. It is based on an existing implementation in java-interop (see https://github.com/dotnet/java-interop/blob/02bceb03f7c07858590d930ef507745a88200a48/src/Java.Interop.Export/Java.Interop/MarshalMemberBuilder.cs#L274-L311). The CoreCLR is able to marshal the delegates built with these types to function pointers just fine.

In a previous attempt at fixing this issue (#10493), I chose a solution which modified the shape of JniNativeMethodRegistration which would be an ABI breaking change (dotnet/java-interop#1364). This implementation is much simpler and doesn't cause the same problem. Thanks to @jonpryor for steering me in this direction.

/cc @jonathanpeppers @grendello

@grendello
Copy link
Contributor

/azp run

@azure-pipelines
Copy link

Azure Pipelines successfully started running 1 pipeline(s).

string delegateTypeName = $"callback_delegate_{EncodeMethodSignature (parameter_type_infos, return_type_info)}";
lock (DynamicCallbackFactory.Module) {
delegate_type = DynamicCallbackFactory.Module.GetType (delegateTypeName)
?? CreateDelegateType (delegateTypeName);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we/should we cache the returned type?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The type is stored in DynamicCallbackFactory.Module so when we later run into a delegate with the same method signature, the existing delegate type will be reused.

@jonathanpeppers jonathanpeppers enabled auto-merge (squash) September 19, 2025 13:52
@jonathanpeppers jonathanpeppers merged commit 0a91e1e into dotnet:main Sep 19, 2025
59 checks passed
@github-actions github-actions bot locked and limited conversation to collaborators Oct 20, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[CoreCLR] Crash during dynamic registration of [Export] methods

3 participants