Object Reference not set to an instance... Marshal.Copy problem

R

Robin Tucker

(apologies in advance for cross post)

Hi there,

I have the following method which uses COM IPersistStorage to "save" a COM
object into an ILockBytes in order for me to be able to fetch the data()
bytes and put them into a database. I am using similar methods to create
COM objects after reading bytes() from the database. Anyway, the line
Marshal.Copy fails with an "object reference not set to an instance of an
object" error. The hGlobal GlobalSize() returns ~69k, which is correct for
the object and theBytes() array is resized correctly. Any ideas why this
won't marshal?

Thanks


Robin

Public Function GetBytes(ByRef theBytes() As Byte) As Boolean

Dim Result As Boolean
Dim hGlobal As IntPtr
Dim hResult As Integer
Dim theILockBytes As COM.ILockBytes
Dim theIStorage As COM.IStorage
Dim theIPersistStorage As COM.IPersistStorage
Dim theSize As Integer

Try
' Make sure we have a document in the first place

If m_Document Is Nothing Then
Return False
End If

' Now, get an IPersistStorage interface

theIPersistStorage = CType(m_Document, COM.IPersistStorage)

' Create an ILockBytes interface on the global

hResult = DLLImports.CreateILockBytesOnHGlobal( _

hGlobal, _

True, _

theILockBytes)

' Now create a storage interface on the ILockbytes

hResult = DLLImports.StgCreateDocfileOnILockBytes( _
theILockBytes, _
COM.STGM.DIRECT Or COM.STGM.CREATE Or COM.STGM.READWRITE Or
COM.STGM.SHARE_EXCLUSIVE, _
0, _
theIStorage)

' Save to the storage.

hResult = theIPersistStorage.Save(theIStorage, False)
hResult = theIPersistStorage.SaveCompleted(theIStorage)

' Get the hGlobal

hResult = DLLImports.GetHGlobalFromILockBytes(theILockBytes,
hGlobal)

' Get the size of the array

theSize = DLLImports.GlobalSize(hGlobal)

' Resize the array

ReDim theBytes(theSize)

' and copy the bytes across (FAILS with "object reference not set to
instance of an object")

Marshal.Copy(hGlobal, theBytes, 0, theSize)

Catch Ex As Exception

Finally

' No need to free the hGlobal here, because
CreateILockBytesOnHGlobal automatically frees it.

End Try

Return Result

End Function
 
R

Robin Tucker

Ok, ok, I fixed it. It doesn't work if I let the ILockBytes allocate its
own handle (I dunno why not), but if I allocate one of zero length and pass
it into CreateILockBytesOn... then it works fine!
 
C

Cor

Hi Robin,

I am glad you have your answer. However please crosspost in the dotnet
groups, most who are active are that in more newsgroups and then they know
where it is and are sure who will answer

And please not multipost, no one of us likes that.
(And when it are the dotnet groups you are always quick ready with maximum 4
I think)

Cor
 

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