C# 调用C++dll中的结构体的定义

来源:互联网 发布:微信点赞截图制作软件 编辑:程序博客网 时间:2024/05/29 12:29

为用户定义的结构指定自定义封送处理
可以为传递到非托管函数或从非托管函数返回的结构和类的字段指定自定义封送处理属性。通过向结构或类的字段中添加 MarshalAs属性可以做到这一点。还必须使用 StructLayout 属性设置结构的布局,还可以控制字符串成员的默认封送处理,并设置默认封装大小。
示例 3
本示例说明如何为结构指定自定义封送处理属性。
请考虑下面的 C 结构:

C/C++ code
typedef struct tagLOGFONT { LONG lfHeight; LONG lfWidth; LONG lfEscapement; LONG lfOrientation; LONG lfWeight; BYTE lfItalic; BYTE lfUnderline; BYTE lfStrikeOut; BYTE lfCharSet; BYTE lfOutPrecision; BYTE lfClipPrecision; BYTE lfQuality; BYTE lfPitchAndFamily; TCHAR lfFaceName[LF_FACESIZE]; } LOGFONT;



在 C# 中,可以使用 StructLayout 和 MarshalAs 属性描述前面的结构,如下所示:

C# code
// logfont.cs// compile with: /target:moduleusing System;using System.Runtime.InteropServices;[StructLayout(LayoutKind.Sequential)]public class 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; }有关 StructLayout 属性的语法的更多信息,请参见 StructLayoutAttribute 类。然后即可将该结构用在 C# 代码中,如下所示:// pinvoke.cs// compile with: /addmodule:logfont.netmoduleusing System;using System.Runtime.InteropServices; class PlatformInvokeTest{ [DllImport("gdi32.dll", CharSet=CharSet.Auto)] public static extern IntPtr CreateFontIndirect( [In, MarshalAs(UnmanagedType.LPStruct)] LOGFONT lplf // characteristics ); [DllImport("gdi32.dll")] public static extern bool DeleteObject( IntPtr handle ); public static void Main() { LOGFONT lf = new LOGFONT(); lf.lfHeight = 9; lf.lfFaceName = "Arial"; IntPtr handle = CreateFontIndirect(lf); if (IntPtr.Zero == handle) { Console.WriteLine("Can't creates a logical font."); } else { if (IntPtr.Size == 4) Console.WriteLine("{0:X}", handle.ToInt32()); else Console.WriteLine("{0:X}", handle.ToInt64()); // Delete the logical font created. if (!DeleteObject(handle)) Console.WriteLine("Can't delete the logical font"); } }}


运行示例
C30A0AE5
代码讨论
在前面的示例中,CreateFontIndirect 方法使用了一个 LOGFONT 类型的参数。MarshalAs 和 In 属性用于限定此参数。程序将由此方法返回的数值显示为十六进制大写字符串。

 

转自:

http://topic.csdn.net/u/20100610/16/a3dc7ee0-88c8-4bb5-a19c-a054af19a233.html?63450

参考:

http://topic.csdn.net/u/20090106/10/cd130dad-4d61-4bad-bb97-5d786fee9b26.html

原创粉丝点击