Marshaling C structs?

  • Thread starter Thread starter Denis C
  • Start date Start date
D

Denis C

I've got a project in which I need a VB program to access
functions within a C library. Here's a simple example of
what I'm attempting to do:

C DLL:
typedef struct GetLongRTS *GetLongRT;
struct GetLongRTS{
LONG lval;
};

DBACCESSDLL_API GetLongRT __cdecl GetLongVal(){
struct GetLongRTS GL;
GL.lval = 5;
return ≷
}


VB CODE:
Public Structure GetLongRTS
Public lval As Long
End Structure

<DllImport("DBAccess.dll", SetLastError:=True)> _
Public Shared Function GetLongVal() As IntPtr
End Function

Module Module1
Sub Main()
Dim ptr As IntPtr = GetLongVal()
Dim obj As GetLongRTS = _
CType(Marshal.PtrToStructure(ptr, GetType _
(GetLongRTS)), GetLongRTS)
Console.WriteLine(obj.lval)
End Sub
End Module


My problem is that some garbage value gets printed out to
console instead of '5'. I think it's because my C struct
and VB structure are not equivalent in memory therefore
obj.lval is not pointing to where I want it. Do I perhaps
need to marshal the VB structure when I declare it? Any
help would be appreciated (Sorry for the long post)
 
Hi,

The managed Integer is the same as the old long. Try replacing the long
with integer.

Ken
 
Back
Top