ByRef param not populated using Reflection

S

Steve Amey

Hiya

I want to execute a function using reflection and retrieve the value of a
string using a ByRef parameter. When I Invoke the MethodInfo passing in the
string parameter, it gets populated in the correct function but when I come
back out of the function that value is not passed back to the code that
called it.

Could somebody please tell me if I'm missing something here? I just need to
be able to use ByRef parameters using reflection to execute the methods.


***********************
Private Shared _aIUDHandler As IUDHandler
Public Shared Function SaveObject(ByVal paMyObject As MyObject, ByRef
psMessage As String) As Boolean

Dim aTypes() As Type = {paMyObject.GetType, psMessage.GetType}
Dim aMethodInfo As System.Reflection.MethodInfo =
_aIUDHandler.GetType.GetMethod("SaveMyObject")

If Not aMethodInfo Is Nothing Then
'// I want to retrieve the value in psMessage here
Dim aRet As Object = aMethodInfo.Invoke(_aIUDHandler, New Object()
{paMyObject , psMessage})
Return CType(aRet, Boolean)
Else
Throw New Exception("Not working")
End If

End Function

Public Class IUDHandler

Public Overloads Function SaveMyObject(ByVal paMyObject As MyObject, ByRef
psMessage As String) As Integer
psMessage = "This ByRef param is not being returned via the reflection call
but is on a normal call"
End Function

End Class
**************************

Kind regards,
Steve
 
B

Bill McCarthy

Hi Steve,

Actually I think you'll find it is being returned, just you are looking in
the wrong place. ByRef means a pointer to the variable, but you aren't
passing that to the Invoke call, you are passing it an array with *another*
pointer. It's that pointer that will be updated.

A simple fix would be to declare the array outside of the invoke call then
get the second item, e.g:

Dim params =New Object() {paMyObject , psMessage}
Dim aRet As Object = aMethodInfo.Invoke(_aIUDHandler, params)
psMessage = params(1)
 
S

Steve Amey

Hi Bill

Thank you very much for your swift response! It works great now :blush:)

Kind Regards,
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top