@@ -28,7 +28,7 @@ namespace Castle.DynamicProxy
2828 /// Wraps a byref-like (<c>ref struct</c>) method argument
2929 /// such that it can be placed in the <see cref="IInvocation.Arguments"/> array during interception.
3030 /// </summary>
31- public unsafe class ByRefLikeArgument
31+ public unsafe class ByRefLikeArgument : IDisposable
3232 {
3333 private static readonly ConcurrentDictionary < Type , ConstructorInfo > constructorMap = new ( ) ;
3434
@@ -95,12 +95,31 @@ public ByRefLikeArgument(void* ptr)
9595 /// will cause undefined behavior, or an <see cref="AccessViolationException"/> at best.
9696 /// </para>
9797 /// </remarks>
98+ /// <exception cref="ObjectDisposedException" />
9899 [ CLSCompliant ( false ) ]
99100 [ EditorBrowsable ( EditorBrowsableState . Advanced ) ]
100101 public void * GetPointer ( )
101102 {
103+ EnsureNotDisposed ( ) ;
104+
102105 return ptr ;
103106 }
107+
108+ public void Dispose ( )
109+ {
110+ ptr = null ;
111+ }
112+
113+ protected void EnsureNotDisposed ( )
114+ {
115+ if ( ptr == null )
116+ {
117+ throw new ObjectDisposedException (
118+ message : "Byref-like method arguments are only available during the method call. "
119+ + "This reference has been invalidated to prevent potentially unsafe access." ,
120+ objectName : null ) ;
121+ }
122+ }
104123 }
105124
106125#if FEATURE_ALLOWS_REF_STRUCT_ANTI_CONSTRAINT
@@ -124,8 +143,11 @@ public ByRefLikeArgument(void* ptr)
124143 /// <summary>
125144 /// Gets the byref-like (<c>ref struct</c>) argument.
126145 /// </summary>
146+ /// <exception cref="ObjectDisposedException" />
127147 public ref TByRefLike Get ( )
128148 {
149+ EnsureNotDisposed ( ) ;
150+
129151 return ref Unsafe . AsRef < TByRefLike > ( ptr ) ;
130152 }
131153 }
@@ -165,8 +187,11 @@ public ReadOnlySpanArgument(void* ptr)
165187 /// <summary>
166188 /// Gets the byref-like (<c>ref struct</c>) argument.
167189 /// </summary>
190+ /// <exception cref="ObjectDisposedException" />
168191 public ref ReadOnlySpan < T > Get ( )
169192 {
193+ EnsureNotDisposed ( ) ;
194+
170195#pragma warning disable CS8500
171196 return ref * ( ReadOnlySpan < T > * ) ptr ;
172197#pragma warning restore CS8500
@@ -199,8 +224,11 @@ public SpanArgument(void* ptr)
199224 /// <summary>
200225 /// Gets the byref-like (<c>ref struct</c>) argument.
201226 /// </summary>
227+ /// <exception cref="ObjectDisposedException" />
202228 public ref Span < T > Get ( )
203229 {
230+ EnsureNotDisposed ( ) ;
231+
204232#pragma warning disable CS8500
205233 return ref * ( Span < T > * ) ptr ;
206234#pragma warning restore CS8500
0 commit comments