C# 12 Interceptors are here! #18
monkey0506
announced in
Announcements
Replies: 1 comment
-
This discussion is out-of-date with the current v2.0.0 API. Changes have been made in the way that custom marshalling behaviors are specified. Until this discussion is updated, the v2.0.0 README.md should be used as a reference for the current API. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
C# 12 interceptors are now available to this project!
The
interceptors
branch was created with a6d0462. This branch uses an incremental generator, which has a dependency on GenericSymbolReferenceTree.The
interceptors
branch has now been renamed tov2.0.0
until it is merged into themaster
branch.Example
Using interceptors is an improvement from v1.0.0 which does not depend on
System.Reflection.Emit
for dynamic code generation. Instead, the marshalling behaviors and unmanaged calling conventions are parsed from the invocation site:Custom marshalling
The
MarshalAsAttribute?[]?
here specifies the runtime marshalling behavior. The native method takes a singlechar*
to a UTF-8 string, which is marshalled as aSystem.String
in managed code. This parameter must be an array initializer (new[] { ... }
) or collection expression ([ ... ]
), or a reference to areadonly
field.If a field is referenced for this parameter, it must be
readonly
and initialized inline with an array initializer or collection expression. Values assigned to this field in a constructor will not be observed.The elements of the collection must be object creation expressions (
new MarshalAsAttribute(...)
).The methods in the
INativeFunc<...>
interfaces also accept aMarshalAsAttribute?
parameter for marshalling the return value. This parameter must be an inline object creation expression or a reference to areadonly
field with an inline initialization.Unmanaged calling convention
The
CallingConvention
parameter must be a literal value ofSystem.Runtime.InteropServices.CallingConvention
. Currently it is not supported to store this value in a field.Technical implementation detail
The source generator will produce a single
class
(per assembly) for each combination of type arguments, marshalling behavior, and unmanaged calling convention. These classes define aSystem.Delegate
that is not generic, that accepts parameters of the managed types specified as type parameters to theINativeAction<...>
orINativeFunc<...>
interface.The individual call sites (
FromAction
,FromFunc
, orFromFunctionPointer
) throughout your code will then be intercepted, and produce an instance of the matching class, which implements the requested interface.Beta Was this translation helpful? Give feedback.
All reactions