Skip to content

Conversation

@SlynxCZ
Copy link
Contributor

@SlynxCZ SlynxCZ commented Oct 21, 2025

Hi! The main goal of this change was to simplify and optimize how native handles are managed internally.
Previously, every [DllImport] invocation could result in a new handle being resolved at runtime, which is unnecessary overhead when the library handle never changes.
By using the NativeLibrary approach, we open and cache the handle once and then reuse it for all future invocations — this makes the call path cleaner, avoids redundant handle resolution, and allows easier debugging of native interop (especially when tracing calls through AcceleratorCSS).

I understand it may look like small churn, but this pattern has proven to be more stable and efficient when frequently calling native methods in managed-to-native bridges. 👍

@SlynxCZ SlynxCZ requested a review from roflmuffin as a code owner October 21, 2025 13:37
@SlynxCZ SlynxCZ changed the title Implement NativeBridge and remove Helpers class Update: Implement NativeBridge and remove Helpers class Oct 21, 2025
@roflmuffin
Copy link
Owner

Previously, every [DllImport] invocation could result in a new handle being resolved at runtime, which is unnecessary overhead when the library handle never changes.

Have you run a benchmark to confirm this behaviour? I am a bit skeptical that there would be that much overhead but I think a simple microbenchmark of a million calls to the old invoke vs this invoke would clear it up

@roflmuffin
Copy link
Owner

I wrote a quick benchmark calling a simple C function from .NET using three approaches, DllImport, LibraryImport, and a delegate for function pointer, and my results showed that the delegate function pointer was actually the slowest. The method it was calling was a simple int GetValue() { return 42; } and this was the outcome.

Method Mean Error StdDev
LibraryImport 2.623 ns 0.0822 ns 0.1098 ns
DllImport 2.521 ns 0.0813 ns 0.0761 ns
LibraryImport_Unsafe 6.674 ns 0.1624 ns 0.2970 ns

@SlynxCZ
Copy link
Contributor Author

SlynxCZ commented Oct 23, 2025

Oh i see, that is interesting. Indeed it isnt logical. But ofc if it is slowest then this isnt needed. But couldnt tere be later some memory leaks from this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants