all groups > dotnet interop > august 2005 >
You're in the

dotnet interop

group:

passing a struct to unmanaged function


passing a struct to unmanaged function nygiantswin2005 NO[at]SPAM hotmail.com
8/26/2005 11:06:50 AM
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.
Re: passing a struct to unmanaged function Mattias Sjögren
8/26/2005 9:21:03 PM
[quoted text, click to view]

The easiest way is to change the declaration of the last parameter to

.... int Rotation, ref MYSTRUCT Attrib);


[quoted text, click to view]

You don't have to manually null-terminate strings (unless a double
terminator is required), the runtime handles that.


[quoted text, click to view]

Do you mean the HANDLE it returns? What do you want to do with it?



Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
AddThis Social Bookmark Button