[CodeProject C #] a Win32 Library for .NET

xiaoxiao2021-03-06  58

http://www.codeproject.com/csharp/win32.asp

Introduction

J # was recently introduced and an article was included on it in MSDN Magazine. The author pointed out that, the J # libraries could be useful for other .NET languages. One reason was that, it included a number of fine classes such as Compression and a Library Containing Win32 API Function Calls.

This article is primarily interested in the Win32 API. It turns out that accessing any of the J # libraries is flawed, if you care about performance. J # has no notions of many of the features we come to expect from C #, such as structs and ref . parameters Win32 data structures must be declared as class;. J # also use another helper class for each class to copy and pass the data to the Win32 API Thus each call to a Win32 function is expensive because of the copying and memory allocation involved In. J #, Ref Parameters Are Simulated by Passing In a Single Element Array. There Areficiencies.

Other .NET LANGUAGES Also include Win32 Apis Declarations in Some form. VB Has The Win32Api.txt File and Managed C , of Course, Has The Header Files, But The C # Does Not Have a Corresponding Library.

Win32 API

I created a new class library Win32, with a default namespace of Win32. That's Right, I Appropriated the name Win32, Because The Class Encapsulates Win32 Function Calls, Constants and Structures.

..............................

Handling Structures

Implemented in the Win32 namespace are all the various Win32 structures (named in uppercase) such as RECT, POINT, and so on. For example, this is what the LOGFONT structure looks like. It is a top-level class underneath the Win32 namespace. Public struct logfont

{

Public intlfheight;

Public int LFWIDTH;

Public int LFESCAPEMENT;

Public Int LirtIntation;

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.ByValarray, SizeConst = GDI.LF_FaceSize]]

Public Byte [] lffacename;

}

structs are, by default, sequentially laid out, while classes are auto-laid out, but I should include the SequentialLayout attribute as well, because the behavior is not specified in the standard. Some structs should actually be explicitly laid out because of the presence But I haven't had Time to do what yet.

Method Calls

There are few special classes such as Kernel, User, GDI, AdvApi, NetApi, WinMM, Shell and others. These classes contain all the Win32 API calls stemming from the system DLL of the same name. I have omitted the 32 suffix from Kernel32, User32, GDI32, And Shell32, Because I felt they were redundant and UNATRACTIVE.

Public Abstract Class GDI

{

[DLLIMPORT ("GDI32")]]]

Public Static Extern Int Abortdoc (HDC HDC);

[DLLIMPORT ("GDI32")]]]

Public Static Extern Int AbortPath (HDC HDC);

[DLLIMPORT ("GDI32")]]]

Public Static Extern Int AddFontResource (String LpFileName);

[DLLIMPORT ("GDI32")]]]

Public Static Extern Int Anglearc (HDC HDC, INT X, INT Y, INT DWRADIUS,

Double Estartangle, Double Esweepangle; [DLLIMPORT ("GDI32")]]

Public Static Extern Int AnimatePalette (Handle Hpalette,

Int WstartIndex, int WNUMENTRIES,

PaletteEntry [] LPPALETTECOLORS);

[DLLIMPORT ("GDI32")]]]

Public Static Extern Int Arc (HDC HDC, INT X1, INT Y1, INT X2, INT Y2,

INT X3, INT Y3, INT X4, INT Y4);

[DLLIMPORT ("GDI32")]]]

Public Static Extern Int Arcto (HDC HDC, INT X1, INT Y1, INT X2, INT Y2,

INT X3, INT Y3, INT X4, INT Y4);

[DLLIMPORT ("GDI32")]]]

Public Static Extern Int Beginpath (HDC HDC);

[DLLIMPORT ("GDI32")]]]

Public Static Extern Int Bitblt (HDC HDestDC, INT X, INT Y, INT NWIDTH,

INT NHEIGHT, HDC HSRCDC, INT XSRC, INT YSRC, INT DWROP

.....

Public const Int absolute = 1;

Public const Int ad_clockwise = 2;

Public const Int ad_counterclockwise = 1;

Public const Int alternate = 1;

Public const INSI_Charset = 0;

Public const INSI_FIXED_FONT = 11;

Public const INT ANSI_VAR_FONT = 12;

Public const Int arabic_charset = 178;

Public const Int aspectX = 40;

Public const INT aspectxy = 44;

Public const Int aspecty = 42;

Public const INT aspect_filtering = 0x1;

}

The constants and structures are stable Most of the changes overt the next week will occur to Win32 function signatures;. However, most of them are correct right now even though they were changed through an automated process.

Some caution:.. I manually searched for function calls that should take a StringBuilder in place of a String Any function that returns or modifies a string should be passing in a StringBuilder There may be other instances where I did not correctly use ref keyword on a . parameter of a primitive type A function taking a non-POINT struct was assumed to be a ref; I have not really found a case where that was not true (I will check again, since there are a few structures such as COORD. that can fit into a short or int) .A future modification will be more nuanced and distinguish between out and ref parameters; for now, using a ref parameter instead of an out parameter will not produce negative consequences; however, the compiler will require a Proper Initialization of The Structure Before Passing It Into An Api Call.

HANDLING Constants

Also include Under The Different DLL Class (User, Kernel, GDI, ...) Are All The Constants That Would Natural BE Categorized Under That DLL Whose Name Is That of the Parent Class.

I originally grouped constants in various enums whose name consisted of the prefix. So, WM_PAINT was WM.PAINT, however, I felt that it might actually make it harder to find the desired constant, and it was also more work on my part. There WERE Also Issues About Sub-Constants, Like WM_DDE_ANY, SHOULD THEBE A WM.DDE_ANY Constant, A WM.DDE.Any Constant, OR a wm.dde_any constant. Well See, i Have Fully Decided on this Point.

Handling ErrorS

Error codes are placed as constants within the abstract class ERROR. I could use an enum to store the values ​​but this would require me to identify any call that returns an error code, but the benefit is that the compiler and debugger already knows how to display an enum string.An alternative is to have Win32 methods that return error codes throw an exception. I plan on investigating this. For most API calls, I plan to merely return the error code value, but, some select API calls, I will throw .. an exception This will depend on the performance requirements of call and severity of the error For those functions that return error values ​​and have a single out parameter, I'll include a second variant that throws an exception and returns the out parameter; those Calls Would Have Preservedsig Set To False.

FUTURE ADDITIONS

Over the next week, i will do the folload:

I plan to cross-check the library with VB's Win32API.txt, the C header files, the J # library and MSDN through some automated scripts I also plan to introduce new types to match the handle types that Win32 uses;. Currently, handles are accepted as IntPtr. My additions will provide a HWND, HDC, and other value types that support conversions, equality and standard constants like HWND_DESKTOP. I will overload certain API calls multiple types to allow for the range of possible data types accepted by Win32 calls. for Example, SendMessage CAN Accept A Wide Variety of Calls. I WILL Also Define Delegates for the Few Callback Handlers That Win32 Supports. I Plan to Place To include Common COM Interfaces As Well Into Class Library.

Performance

It's natural to wonder what the performance implications of having thousands of Win32 APIs methods declared in a library. I doubt there will be very much, but when the library is finally checked, I will conduct a performance analysis of introducing a large library where few functions Are used. Since i Have Divided The Library Based on the DLL, IT Would Be Easy To Remove Those Dlls That You Do Utilize.conclusion

I believe this a worthy addition for Code Project and C # developers everywhere. Since this is a class library, it will work for other .NET languages. I do not include pointers or other non CLSCompliant types in the Win32 API method signatures. Although for a FEW CALLS LIKE COPYMEMORY, I Might Actually Add An Additional Overload with the (ClsCompliant (false) attribute..

I Would Like to Receive Feedback to Correct or Restructure The Library. I Will Do A DIFF AND review To changees to my owmby, Which I Resubmit.

I would appreciate your vote.

Version History

July 1, 2003 - Original Article On Win32

转载请注明原文地址:https://www.9cbs.com/read-118324.html

New Post(0)