April 07, 2006

Passing LogFont struct from VB to C#

LogFont structre in VB looks as:

Type LogFont ' 60 Bytes
lfHeight As Long
lfWidth As Long
lfEscapement As Long
lfOrientation As Long
lfWeight As Long
lfItalic As Byte
lfUnderline As Byte
lfStrikeOut As Byte
lfCharSet As Byte
lfOutPrecision As Byte
lfClipPrecision As Byte
lfQuality As Byte
lfPitchAndFamily As Byte
lfFaceName As String * 32
End Type


Use CopyMemory API to convert struct in bytes

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pDst As Any, pSrc As Any, ByVal ByteLen As Long)

Dim lf As LogFont
Dim bt(100) As Byte
CopyMemory bt(0), lf, LenB(lf)

'Finally call the C# function
objNet.SendLogFont(bt))

In C# you can convert bytes back to logFont as shown:

LogFont struct in C# looks as:


[StructLayout(LayoutKind.Sequential, Pack = 1)] //, CharSet = CharSet.Auto)]
internal struct LOGFONT
{
public const int LF_FACESIZE = 32;
public int lfHeight;
public int lfWidth;
public int lfEscapement;
public int lfOrientation;
public int lfWeight;
public byte lfItalic;
public byte lfUnderline;
public byte lfStrikeOut;
public byte lfCharSet;
public byte lfOutPrecision;
public byte lfClipPrecision;
public byte lfQuality;
public byte lfPitchAndFamily;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = LF_FACESIZE)]
public string lfFaceName;
}

Then write SendLogFont() function as

public void SendLogFont()
{
LOGFONT lf = new LOGFONT();
try
{
GCHandle gcHandle = GCHandle.Alloc(Buff, GCHandleType.Pinned);
// Marshals data from an unmanaged block of memory
// to a newly allocated managed object of the specified type.
Object Obj = Marshal.PtrToStructure(gcHandle.AddrOfPinnedObject(), typeof(LOGFONT));
lf = (LOGFONT)Obj;
// Free GChandle to avoid memory leaks
gcHandle.Free();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}

}