dotnet interop:
I would like to know how do I pass a pointer to a struct from managed
code to unmanaged code. For example if I create structure like this in
managed code.
StructLayout( LayoutKind.Sequential, CharSet=3DCharSet.Ansi ) ]
public struct MYSTRUCT
{
[ MarshalAs( UnmanagedType.LPStr ) ]
public String Text;
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=3D64 ) ]
public String Font1;
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=3D64 ) ]
public String Font2;
public int Justify;
public int VertJustify;
public bool bMirrored;
public bool bVerticalText;
public int TextColor;
public int BackgroundColor;
public bool IsRichText;
public int Effects;
}
And then I have C function like this which has an argument which is
void* (pointer to void object).
/*
HANDLE WINAPI AddObject(LPCSTR ObjType, LPCSTR ObjName, RECT Size,
int Rotation, void* Attrib);
*/
[DllImport("labels.dll")]
static extern IntPtr AddObject(String ObjType, String ObjName, int
Size, int Rotation, IntPtr Attrib);
How do I pass the structure MYSTRUCT to the Addobject() function. The
last argument of the AddObject() functions wants you to send a pointer
to MYSTRUCT object. Is this the right way to code this.
static void Main(string[] args)
{
MYSTRUCT x =3D new MYSTRUCT();
x.Text =3D "Hello World \r\n";
x.Font1 =3D "Times New Roman, 10, Bold" + '\0';
x.Font2 =3D "Times New Roman, 10, Bold" + '\0';
x.Justify =3D 0;
x.VertJustify =3D 0;
x.bMirrored =3D false;
x.bVerticalText =3D false;
x.TextColor =3D 0;
x.BackgroundColor =3D 255;
x.IsRichText =3D false;
x.Effects =3D 0;
IntPtr mypointer =3D
Marshal.AllocHGlobal(Marshal.S=ADizeOf(typeof(MYSTRUCT)));
Marshal.StructureToPtr(x, mypointer, true);
to.oID =3D (int) AddObject("Text", "sunday", 0, 0, mypointer);
} // end of Main()
Can you correct this code so that it will work. How do you pass a Stuct
from managed code to an unmanaged C function that expects you to pass a
void* pointer to the struct. And how do retrieve a void* pointer that
the unmanaged C function returns after completing its execution.