Hello, all,
I have a .NET application (VB) that passes the address of a delegate to
unmanaged code in a DLL. The unmanaged code then uses the delegate as a
call-back.
This seems to work fine, but now I am worried about garbage collection.
I am concerned that the location of the delegate might be altered as
a result of other (unused) objects being garbage collected. This would
probably cause undesirable results when the unmanaged DLL attempted to
make a subsequent call-back operation.
Although I haven't yet seen such a problem, I understand that garbage
collection is largely uncontrollable and unpredictable. So I am worried
about mysterious and sporadic problems appearing when the application is
actually in use. To avoid this possibility, I tried "pinning" the
delegate, but I get the error message:
"Object contains non-primitive or non-blittable data."
Are my concerns about this justified? If so, what (if anything) can I
do to prevent this problem?
For any who are interested, I have posted relevant code snippets below.
Cheers,
Randy
Private Delegate Function mdgtDataInterface( _
ByVal strAction As String, _
ByVal intActionLen As Integer, _
<MarshalAs(UnmanagedType.SafeArray)> _
ByRef objaData() As Object) As aenmDataRequestStatus
...
...
' DataInterface is the .Net call-back routine.
Dim dgtDataInterface As mdgtDataInterface = AddressOf DataInterface
'''The following statement causes a System.ArgumentException.
'''Dim gchDIPin As GCHandle = GCHandle.Alloc(dgtDataInterface, _
GCHandleType.Pinned)
...
' This calls the unmanaged code and passes the call-back delegate.
Dim intStatus As Integer = RunUnmanaged(intModelAddress, _
dgtDataInterface, _
strMessage)
...
...
' This is the call-back routine
Public Function DataInterface(ByVal strRequest As String, _
ByVal intRequestLength As Integer, _
<MarshalAs(UnmanagedType.SafeArray)> _
ByRef objaData() As Object) _
As aenmDataRequestStatus
...
...