Link to home
Start Free TrialLog in
Avatar of jeffs1
jeffs1

asked on

Accessint C struct in VB?

I have a VB compiled app, that uses a DLL written in C.  The VB app calls a function in the DLL to register a callback function in the VB app.  The DLL then calls the VB Callback function periodically with a pointer to a data structure.  Everything works fine with the initial register call and the periodic callback works fine also... I am getting the correct address as the only parametyer of the callback function...

I just need some help with the last step... how can I access the members of this structure in VB now that I have th address in VB?  Is there a VB equivalent of the C structure that I can cast to this address and then access the structure members?

Thanks,
Jeff
Avatar of inthedark
inthedark
Flag of United Kingdom of Great Britain and Northern Ireland image

I have seen some code which does this using the copymemory API call.

e.g.

Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)


DIM Fred as YourStructure

and when you receive the address:

CopyMemory Fred, YourAddressFromDLL, Len(fred)

YOU WILL GET PROBLEMS IF YOU INTEND TO HAVE STRINGS IN YOUR STRUCTURE.  If you need strings you will need to unpack them into another place before you use them.

Hope this works for you.
You'd need to define the same structure in Visual Basic. Define a variable of that type, and use that variable to retrieve the correct items.

Another thing you can do is by creating a public struct / class in the C dll, and create a variable of that type in your VB program...

regards
CJ
hearing...
Hi

Public Type MyStruct
    Member1 As Long
    Member2 As Integer
    Member3(1 to 15) As Byte
    Member4 As String
End Type

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (lpDest As Any, lpSource As Any, ByVal cBytes As Long)

Public Function MyCallBack (ByVal lpStruct As Long) As MyStruct
   Dim ms As MyStruct
   Call CopyMemory(ms, ByVal lpStruct, Len(ms))
   MyCallBack = ms  
End Function

Cheers
Avatar of jeffs1
jeffs1

ASKER

OK... that makes sense... one question though...

I think I understand that the Member3(1 to 15) As Byte would equate to "char field3[15]" on the C side... but what would the Member4 As String look like on the C side? From what I understand VB uses Unicode for Strings... What is the best way to pass C "string" info (char array) to VB? Keeping in mind that this DLL needs to be used by C and VB applications... so the same callback prototype should work with both...

Thanks,
Jeff
ASKER CERTIFIED SOLUTION
Avatar of Ark
Ark
Flag of Russian Federation image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial