468,720 Members | 1,591 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,720 developers. It's quick & easy.

passing a struct from managed code to unmanaged function

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=CharSet.Ansi ) ]
public struct MYSTRUCT
{
[ MarshalAs( UnmanagedType.LPStr ) ]
public String Text;
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=64 ) ]
public String Font1;
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=64 ) ]
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 = new MYSTRUCT();
x.Text = "Hello World \r\n";
x.Font1 = "Times New Roman, 10, Bold" + '\0';
x.Font2 = "Times New Roman, 10, Bold" + '\0';
x.Justify = 0;
x.VertJustify = 0;
x.bMirrored = false;
x.bVerticalText = false;
x.TextColor = 0;
x.BackgroundColor = 255;
x.IsRichText = false;
x.Effects = 0;
IntPtr mypointer =
Marshal.AllocHGlobal(Marshal.S*izeOf(typeof(MYSTRU CT)));

Marshal.StructureToPtr(x, mypointer, true);

to.oID = (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.

Nov 17 '05 #1
0 1228

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by JohnO | last post: by
17 posts views Thread by mr.resistor | last post: by
3 posts views Thread by =?Utf-8?B?b2xpZGVt?= | last post: by
17 posts views Thread by =?Utf-8?B?U2hhcm9u?= | last post: by
6 posts views Thread by =?Utf-8?B?QWxleGFuZGVyZmU=?= | last post: by
1 post views Thread by CARIGAR | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.