    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Understanding Windows (8)</title>
        <link>http://accu.org/index.php/journals/722</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">CVu Journal Vol 8, #1 - Feb 1996 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="http://accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="http://accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="http://accu.org/index.php/journals/c77/">CVu</a>

                     &gt;                         <a href="http://accu.org/index.php/journals/c137/">081</a>
                    (7)
<br />

                                            <a href="http://accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="http://accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="http://accu.org/index.php/journals/c65/">Programming</a>
                    (488)
<br />

                                            <a href="http://accu.org/index.php/journals/c137-65/">Any of these categories</a>

                    -                        <a href="http://accu.org/index.php/journals/c137+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Understanding Windows (8)</h1>
<p><strong>Author:</strong>&nbsp;Administrator</p>
<p>
<strong>Date:</strong> 03 February 1996 13:15:26 +00:00 or Sat, 03 February 1996 13:15:26 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a>The portability
problem</h2>
</div>
<p>The nature of Windows programming is such that program design
tends to be dominated by the user interface and the demands of the
target version of Windows. It is a fact of life that much existing
code is very closely tied to the Windows 3.x API. There are all
sorts of reasons why code will end up being difficult to port to
another environment, not least being the difference in data sizes.
Experienced programmers will instinctively avoid the worst of such
traps - such as storing a <tt class="literal">POINT</tt> structure
in the space taken up by a far pointer in the previous article. In
the end any attempt to make the same body of code fully portable
between say Windows 3.1 and 95 and NT will fail in that only a
subset of features can be supported. For example a 16 bit
application will be unable to take advantage of multithreading if
simply re-compiled for 32 bits. Since in practice most software is
written for one environment and then only ported as an
afterthought, the port can be expected to be both difficult and
ineffective.</p>
<p>Apart from avoiding the obvious pitfalls awaiting those who make
unwarranted assumptions about data sizes, selector tiling, machine
architecture (Windows NT isn't restricted to Intel processors),
etc., what can the ordinary overworked programmer do?</p>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e28" id="d0e28"></a>The library
solution</h2>
</div>
<p>One of the fundamentals of software engineering is that user
interface (UI) code should be separated from that which does the
real work of the application. It is generally easiest to port code
that isn't directly involved with the UI from one platform to
another (including non Windows), as well as from one application to
another. It is even easier if that code makes no direct API calls
at all, for example substituting '<tt class="literal">new</tt>' and
'<tt class="literal">delete</tt>' for global heap allocation
functions.</p>
<p>As much code as possible should be written as 'library' code (at
least conceptually) with well thought out interfaces that can be
used in any environment. If this is done with care the resultant
body of code can simply be re-compiled under any environment. It is
a matter of choice whether this is a set of C functions or a true
class library - I'd go for the class library every time.</p>
<p>In order to build a finished application it is then necessary to
bolt on the platform specific components. These components can be
thought of as coming in two flavours, first those for which the
library code is a 'client' and secondly those which are clients of
the library. The heap management routines (mentioned above), which
are linked in behind the scenes, fall into the first category, as
do any other substitutable drivers, hardware interfaces or
whatever. The user interface code will largely be in the second
category, i.e. a client of the library code.</p>
<p>This is best understood with a diagram, so I suggest that the
interested reader goes away and draws one.</p>
<p>Hint: Try to make the library domain as large as possible and
its interface as simple as possible. Make platform specific
components as minimal as possible - that's it, you're getting the
idea!</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e47" id="d0e47"></a>Alternative
user interfaces</h2>
</div>
<p>The inevitable thrust of the preceding articles is concerned
with using the Windows API to provide the user interface to your
program. Indeed example programs have been almost all UI and little
real substance. This API when used with care can be reasonably
portable across Windows platforms. The C++ equivalent is to use
MFC. as a cleaner interface to the API. This used sensibly gives
better portability to other Windows platforms, including simulating
some features that aren't fully supported between '95 and NT.</p>
<p>Other class libraries that provide a more abstract view of the
UI are available. These promise to enable source code portability
across a wider range of platforms, at the cost of only supporting a
common subset of features and involving some extra complexity.</p>
<p>In general, class libraries should support the 'document - view'
architecture. I recommend that you should make the interface
between your own platform independent code and the UI concentrate
in one or more specialisations of the document class. As with the
discussion above I feel that it is a mistake to allow references to
the UI class library to creep into your own library code. Unless
you are totally enamoured of the third party library you will
probably want to separate them at some point in the future.</p>
<p>One of the above alternatives will suit many developers,
depending on their particular needs.</p>
<p>On the other hand, if you are concentrating on Windows targets
and wish to integrate your code with applications written in other
languages (or macro languages in third party applications) then
other possibilities arise.</p>
<p>The simplest is to make your code into one or more DLLs, these
export a simple functional interface and being language independent
can be used almost anywhere.</p>
<div class="sidebar">
<p>Where DLLs contain platform independent modules, it is advisable
to add an extra layer in the form of a source and header file
containing just the exported functions. These exported functions
then act as an interface layer, fulfilling the requirements of DLLs
without interfering with the generic code. If the extra overhead is
really a problem, the alternative is to declare the functions with
a platform dependent macro, you may need a few of these in some
circumstances anyway!</p>
</div>
<p>Other alternatives include the venerable 'VBX control', the
exciting new 16 and 32 bit OLE custom controls and full OLE 2
server applications, all of which require significant extra work to
produce.</p>
<p>All of these separate compiled components can be shared across
multiple application instances, so they should be considered for
use with purely C/C++ applications.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e69" id="d0e69"></a>The Visual
Basic alternative</h2>
</div>
<p>I find it difficult to raise any real enthusiasm for this
language but with many companies using VB 3.0 and its close
relatives - VBA (Visual Basic for Applications) in other Microsoft
products, we have to take it seriously.</p>
<p>The main reason for its popularity is that it is very easy to
produce a running application without needing either skill or
patience. For this reason it is often put forward as an ideal
proto-typing tool, frankly I believe this not to be the case, it
isn't really difficult to produce an equivalent UI framework in
C/C++.</p>
<p>VB applications have a certain indefinable 'look and feel' which
I think comes from the 'form' concept, combined with the general
availability of icons as a UI element.</p>
<p>Where VB is useful is in providing a 'quick and dirty' test bed
for DLLs as well as producing finished applications for vertical
markets or bespoke applications where there may be no justification
for producing optimal solutions and where maintenance by less
skilled programmers is considered desirable.</p>
<p>For all its ease of use, VB is a positive minefield when applied
to large projects. It is not an OOP language and gets out of
control if you aren't careful for anything over - say - 10,000
lines of code. Having said all of that, it handles databases
(Access 1.1) very well and has a quite reasonable exception
handling mechanism.</p>
<p>As with all languages it is desirable to separate UI from the
rest and VB does this by allowing you to attach code to 'events'
within each form module but also allows you to write code in
modules which are not associated with forms. Some abstraction is
possible in terms of references to VB objects (forms and controls)
but sadly less in terms of programmer defined types.</p>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e84" id="d0e84"></a>Some Visual
Basic specifics</h2>
</div>
<p>The basic data types correspond more or less with those used in
C, there is no concept of unsigned integers and no equivalent of
'<tt class="literal">char</tt>'. VB types include '<tt class=
"literal">Integer</tt>'(16 bit signed), '<tt class=
"literal">Long</tt>'(32 bit signed), '<tt class=
"literal">Double</tt>' and '<tt class="literal">String</tt>'.</p>
<p>VB functions and subroutines take parameters that default to
passing by reference but can be forced to be passed by value. When
a DLL function is declared as taking a string parameter passed by
value VB has the decency to pass a pointer to a null terminated
string!</p>
<p>Strings can be made large enough to accommodate the DLL function
writing back to it. This needs to be handled with care. It is
advisable to pass the buffer length as a separate parameter.</p>
<p>Simple data structures can be declared as 'types'.</p>
<p>One of the many deficiencies of VB is that it is difficult to
create dynamic instances of programmer defined types, large objects
have to be created statically, on the stack or as elements of an
array (which may grow and shrink). It is also extremely difficult
to represent associations between objects due to the difficulty of
taking an object's address. The best you may be able to do is to
use an index into an array of objects. An example that comes to
mind is that maps tend to be implemented by a linear search of an
entire array (separate code for each map usually).</p>
<p>Type safety is good for those parameters that are properly
declared and which VB understands: A structure reference parameter
will be properly checked whereas a pointer masquerading as a
'<tt class="literal">long</tt>' cannot be checked (after all you
have just evaded type checking - like casting in C ).</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e117" id="d0e117"></a>Problems with
handling objects</h2>
</div>
<p>Whether you are using OOP or not you will probably want to
create and destroy large data instances within your C/C++ DLL,
managing these objects and their associations internally.</p>
<p>The option of allowing the VB code to create the objects and
pass references for the DLL to act upon may be appropriate in some
circumstances but it does leave responsibility for the object
divided uncomfortably. Finally, it doesn't allow for inheritance in
C++, you may well want to expose only the base object to VB code
when in fact the object could be of a derived class.</p>
<p>The traditional mechanism is to have a set of functions
corresponding to constructor (called with the '<tt class=
"literal">new</tt>' operator), member functions and a destructor
(called with '<tt class="literal">delete</tt>'). The creation
function returns a '<tt class="literal">handle</tt>' to the object
that it has created an instance of (on the heap). This handle is
then passed to the other functions, finishing with the destructor
(which frees the heap memory after performing cleanup). This scheme
works well but there are a number of drawbacks. The handle will be
an integer type ('<tt class="literal">Long</tt>' or '<tt class=
"literal">Integer</tt>') in VB representing a pointer in C (either
'<tt class="literal">near</tt>' with a known selector or
'<tt class="literal">far</tt>' more usually). There is nothing to
stop the VB code from modifying it between uses or calling the
functions in the wrong order, such as calling the destructor before
a member function or calling a member function before the
constructor. Furthermore there is nothing to prevent a handle to
some other type of object being passed or even some other number,
simply because VB can't differentiate between them.</p>
<p>A safer but slower version uses the handle as an abstract
identifier and maps that to a pointer, failing gracefully when the
wrong value is passed. This is of course still not proof against
accidentally passing a valid ID of the wrong type of object.</p>
<p>Consider another problem, if you are using a handle to the
object, you will need to provide a set of access functions to
retrieve attribute values. On the other hand if the object is
'owned' by the VB code, there is no privacy enforceable, any VB
code that can access the object can modify its members.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e151" id="d0e151"></a>A solution
(or how I do it)</h2>
</div>
<p>For each class that you wish to work with, declare a VB type
that contains a handle and any other members that may be useful for
information purposes. The handle is used by the DLL to store the
address of its actual class instance. Each function takes a
reference to this object as its first parameter, possibly writing
to the members.</p>
<p>The VB code may read the information members that will be
updated by the DLL functions. So long as the VB code doesn't
actually modify the handle member, the functions can only be called
with valid references and the handle only has to be checked for
zero by the functions. This relies on the fact that VB initialises
all data instances (including automatic ones) to zero before they
are used.</p>
<p>Passing a reference to a type understood by VB enforces a lot
more type safety than the direct handle mechanism but with the real
object being in the hands of the DLL allows for the full C++ class
semantics to be applied.</p>
<p>Having additional attributes in the interface structure is
optional but useful. I would advocate that these are only written
to by the DLL functions, and where the VB code needs to supply new
values that these are passed as separate arguments.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e162" id="d0e162"></a>Example DLL
interface</h2>
</div>
<p>As an example, imagine an interface to a lift class, the
interface structure can be declared in 'C':</p>
<pre class="programlisting">
struct LiftData { int num_floors; int max_people; int cur_floor; LiftBase *pLift; };
</pre>
<p>Assuming that we have a class '<tt class=
"literal">LiftBase</tt>' define some exportable functions:</p>
<pre class="programlisting">
#ifdef __cplusplus extern &quot;C&quot; { #endif void __export CALLBACK lift_create(LiftData&amp; ld, int num_floors, int max_people ){ ld.pLift = new LiftBase( num_floors, max_people ); ld.num_floors = num_floors; ld.max_people = max_people; ld.cur_floor = ld.pLift-&gt;get_cur_floor(); } void __export CALLBACK lift_destroy(LiftData&amp; ld) { delete ld.pLift; ld.pLift = 0; } void __export CALLBACK lift_request( const LiftData&amp; ld, int floor_num, BOOL in_lift) { if( ld.pLift ) ld.pLift-&gt;request( floor_num, in_lift ); } // ... and more 'lift_' procedures #ifdef __cplusplus } // End extern &quot;C&quot; #endif
</pre>
<div class="sidebar">
<p>The above declarations actually give Pascal calling and naming
convention which means that there are no leading underscores added
and that the name is converted to uppercase. The linkage
specification has already eliminated the name mangling. When
declaring these functions in a header file it is usual to
conditionally compile the 'extern &quot;C&quot; { ' and '} // end extern &quot;C&quot;'
lines for '__cplusplus' so that the header can be used from a
client application or DLL written in either C or C++. Although it
is possible to compile DLLs in memory models other than large,
there is little to be gained in doing so. The exported functions
have to be 'far' and most pointers also have to be 'far' if either
passed to an exported function or if they may reference an object
on the stack. Since this translates to far 'this' pointers in C++,
quite a lot of hand tuning has to be done to use near pointers at
all! Usually if you just select DLL as the target type you will
have no problems. You may need to define a 'LibMain' and a 'WEP'
procedure for library initialisation and cleanup, this is well
documented elsewhere. Modern environments will run 'implib' on the
resulting DLL to produce an import library (with a '.lib'
extension). This library is then included in application projects
to complete the linking process.</p>
</div>
<p>The above fragments illustrate the technique. The functions
correspond with the public interface to the <tt class=
"literal">LiftBase</tt> class (more or less). If other classes are
derived from <tt class="literal">LiftBase</tt>, there would need to
be extra creation functions for these types. Assuming that virtual
functions (and destructors) are used throughout, the existing
'member' functions remain equally valid. <tt class=
"literal">LiftData</tt> represents an abstract type - this gives
you an OOP interface to the DLL!</p>
<p>This DLL interface is aimed at VB but would be perfectly good
for any client language.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e192" id="d0e192"></a>Used from
Visual Basic</h2>
</div>
<p>Sadly, VB doesn't understand C header files, nor will it read
import libraries. We have to declare the functions in a '.bas'
module:</p>
<pre class="programlisting">
Type LiftData num_floors As Integer max_people As Integer cur_floor As Integer pLift As Long End Type Declare Sub lift_create Lib &quot;lift.dll&quot; (ld As LiftData, ByVal n_f As Integer, ByVal max_p As Integer) Declare Sub lift_destroy Lib &quot;lift.dll&quot; (ld As LiftData) Declare Sub lift_request Lib &quot;lift.dll&quot; (ld As LiftData, ByVal f_num As Integer, ByVal in_lift as integer)
</pre>
<p>These '<tt class="literal">Declare Sub</tt>' lines declare the
signature of the procedure as well as its DLL name in one go.
Notice that all parameters that are passed by value are explicitly
declared as such. It's important to get these declarations correct;
failure to do so will lead to garbage being passed to the DLL
functions!</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e204" id="d0e204"></a>Finally</h2>
</div>
<p>This article has rambled over a wider area than purely Windows
programming. It's good to keep in mind the fact that most Windows
applications do have a wider context. Putting it another way, don't
get too wrapped up in the Windows specifics and leave your UI
options as open as you can.</p>
<p>The VB - DLL interface ideas are presented as a result of my own
experiences, so if you have any further thoughts on them please
write in with your own contribution/criticism!</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
