Help with marshaling

eddie74

New member
Joined
Sep 28, 2006
Messages
2
Location
Montreal
Programming Experience
5-10
Hello forum members,
I hope I am posting in the correct place.

I am relatively new to the .net frmework, but i LOVE IT. I was die-hard to upgrade from vb6, but I am glad I did.

Here is my problem. I am useing visual studio (vb.net) 2005. In my app, I use an API call to retireive a list of file object handles from a portable media device useing the Media Transport Protocol. ( I know what the handles of the files actually are becuase I use the direct MTP tool to show me what they are.) Here is API call I use:


Sub GetObjectHandles(ByVal StorageId As UInteger, ByVal FormatCode As MtpLib.MTP_FORMATCODE, ByVal ParentObjectHandle As UInteger, ByRef pcelt As Integer, ByVal ppObjectHandles As System.IntPtr, ByRef pResponseCode As MtpLib.MTP_RESPONSECODE)


And here is how i use it:


'Imports
Imports
MtpLib
Imports System.Runtime.InteropServices ' I added for marshaling

Public MTP AsNew MtpLib.WindowsMtp

'Decalres
Dim pCelt As Integer
Dim objHandles as IntPtr
Dim resCode as MtpLib.MTP_RESPONSECODE

'In my sub


MTP.GetObjectHandles(65537, 0, 0, pcelt, objHandles, resCode)

When I run the code I get this error :

"AccessViolationException was unhandles" - "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

I figured this was because the IntPtr variable needed to be marshaled. Problem is HOW? I don't know alot about marshaling. Can some please try and describe some working code for me? I have completed the entire program by designing around static object handles. It would really be nice to get all the files at runtime you know?

Also,

I know the storage id is correct (because I used it successfully in other API calls in the app)

AND

I know the procedure is returning the correct amount of files, because pCelt is equall to 312 after the procedure fails (and there are exactly 312 files on my device) problem is, I think the objHand is an array of file handles and I need to convert them. When I tried my hand at marshaling them, I got random numbers every time (or what seemed like random numbers.)

I have been working on this same problem nowfor two weeks PLEASE HELP!!!!!!!!!!!

Do I need to create a structure and then read / write it ? if so how how how how ????
 
Try: Dim resCode as New MtpLib.MTP_RESPONSECODE

Also not sure if you have to write: 65537UI
 
Marshalling

In fact you have first allocate the memory to receive the unmanaged memory pointer.

try:

objHandles = Marshal.AllocHGlobal(1);

After that you will need to read each handle.

Then you can try:

for( int i=0; i < pcelt; i++ )
{
Console.WritLine( "Handle {0} = {1}", i, Marshal.ReadIntPtr(objHandles ) );
}

I hope this is helpful.

Best regards,
 
Back
Top