Marshaling C structs?

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)
 
K

Ken Tucker [MVP]

Hi,

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

Ken
 

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