<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Bobobobo's Weblog &#187; C++</title>
	<atom:link href="http://bobobobo.wordpress.com/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://bobobobo.wordpress.com</link>
	<description>technology and the internets</description>
	<lastBuildDate>Mon, 30 Nov 2009 16:56:23 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='bobobobo.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/0e8d17c68f90a18a1e89a776717e00e2?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Bobobobo's Weblog &#187; C++</title>
		<link>http://bobobobo.wordpress.com</link>
	</image>
			<item>
		<title>Using C++ boost regex</title>
		<link>http://bobobobo.wordpress.com/2009/11/30/using-c-boost-regex/</link>
		<comments>http://bobobobo.wordpress.com/2009/11/30/using-c-boost-regex/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 16:33:13 +0000</pubDate>
		<dc:creator>bobobobo</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[boost]]></category>

		<guid isPermaLink="false">http://bobobobo.wordpress.com/?p=1380</guid>
		<description><![CDATA[
First, Install Boost and be sure to choose the regex package when you install it.

Regex matching in C++ using BOOST
Regex replace in C++ using BOOST
Regex extract in C++ using BOOST
See example below.


#include &#60;iostream&#62;
#include &#60;string&#62;
#include &#60;boost/regex.hpp&#62; // add boost regex library
using namespace std ;

int main()
{
  // http://www.boost.org/doc/libs/1_35_0/more/getting_started/windows.html#get-boost

  // To practice regular expressions, use
  [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1380&subd=bobobobo&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>
First, <a href="http://www.boost.org/doc/libs/1_35_0/more/getting_started/windows.html#get-boost">Install Boost</a> and be sure to choose the regex package when you install it.
</p>
<h1>Regex matching in C++ using BOOST</h1>
<h1>Regex replace in C++ using BOOST</h1>
<h1>Regex extract in C++ using BOOST</h1>
<p>See example below.</p>
<blockquote>
<pre>
#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;boost/regex.hpp&gt; // add boost regex library
using namespace std ;

int main()
{
  // http://www.boost.org/doc/libs/1_35_0/more/getting_started/windows.html#get-boost

  // To practice regular expressions, use
  // http://weitz.de/regex-coach/
  bool quitting = false ;
  string input ;

  puts( " *** Regex MATCH test ***" ) ;
  puts( " ------------------------" ) ;
  while( !quitting )
  {
    boost::regex EXPR( "[0-9][0-9][A-Za-z]" ) ;

    cout &lt;&lt; "The expression is:" &lt;&lt; endl ;
    cout &lt;&lt; EXPR &lt;&lt; endl &lt;&lt; endl ;

    cout &lt;&lt; "Enter a string to match it, or just type Q to move on" &lt;&lt; endl ;
    getline( cin, input ) ;

    bool matches = boost::regex_match( input, EXPR ) ;
    if( matches )
    {
      puts( "Congrats, you entered a string that matches the expression." ) ;
    }
    else if( input == "q" || input == "Q" )
    {
      puts( "Bye!" ) ;
      quitting = true ;
    }
    else
    {
      puts( "NO, that string didn't match" ) ;
    }
  }

  puts( "\n" ) ;
  puts( " *** Regex REPLACE test ***" ) ;
  puts( " --------------------------" ) ;
  quitting = false ;

  while( !quitting )
  {
    boost::regex EXPR( "e" ) ;
    string REPLACEMENT = "X" ;

    cout &lt;&lt; "I am replacing: " &lt;&lt; EXPR &lt;&lt; " with: " &lt;&lt; REPLACEMENT &lt;&lt; endl ;
    cout &lt;&lt; EXPR &lt;&lt; endl &lt;&lt; endl ;

    cout &lt;&lt; "Enter a string with lowercase 'e' in it, or just type Q to quit." &lt;&lt; endl ;
    getline( cin, input ) ;

    if( input == "q" || input == "Q" )
    {
      puts( "Bye!" ) ;
      quitting = true ;
    }
    else
    {
      string replaced = boost::regex_replace( input, EXPR, REPLACEMENT, boost::match_default | boost::format_sed ) ;
      cout &lt;&lt; replaced &lt;&lt; endl;
    }
  }

  // Finally, a test showing capturing
  boost::regex EXPR( "&lt;food&gt;([A-Za-z]+)&lt;/food&gt;" ) ;
  string xmlData = "&lt;food&gt;pizza&lt;/food&gt;" ;

  string replaced = boost::regex_replace(

    xmlData,  // the data

    EXPR,     // the regex

    "\\1",    // Don't forget to DOUBLE backslash
              // your regex escape sequences!!

    boost::match_default | boost::format_sed
    // You can get perl-style regex strings,
    // "sed" style regex strings,
    // or you can use boost's own
    // extended format style strings.
    // See http://www.boost.org/doc/libs/1_33_1/libs/regex/doc/format_syntax.html
  ) ;
  cout &lt;&lt; "EXPR: " &lt;&lt; EXPR &lt;&lt; endl;
  cout &lt;&lt; "Data: " &lt;&lt; xmlData &lt;&lt; endl;
  cout &lt;&lt; "The extracted data was: " &lt;&lt; replaced &lt;&lt; endl ;
}
</pre>
</blockquote>
Posted in C++ Tagged: boost, C++ <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bobobobo.wordpress.com/1380/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bobobobo.wordpress.com/1380/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bobobobo.wordpress.com/1380/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bobobobo.wordpress.com/1380/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bobobobo.wordpress.com/1380/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bobobobo.wordpress.com/1380/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bobobobo.wordpress.com/1380/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bobobobo.wordpress.com/1380/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bobobobo.wordpress.com/1380/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bobobobo.wordpress.com/1380/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1380&subd=bobobobo&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://bobobobo.wordpress.com/2009/11/30/using-c-boost-regex/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a4ec51727310397c9e592dd84ae74dc2?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">bobobobo</media:title>
		</media:content>
	</item>
		<item>
		<title>Do you write char* var, char * var, or char *var ?</title>
		<link>http://bobobobo.wordpress.com/2009/10/31/do-you-write-char-var-char-var-or-char-var/</link>
		<comments>http://bobobobo.wordpress.com/2009/10/31/do-you-write-char-var-char-var-or-char-var/#comments</comments>
		<pubDate>Sat, 31 Oct 2009 16:45:49 +0000</pubDate>
		<dc:creator>bobobobo</dc:creator>
				<category><![CDATA[C C++]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://bobobobo.wordpress.com/?p=1370</guid>
		<description><![CDATA[This seems to be a trivial and is an inherently subjective question but I want to know what the best practice is __with reasons__.
I used to write


    char * var ;


But I started writing


    char* var ;


Because I thought that the type of var is simply char* so the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1370&subd=bobobobo&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This seems to be a trivial and is an inherently subjective question but I want to know what the best practice is __with reasons__.</p>
<p>I used to write</p>
<blockquote>
<pre>
    char * var ;
</pre>
</blockquote>
<p>But I started writing</p>
<blockquote>
<pre>
    char* var ;
</pre>
</blockquote>
<p>Because I thought that the type of var is simply <code>char*</code> so the * pointer should be stuck to the type so its read in &#8220;one eyeful.&#8221;</p>
<p>THEN I ran into a bug recently where I didn&#8217;t notice that I had declarations</p>
<blockquote>
<pre>
    char* var1, var2 ;
</pre>
</blockquote>
<p>And I actually didn&#8217;t realize that var2 was type char, not char*.  Hmm.  Then I thought, well, this way makes the most sense then:</p>
<blockquote>
<pre>
    char *var1, *var2 ;
</pre>
</blockquote>
<p>Currently I&#8217;m thinking the last way is the correct way now.</p>
Posted in C C++, C++ Tagged: C++ <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bobobobo.wordpress.com/1370/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bobobobo.wordpress.com/1370/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bobobobo.wordpress.com/1370/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bobobobo.wordpress.com/1370/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bobobobo.wordpress.com/1370/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bobobobo.wordpress.com/1370/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bobobobo.wordpress.com/1370/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bobobobo.wordpress.com/1370/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bobobobo.wordpress.com/1370/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bobobobo.wordpress.com/1370/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1370&subd=bobobobo&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://bobobobo.wordpress.com/2009/10/31/do-you-write-char-var-char-var-or-char-var/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a4ec51727310397c9e592dd84ae74dc2?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">bobobobo</media:title>
		</media:content>
	</item>
		<item>
		<title>Mistake in &#8220;OLE DB for the ODBC Programmer&#8221;</title>
		<link>http://bobobobo.wordpress.com/2009/07/15/mistake-in-ole-db-for-the-odbc-programmer/</link>
		<comments>http://bobobobo.wordpress.com/2009/07/15/mistake-in-ole-db-for-the-odbc-programmer/#comments</comments>
		<pubDate>Wed, 15 Jul 2009 04:06:02 +0000</pubDate>
		<dc:creator>bobobobo</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[OLEDB]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://bobobobo.wordpress.com/?p=1296</guid>
		<description><![CDATA[While the OLE DB for the ODBC Programmer article is excellent, there is a mistake in it.
The rgParamBindInfo array should not have names for the parameters (they should be NULL) because the prepared statement doesn&#8217;t use named parameters (they are unnamed (?,?,?,?)&#8217;s)
Because the author does not check the HRESULTS that come back from his SetParameterInfo() [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1296&subd=bobobobo&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>While the <a href="http://msdn.microsoft.com/en-us/library/ms810892.aspx">OLE DB for the ODBC Programmer</a> article is excellent, there is a mistake in it.</p>
<p>The rgParamBindInfo array should not have names for the parameters (they should be NULL) because the prepared statement doesn&#8217;t use named parameters (they are unnamed (?,?,?,?)&#8217;s)</p>
<p>Because the author does not check the HRESULTS that come back from his SetParameterInfo() invokation, he doesn&#8217;t know about this error.  But if you check this line:</p>
<blockquote>
<pre>
pICmdWithParams-&gt;SetParameterInfo(nParams, rgParamOrdinals,
        rgParamBindInfo);
</pre>
</blockquote>
<p>with</p>
<blockquote>
<pre>
if( FAILED( pICmdWithParams-&gt;SetParameterInfo(nParams, rgParamOrdinals,
        rgParamBindInfo) )
{
  puts( "The 1997 article by Michael Pizzo, Jeff Cochran has a mistake in it" ) ;
}
</pre>
</blockquote>
<p>you find it throws an error because rgParamBindInfo is wrong (it should look like this:)</p>
<blockquote>
<pre>

  DBPARAMBINDINFO     rgParamBindInfo[] =
        {
        OLESTR("DBTYPE_CHAR"),  0 /* OLESTR("CustomerID")*/,    5,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("CompanyName")*/,  40,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("ContactName") */,  30,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("ContactTitle") */, 30,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("Address") */,      60,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("City") */,         15,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("Region") */,       15,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("PostalCode") */,   10,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("Country") */,      15,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("Phone") */,        24,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("FAX") */,          24,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        };
</pre>
</blockquote>
<p>Because the prepared statement looks like this:</p>
<blockquote>
<pre>
  WCHAR               wSQLString[] =
    OLESTR("insert into Customers (CustomerID, CompanyName, ContactName,")
    OLESTR(" ContactTitle, Address, City, Region, PostalCode, Country,")
    OLESTR(" Phone, Fax)")
    OLESTR(" values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
</pre>
</blockquote>
<p>If the prepared statement used <b>named parameters</b>, it would look something like this:</p>
<blockquote>
<pre>
  WCHAR               wSQLString[] =
    OLESTR("insert into Customers (CustomerID, CompanyName, ContactName,")
    OLESTR(" ContactTitle, Address, City, Region, PostalCode, Country,")
    OLESTR(" Phone, Fax)")
    OLESTR(" values (:CustomerID, :CompanyName, :ContactName, ")
    OLESTR(" :ContactTitle, :Address, :City, :Region, :PostalCode, :Country, ")
    OLESTR(" :Phone, :Fax)");
</pre>
</blockquote>
<p>That&#8217;s why the docs also say <a href="http://msdn.microsoft.com/en-us/library/ms714917(VS.85).aspx">The name of the parameter; it is a null pointer if there is no name. Names are normal names. The colon prefix (where used within SQL text) is stripped.</a></p>
Posted in C++ Tagged: C++, OLEDB, sql <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bobobobo.wordpress.com/1296/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bobobobo.wordpress.com/1296/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bobobobo.wordpress.com/1296/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bobobobo.wordpress.com/1296/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bobobobo.wordpress.com/1296/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bobobobo.wordpress.com/1296/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bobobobo.wordpress.com/1296/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bobobobo.wordpress.com/1296/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bobobobo.wordpress.com/1296/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bobobobo.wordpress.com/1296/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1296&subd=bobobobo&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://bobobobo.wordpress.com/2009/07/15/mistake-in-ole-db-for-the-odbc-programmer/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a4ec51727310397c9e592dd84ae74dc2?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">bobobobo</media:title>
		</media:content>
	</item>
		<item>
		<title>Working with ODBC from C++</title>
		<link>http://bobobobo.wordpress.com/2009/07/11/working-with-odbc-from-c/</link>
		<comments>http://bobobobo.wordpress.com/2009/07/11/working-with-odbc-from-c/#comments</comments>
		<pubDate>Sat, 11 Jul 2009 03:51:58 +0000</pubDate>
		<dc:creator>bobobobo</dc:creator>
				<category><![CDATA[C C++]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[odbc]]></category>

		<guid isPermaLink="false">http://bobobobo.wordpress.com/?p=1252</guid>
		<description><![CDATA[Setting up MySQL for use through ODBC.
First, recognize that THERE ARE several ways you can connect to a MySQL database from an application.
MDAC

click for larger
The 3 main ways are:

Native C api &#8211; compile and link-in code that can talk to MySQL WITHIN your app.  This is ALMOST like making MySQL &#8220;part of your program&#8221;
 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1252&subd=bobobobo&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h1>Setting up MySQL for use through ODBC.</h1>
<p>First, recognize that <a href="http://dev.mysql.com/downloads/connector/">THERE ARE several ways</a> you can connect to a MySQL database from an application.</p>
<p><a href="http://en.wikipedia.org/wiki/MDAC">MDAC</a></p>
<p><a href="http://bobobobo.files.wordpress.com/2009/07/db-full-diagram.png"><img src="http://bobobobo.files.wordpress.com/2009/07/db-full-diagram-small.png" /><br />
click for larger</a></p>
<p>The 3 main ways are:</p>
<ul>
<li><a href="http://bobobobo.wordpress.com/2009/04/05/getting-started-with-mysql-in-c/">Native C api</a> &#8211; compile and link-in code that can talk to MySQL WITHIN your app.  This is ALMOST like making MySQL &#8220;part of your program&#8221;
<p>  <img src="http://bobobobo.files.wordpress.com/2009/07/cpp-mysql.png" /></p>
</li>
<li><a href="#">ODBC</a> (this article).  ODBC stands for Ol&#8217; Dirty Bastard Connector.. :) Just kidding.  But it should.  ODBC was first released in 1992.  ODBC is short for <b><em>Open Database Connectivity</em></b>.
<p>  Basically your application TALKS TO the ODBC driver THROUGH A COMMON SET OF API FUNCTIONS &#8211; the <a href="http://msdn.microsoft.com/en-us/library/ms714562(VS.85).aspx">ODBC API library</a>.  The ODBC driver in turn, talks to the actual database for you.  So you achieve a certain level of database API independence:  you use ODBC in the same way whether programming to a MySQL database, or an MS-SQL Server database, or an Oracle database &#8211; you use the same functions and it works, as long as you have an ODBC driver for that database.  So using ODBC is just ONE LEVEL of abstraction above the native C API.  ODBC is still alive and kicking today and works fine.</p>
<p>  <img src="http://bobobobo.files.wordpress.com/2009/07/cpp-odbc-mysql.png" /></p>
<p>  Aside:</p>
<blockquote><p>
  If you&#8217;re familiar with how the HAL works in Direct3D, ODBC is a little bit like the HAL.</p>
<table>
<tr>
<td>Direct3D function calls</td>
<td>ODBC function calls</td>
</tr>
<tr>
<td>HAL (hardware abstraction layer)</td>
<td>ODBC driver</td>
</tr>
<tr>
<td>GPU hardware itself</td>
<td>Database software itself</td>
</tr>
</table>
<p>  In this case, the &#8220;database&#8221; is like the GPU, and ODBC driver is that layer which transforms standard ODBC function calls into function calls that the actual database being used underneath can understand.</p>
<p>  If that just didn&#8217;t make any sense, ignore this whole block</p>
</blockquote>
<p>  The advantage of using ODBC above the MySQL functions directly is .. well, just that you don&#8217;t have to program to the MySQL function set directly anymore.  So, say you already had experience with setting up a database connection under C++/Oracle, and you want to quickly get up and running on a C++/MySQL program.  Instead of going and figuring out how the <a href="http://bobobobo.wordpress.com/2009/04/05/getting-started-with-mysql-in-c/">MySQL native api works</a>, you actually wouldn&#8217;t have to know any of that at all, you&#8217;d just install the ODBC driver and program <b><em>&#8220;to&#8221;</em></b> ODBC &#8211; this is what we&#8217;ll show how to do in this article.</p>
</li>
<li>
<h1><a href="http://msdn.microsoft.com/en-us/library/ms722784(VS.85).aspx">OLE DB</a></h1>
<p>  Just ANOTHER, newer, more recent library of functions that is supposed to replace ODBC.  <a href="http://msdn.microsoft.com/en-us/library/ms678262(VS.85).aspx">OLE DB is a low-level, high-performance interface to a variety of data stores</a>.  OLE DB, like ODBC as shown in this article, has a C-style API.</p>
<p>  OLE DB&#8217;s advantage over ODBC is that the underlying data provider when using OLE DB <b><em>does NOT have to be a relational database</em></b>.</p>
<p>  In fact, according to <a href="http://books.google.ca/books?id=JTKX7OUqCEMC&amp;lpg=PP1&amp;dq=contact%20jason%20roff%20activex%20data%20objects&amp;pg=PA8">page 8 of this book</a></p>
<blockquote><p>
&#8230; <b><em>ODBC</em></b> as we have just seen, is an excellent technology for accessing SQL-based data.  OLE DB <em>incorporates this proven technology</em> with a particular component that allows OLE DB <em>consumers</em> to communicate directly with ODBC <em>providers</em>.  In other words, use OLE DB to access SQL-based data, and you gain the advantage of being able to access both relational and other forms of data with the same code.
</p></blockquote>
<p>  So it looks like this:</p>
<p>  <img src="http://bobobobo.files.wordpress.com/2009/07/cpp-ole-db-odbc-mysql.png" /></p>
</li>
<li>
<h1>Finally, <a href="http://msdn.microsoft.com/en-us/library/ms678262(VS.85).aspx">ADO</a>, (also, <a href="http://msdn.microsoft.com/en-us/library/e80y5yhx.aspx">ADO.NET)</a>.</h1>
<p>  <a href="http://msdn.microsoft.com/en-us/library/ms678262(VS.85).aspx">ADO is a high-level, easy-to-use interface to OLE DB</a>.</p>
<p>  ADO is the NEWEST and is probably the most commonly used technology for accessing databases from MS apps.  Ever heard of <a href="http://hibernate.org/">hibernate</a>?  Well, ADO, (which stands for <em>ActiveX Data Objects</em>) is BASICALLY the same idea as Hibernate.  You can interact with the database through a series of functions WITHOUT EVER WRITING A LINE OF SQL.  You interact with the database instead through the functionset provided by ADO.</p>
<p>  <img src="http://bobobobo.files.wordpress.com/2009/07/cpp-ado-ole-db-odbc-mysql.png" /></p>
<p>  Can you see the layers?  You can see that you should expect ADO to be somewhat slower than using ODBC directly.</p>
<p>  ADO is accessible in two flavors:  ADO &#8220;regular&#8221; and ADO.NET.  ADO.NET, clearly, is part of the .NET framework and so if you&#8217;re using a .NET application, then data access through ADO.NET is the natural standard for you.</p>
<p>  If you&#8217;re programming a native C++ app on the other hand, the choice whether to use native MySQL function calls, ODBC, OLE DB (directly), ADO, or ADO.NET kind of looms before you.</p>
</li>
</ul>
<p>So, ok, on with it.</p>
<h1>Accessing a MySQL database through ODBC</h1>
<p>1.  The first step is to install a MySQL database and create a table or two.  Do it do it do it!!</p>
<p>2.  Ok, now the SECOND step is to <a href="http://dev.mysql.com/downloads/connector/odbc/5.1.html">GET THE MySQL ODBC 5.1 DRIVER</a>.  <b>GET THE 32-BIT DRIVER ONLY, PLEASE, EVEN IF YOU ARE ON A 64-bit MACHINE.  Unless you know EXACTLY what you&#8217;re doing FOR SURE and you KNOW your compiler pushes out 64-bit applications (Visual Studio 2005/2008 pushes out 32-bit applications by default ONLY!! EVEN IF you are on a 64-bit platform!)</b></p>
<p>3.  Once you&#8217;ve got that installed, OPEN UP Start -&gt; Administrative Tools -&gt; Data Sources (ODBC).</p>
<blockquote><p>
Note:  If you DO NOT SEE &#8220;Administrative Tools&#8221; on your start menu RIGHT CLICK TASKBAR &gt; PROPERTIES &gt; START MENU TAB &gt; CUSTOMIZE &gt; FIND AND SELECT THE &#8220;DISPLAY ADMINISTRATIVE TOOLS&#8221; checkbox.
</p></blockquote>
<p>4.  Ok, now in the Ol&#8217; Dirty Bastard Connections window (ODBC Window) that you just opened in step 3, select the System DSN tab<br />
<img src="http://bobobobo.files.wordpress.com/2009/07/systemdsn.png" /></p>
<blockquote>
<h2>
IMPORTANT NOTE:  IF YOU ARE ON A 64-BIT MACHINE, __DO NOT__, I REPEAT, __DO NOT__ USE THE ODBC Window that is accessible from the taskbar.  Instead, go to START &gt; RUN &gt; C:\Windows\SysWOW64\odbcad32.exe.<br />
</h2>
<h4>
The reason is when developing in Visual Studio 2005/2008, under normal circumstances you in fact cannot publish 64-bit applications, so you CANNOT USE the 64-bit ODBC drivers from your 32-bit application.  So you must set up and use the __32-bit__ ODBC drivers instead.  This is a REAL assbiter.  See jlgdeveloper&#8217;s master-genius answer at <a href="http://forums.devarticles.com/microsoft-sql-server-5/data-source-name-not-found-and-no-default-driver-specified-8346.html#postmenu_203344">http://forums.devarticles.com/microsoft-sql-server-5/data-source-name-not-found-and-no-default-driver-specified-8346.html#postmenu_203344</a> (repeated at bottom of this page for permanence)</h4>
</blockquote>
<p>5.  Click ADD.  You see a menu</p>
<p><img src="http://bobobobo.files.wordpress.com/2009/07/createnewdatasource.png" /></p>
<p>IF YOU DO NOT SEE &#8220;MySQL ODBC 5.1 DRIVER&#8221; there, CALL 911.  Or, try installing the correct version of the ODBC driver.</p>
<p>6.  Now, pick the ODBC 5.1 item and click &#8220;FINISH&#8221; (you&#8217;re not done yet though..)</p>
<p>7.  Fill out the connection params.  This is how I filled out mine.<br />
<img src="http://bobobobo.files.wordpress.com/2009/07/connectionparams.png" /></p>
<p>When you&#8217;re done click TEST.  You should see the box that I see &#8220;Connection successful&#8221;</p>
<p>If you see this box</p>
<p><img src="http://bobobobo.files.wordpress.com/2009/07/wrong.png" /></p>
<p>CALL 911, or double check your parameters and make sure your MySQL daemon is running.</p>
<p>8.  Now that you&#8217;re done that, you should see this:</p>
<p><img src="http://bobobobo.files.wordpress.com/2009/07/mysqldata.png" /></p>
<p>REMEMBER THAT NAME, &#8220;mysqldata&#8221; or whatever name you gave the connection in the top box.  This is the name you&#8217;ll refer to from your program.</p>
<p>9.  Now run this program.  Once again I remind you IF YOU ARE ON A 64-BIT MACHINE, BE SURE TO HAVE SET UP YOUR ODBC CONNECTIONS IN THE C:\Windows\SysWOW64\odbcad32.exe WINDOW, AND NOT THE ODBC WINDOW ACCESSIBLE FROM THE START MENU.  YOU HAVE BEEN WARNED.</p>
<blockquote>
<pre>

///////////////////////////////////////////
//                                       //
// WORKING WITH OL' DIRTY BASTARD (ODBC) //
//                                       //
// You found this at bobobobo's weblog,  //
// http://bobobobo.wordpress.com         //
//                                       //
// Creation date:  July 10/09            //
// Last modified:  July 10/09            //
//                                       //
///////////////////////////////////////////
// Note also nice sample comes with
// WinSDK in <b>C:\Program Files\Microsoft SDKs\Windows\v6.1\Samples\dataaccess\odbc\odbcsql</b>

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;windows.h&gt;

#include &lt;sql.h&gt;
#include &lt;sqltypes.h&gt;
#include &lt;sqlext.h&gt;

// Here is the complete Ol' Dirty Bastard function reference:
// http://msdn.microsoft.com/en-us/library/ms714562(VS.85).aspx

// <a href="http://msdn.microsoft.com/en-us/library/ms711810(VS.85).aspx">This article</a> says you need
// to link with odbc32.lib, but taking the next line of code OUT
// doesn't seem to harm anything
#pragma comment( lib, "odbc32.lib" )

bool CHECK( SQLRETURN rc, char * msg, bool printSucceededMsg=false, bool quit=true )
{
  if( SQL_SUCCEEDED( rc ) )
  {
    if( printSucceededMsg )  printf( "%s succeeded\n", msg ) ;

    return true ;
  }
  else
  {
    printf( "NO!!!  %s has FAILED!!\n", msg ) ;

    if( quit )  FatalAppExitA( 0, msg ) ;

    return false ;
  }
}

void status( SQLSMALLINT handleType, SQLHANDLE theHandle, int line )
{
  SQLCHAR sqlState[6];
  SQLINTEGER nativeError;
  SQLCHAR msgStr[256];
  SQLSMALLINT overBy ; // the number of characters that msgStr buffer was TOO SHORT..

  // <a href="http://msdn.microsoft.com/en-us/library/ms716256(VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms716256(VS.85).aspx</a>
  // This must be the WEIRDEST ERROR REPORTING FUNCTION I've EVER seen.
  // It requires 8 parameters, and its actually pretty .. silly
  // about the amount of state information it expects YOU to keep track of.

  // It isn't so much a "GetLastError()" function
  // as it is a "GetMeStatus( something very, very specific )" function.

  SQLRETURN retCode ;

  for( int i = 1 ; i &lt; 20 ; i++ )
  {
    retCode = SQLGetDiagRecA(

      handleType,  // the type of object you're checking the status of
      theHandle,   // handle to the actual object you want the status of

      i, // WHICH status message you want.  The "Comments" section at the
      // bottom of http://msdn.microsoft.com/en-us/library/ms716256(VS.85).aspx
      // seems to explain this part well.

      sqlState,    // OUT:  gives back 5 characters (the HY*** style error code)
      &amp;nativeError,// numerical error number
      msgStr,      // buffer to store the DESCRIPTION OF THE ERROR.
      // This is the MOST important one, I suppose

      255,         // the number of characters in msgStr, so that
      // the function doesn't do a buffer overrun in case it
      // has A LOT to tell you
      &amp;overBy      // again in case the function has A LOT to tell you,
      // the 255 character size buffer we passed might not be large
      // enough to hold the entire error message.  If that happens
      // the error message will truncate and the 'overBy' variable
      // will have a value &gt; 0 (it will measure number of characters
      // that you 'missed seeing' in the error message).

    ) ;

    if( CHECK( retCode, "SQLGetDiagRecA" ) )
    {
      printf( "LINE %d:  [%s][%d] %s\n", line, sqlState, nativeError, msgStr ) ;
    }
    else
    {
      // Stop looping when retCode comes back
      // as a failure, because it means there are
      // no more messages to tell you
      break ;
    }
  }
}

int main()
{
  // Following <a href="http://msdn.microsoft.com/en-us/library/ms711810(VS.85).aspx">this example</a>, just adding a bit more
  // color and making it work with our specific example.

  // 1.  Create a handle for the environment.
  SQLHANDLE hEnv ;
  SQLRETURN retCode ;

  retCode = SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &amp;hEnv ) ;

  CHECK( retCode, "allocate environment handle" ) ;

  // 2.  Next, set the version of ODBC to use to ODBC version 3.
  // Format of this command is a bit weird, we cast the value we're passing
  // to (void*) because the function requires it, but then we say that the
  // length of the "string" we've passed in is 0 characters long, so I assume
  // that means SQLSetEnvAttr should know to interpret the "pointer value" that
  // we passed in as actually an integer value (which is what it is).
  retCode = SQLSetEnvAttr( hEnv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0 ) ; 

  CHECK( retCode, "setting the environment attribute setting to ODBC version 3" ) ;

  // 3.  Allocate the connection handle.  Note this doesn't
  // connect us to the database YET.  We're still "ALLOCATING",
  // whatever that means :) (Hey i know what allocating is,
  // but this is an awful number of steps to follow if you
  // ask me, microsoft!!  Whatever happened to a simple init()
  // function?
  SQLHANDLE hConn ;

  CHECK( SQLAllocHandle( SQL_HANDLE_DBC, hEnv, &amp;hConn ), "allocate handle" ) ;

  // HOOK IT UP!!  Actually connect to the database.
  SQLCHAR* dsnName = (SQLCHAR*)"mysqldata" ;  // MUST BE THE SAME
  // as the name of the ODBC data source you set
  // in the Microsoft ODBC Administrator window.

  SQLCHAR* userid = (SQLCHAR*)"root";
  SQLCHAR* password = (SQLCHAR*)"";  // using a BLANK
  // Above are my own correct userid and password credentials to
  // be used when logging into the MySQL database server.

  // 4.  Open database connection.
  retCode = SQLConnectA(

    hConn,

    dsnName,  // name of data source we are connecting to,
    // AS PER REGISTERED IN ODBC Data Source Administrator.

    // If you are on a 64-bit machine, and you
    // DO NOT USE THE 64-bit driver.  As long as
    // your compiler publishes a 32-bit .exe (which
    // Visual Studio does), you'll keep getting:

    // [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

    // SO DON'T USE THE 64-BIT DRIVERS!  Instead, install
    // the 32-bit driver, and then managing/using
    // your 32-bit datasources in
    // <b>c:\windows\syswow64\odbcad32.exe</b>

    // Note that on a 64-bit windows machine, the 32-bit
    // drivers and the 64-bit drivers are managed
    // from COMPLETELY SEPARATE, BUT IDENTICAL-LOOKING
    // windows.  Its really weird.

    // On a 64-bit machine:
    // c:\windows\system32\odbcad32.exe    // 64-bit version [even though it SAYS system32_ in the path, this is the __64__ bit version on a 64-bit machine]
    // c:\windows\syswow64\odbcad32.exe    // 32-bit version [even though it SAYS syswow64_ in the path]

    // Call it stupid, scream, pull your hair out,
    // that's what it is.
    // http://stackoverflow.com/questions/949959/why-do-64bit-dlls-go-to-system32-and-32bit-dlls-to-syswow64-on-64bit-windows

    // and

    // http://blogs.sepago.de/helge/2008/04/20/windows-x64-all-the-same-yet-very-different-part-7/

    // Thanks again, Microsoft,
    // for making the 64-bit programming experience
    // such a <em>pleasure</em>.
    SQL_NTS,  // the DSN name is a NULL TERMINATED STRING, so "count it yourself"

    userid,
    SQL_NTS,  // userid is a null-terminated string

    password,
    SQL_NTS   // password is a null terminated string

  ) ;
  if( !CHECK( retCode, "SqlConnectA", false ) )
  {
    // if this fails, I want that extra status
    // information about WHY the failure happened.
    // status function is defined above.

    status( SQL_HANDLE_DBC, hConn, __LINE__ ) ;
  }

  // 6.  Create and allocate a statement
  SQLHANDLE hStmt ;
  CHECK( SQLAllocHandle( SQL_HANDLE_STMT, hConn, &amp;hStmt ), "allocate handle for statement" ) ;

  // 7.  Form a query to run and attach it to the hStmt
  // this basically connects the hStmt up with
  // some results.
  SQLCHAR* query = (SQLCHAR*)"SELECT * from user" ;
  CHECK( SQLExecDirectA( hStmt, query, SQL_NTS ), "execute query" ) ;

  // 8.  Read data results that are now in the hStmt.
  retCode = SQLFetch( hStmt ) ;

  CHECK( retCode, "first sqlFetch" ) ;

  // How many rows got returned?
  SQLLEN numRows ;
  retCode = SQLRowCount( hStmt, &amp;numRows ) ;
  printf( "%d rows were fetched, ruff.\n", numRows ) ;

  // With a query like the one we wrote (SELECT *),
  // we don't know how many columsn should be in
  // the result set at this point.
  // So we ask ODBC to tell us!
  SQLSMALLINT numCols ;
  retCode = SQLNumResultCols( hStmt, &amp;numCols ); // <a href="http://msdn.microsoft.com/en-us/library/ms715393(VS.85).aspx">SqlNumResultCols</a>

  // Now print the column names.
  // <a href="http://msdn.microsoft.com/en-us/library/ms716289(VS.85).aspx">SQLDescribeCol function</a>
  SQLCHAR colName[ 256 ] ;

  SQLSMALLINT colNameLen, dataType, numDecimalDigits, allowsNullValues ;
  SQLUINTEGER columnSize ;

  for( int i = 1 ; i &lt;= numCols ; i++ )
  {
    retCode = SQLDescribeColA( hStmt, i, colName, 255, &amp;colNameLen, &amp;dataType, &amp;columnSize, &amp;numDecimalDigits, &amp;allowsNullValues ) ;
    if( CHECK( retCode, "SQLDescribeCol" ) )
    {
      printf( "Column #%d: '%s', datatype=%d size=%d decimaldigits=%d nullable=%d\n",
                       i,colName,   dataType, columnSize,  numDecimalDigits, allowsNullValues ) ;
    }
  }

  for( int i = 1 ; i &lt;= numRows ; i++ )
  {
    // <a href="http://msdn.microsoft.com/en-us/library/ms714556(VS.85).aspx">Datatypes</a>
    // <a href="http://msdn.microsoft.com/en-us/library/ms715441(VS.85).aspx">SQLGetData</a>

    char buf[256];
    SQLINTEGER numBytes ;

    for( int j = 1 ;   // column counter starts at __1__, not 0.
      j &lt;= numCols ;   // numCols retrieved above
      j++ )
    {
      retCode = SQLGetData(

        hStmt,
        j,           // COLUMN NUMBER of the data to get
        SQL_C_CHAR,  // the data type that you expect to receive
        buf,         // the place to put the data that you expect to receive
        255,         // the size in bytes of buf (-1 for null terminator)
        &amp;numBytes    // size in bytes of data returned

      ) ;

      if( CHECK( retCode, "SqlGetData", false ) )
      {
        // Print the data we got.
        printf( "%10s", buf ) ;
      }

    } // end for.

    puts("");

    // Try and fetch the next result.
    // fall out of the loop if fetch fails
    // (meaning, no more data to get)
    retCode = SQLFetch( hStmt ) ;
    if( !SQL_SUCCEEDED( retCode ) )
    {
      // SQLFetch FAILS AS IT FETCHES the last row of data.
      printf( "And %d is the LAST row.. we're not getting any more after this one\n", i ) ;
    }
  }

  // So we used a FOR loop above to fetch
  // exactly numRows rows from the results.

  // The other (perhaps more common)
  // way to do this is to use a loop like

  // while( SQL_SUCCEEDED( SQLFetch( hStmt ) ) )
  // {
  //   // Work with result data
  // }

  // When we do it that way,
  // WE EXPECT/RELY ON SQLFetch TO TELL US
  // IT FAILED when we've reached the
  // LAST row of data.

  // free up resources.
  SQLFreeHandle( SQL_HANDLE_STMT, hStmt ) ;
  SQLFreeHandle( SQL_HANDLE_DBC, hConn ) ;
  SQLFreeHandle( SQL_HANDLE_ENV, hEnv ) ;
}

// Assbiters:
// 1. Be careful not to use the SUCCEEDED() macro
// instead of the SQL_SUCCEEDED() macro when
// checking your SQLRESULT values.
//
// 2. Do not use 64-bit ODBC drivers, even if on
// a 64-bit machine.  See information above.

/*
     ____   __   __      __   __  ___
    / _  \ /  / /  /    /  /  \ \/  /
   / _/ / /  / /  /    /  /    \   /
  / _/ \ /  / /  /__  /  /__   /  /
 /_____//__/ /______//______/ /__/

*/
</pre>
</blockquote>
<p>Master genius John</p>
<blockquote><p>
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified</p>
<p>I had this error and want to let you know how it was resolved.</p>
<p>First, this was an ASP web application using a vb 6.0 dll to get data from a sql server 2005 database on a 64 bit windows server 2008 enterprise (vista like) server. I could only get the dll to work in component services as opposed to simply registering it.</p>
<p>It all worked fine upon setup, but after four windows updates one night, the error above was posted in the event viewer, and the web app crashed.</p>
<p>Here is the resolution:</p>
<p>In a 64 bit windows server operating system, there are TWO odbc managers. When you pull up the usual menu for the odbc / dsn system, it is for the 64 bit odbc manager, and 32 bit applications (vb 6.0) will not work using these dsn&#8217;s.</p>
<p>This is where the 32 bit odbc manager is:</p>
<p>C:\Windows\SysWOW64\odbcad32.exe</p>
<p>I hope you do not have to go through what I and three Microsoft Support engineers had to to figure this out.</p>
<p><a href="http://forums.devarticles.com/microsoft-sql-server-5/data-source-name-not-found-and-no-default-driver-specified-8346.html#postmenu_203344">Jonathan</a>
</p></blockquote>
<h3><a href="http://www.esnips.com/nsdoc/f3243bb8-6157-4acd-a19b-8cd41482f2bc/?action=forceDL">Download the code package courtesy of esnips</a> (thanks esnips!)</h3>
Posted in C C++, C++, mysql Tagged: C++, mysql, odbc <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bobobobo.wordpress.com/1252/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bobobobo.wordpress.com/1252/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bobobobo.wordpress.com/1252/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bobobobo.wordpress.com/1252/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bobobobo.wordpress.com/1252/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bobobobo.wordpress.com/1252/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bobobobo.wordpress.com/1252/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bobobobo.wordpress.com/1252/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bobobobo.wordpress.com/1252/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bobobobo.wordpress.com/1252/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1252&subd=bobobobo&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://bobobobo.wordpress.com/2009/07/11/working-with-odbc-from-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a4ec51727310397c9e592dd84ae74dc2?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">bobobobo</media:title>
		</media:content>

		<media:content url="http://bobobobo.files.wordpress.com/2009/07/db-full-diagram-small.png" medium="image" />

		<media:content url="http://bobobobo.files.wordpress.com/2009/07/cpp-mysql.png" medium="image" />

		<media:content url="http://bobobobo.files.wordpress.com/2009/07/cpp-odbc-mysql.png" medium="image" />

		<media:content url="http://bobobobo.files.wordpress.com/2009/07/cpp-ole-db-odbc-mysql.png" medium="image" />

		<media:content url="http://bobobobo.files.wordpress.com/2009/07/cpp-ado-ole-db-odbc-mysql.png" medium="image" />

		<media:content url="http://bobobobo.files.wordpress.com/2009/07/systemdsn.png" medium="image" />

		<media:content url="http://bobobobo.files.wordpress.com/2009/07/createnewdatasource.png" medium="image" />

		<media:content url="http://bobobobo.files.wordpress.com/2009/07/connectionparams.png" medium="image" />

		<media:content url="http://bobobobo.files.wordpress.com/2009/07/wrong.png" medium="image" />

		<media:content url="http://bobobobo.files.wordpress.com/2009/07/mysqldata.png" medium="image" />
	</item>
		<item>
		<title>Getting started with Direct3D IN C++</title>
		<link>http://bobobobo.wordpress.com/2009/07/03/getting-started-with-direct3d-in-c/</link>
		<comments>http://bobobobo.wordpress.com/2009/07/03/getting-started-with-direct3d-in-c/#comments</comments>
		<pubDate>Fri, 03 Jul 2009 20:40:09 +0000</pubDate>
		<dc:creator>bobobobo</dc:creator>
				<category><![CDATA[C C++]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[d3d]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://bobobobo.wordpress.com/?p=1213</guid>
		<description><![CDATA[This is a very long, very long, very long tutorial about how to get started with D3D in C++.
Check it out!


//////////////////////////////////////////
//                                   [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1213&subd=bobobobo&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This is a very long, very long, very long tutorial about how to get started with D3D in C++.</p>
<p>Check it out!</p>
<blockquote>
<pre>
//////////////////////////////////////////
//                                      //
// Direct3D basics                      //
//                                      //
// You found this at bobobobo's weblog, //
// http://bobobobo.wordpress.com        //
//                                      //
// Creation date:  July 1/09 (HAPPY CANADA DAY! ) //
// Last modified:  July 3/09            //
//                                      //
//////////////////////////////////////////

#include &lt;windows.h&gt;
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;math.h&gt;

#include &lt;d3d9.h&gt;      // core direct3d
#include &lt;d3dx9.h&gt;     // aux libs

#include &lt;dxerr9.h&gt;    // detailed error messages

#pragma comment(lib, "d3d9.lib")
#pragma comment(lib, "d3dx9.lib")  // aux libs
#ifdef _DEBUG
#pragma comment(lib,"d3dx9d.lib")
#else
#pragma comment(lib,"d3dx9.lib")
#endif

#pragma comment(lib, "dxerr9.lib")

// Macros.
#define SAFE_RELEASE(ptr) if(ptr) { ptr-&gt;Release(); ptr = NULL; }
#define CAST_AS_DWORD(x) *((DWORD*)&amp;x)
#define PI 3.14159

struct Globals
{
  // Wrapping the Win32-related variables up
  // together in their own struct so they don't
  // get in the way of the Direct3D ones
  struct _Win
  {
    HINSTANCE hInstance;    // window app instance
    HWND hwnd;              // handle for the window
    HWND hConsole ;         // handle for the console window

    int width, height;      // the desired width and
    // height of the CLIENT AREA
    // (DRAWABLE REGION in Window)
  } win ;

  #pragma region DIRECT3D9 stuff
  ////////////////////////////
  // Declare The IDirect3D9 INTERFACE!!
  // <a href="http://msdn.microsoft.com/en-us/library/bb174300(VS.85).aspx">IDirect3D9 interface</a>
  IDirect3D9 * d3d ;        // represents the BEAST
  // that is Direct3D9 itself.  What's it for?

  // MSDN SAYS about the IDirect3D9 interface:
  // "Applications use the methods of the IDirect3D9 interface
  // to create Microsoft Direct3D objects and set up the
  // environment. This interface includes methods for
  // enumerating and retrieving capabilities of the device."

  // <a href="http://msdn.microsoft.com/en-us/library/bb174336(VS.85).aspx">IDirect3DDevice9</a>
  IDirect3DDevice9 * gpu ;  // represents the GPU

  // MSDN SAYS about the IDirect3DDevice9:  "Applications use the
  // methods of the IDirect3DDevice9 interface to perform
  // DrawPrimitive-based rendering, create resources, work
  // with system-level variables, adjust gamma ramp levels,
  // work with palettes, and create shaders."
  ////////////////////////////

  // The ABOVE TWO variables are
  // very important to this application.

  // For both of these, notice how they
  // are BOTH POINTERS to an INTERFACE.

  // What's an interface?  Well, in a few words,
  // an INTERFACE is something you "face" to
  // interact with something.  Thru means of
  // the "INTERFACE" you get information from
  // the underlying system, or send commands
  // to the underlying system, without really
  // having to understand the underlying system
  // at all to do it.  You just have to know what
  // types of commands it expects to get.

  // For example, your car.

  // The "interface" of your car is its steering wheel,
  // its dials on the dash telling you what speed
  // you're going and the RPM's you're at so you
  // don't blow the engine redlining, and also,
  // the gas and brakes, so you can send commands
  // to the car to stop and go.

  // Notice how you don't have to know a THING
  // about how an internal combustion engine works
  // to get the car to go.  Because the car's INTERFACE
  // is SO abstract (simply PUSH THE PEDAL TO GO),
  // working the car becomes incredibly simple.

  // If the car didn't have such an abstract
  // interface (like, if REALLY crummy engineers
  // made a car), then to drive that crummy car,
  // you might have to put your hands into
  // the engine and carefully push
  // vaporized gas underneath a piston, then
  // push down on the piston until it goes POP!
  // Then the car would be going!

  // Anyway, point is, working with a system
  // THROUGH ITS INTERFACE that the system defines
  // makes working with the system SO easy, and
  // the system itself is a black box -- its internal
  // workings are hidden from you.  Like, you
  // don't even have to know what an internal
  // combustion engine IS to be able to
  // work a modern car.  Heck, for all you know,
  // it might not even be an internal combustion
  // engine!  (It might be electric).  That's another
  // beauty about interfaces:  You can swap out
  // the nitty gritty details of the implementation
  // (e.g. software updates / patches, or the
  // difference between Direct3D9 June 2008 release
  // and March 2009 release) without affecting
  // the programs that USE those interfaces, so long
  // as you have not CHANGED the interface itself.

  // IN the case of Direct3D9, an IDirect3DDevice9 *
  // is a pointer to, let's just say the "dashboard" ON TOP
  // OF the Direct3D9 RENDERING MACHINE.

  // Inside, the Direct3D 3D graphics "engine" is VERY complex!
  // Especially when you get to rendering textures in 3D..
  // (see <a href="http://www.cs.utah.edu/~shirley/books/fcg2/">this book</a> if you want to learn that stuff!)

  // But with Direct3D9, you don't have to understand
  // HOW 3d graphics actually gets drawn.  You only have to
  // understand the format that D3D expects, and pass it
  // your data that you want drawn in that format.

  // OK?  So hopefully that made a little bit of sense.
  // To me Direct3D seems slightly more "centralized"
  // than OpenGL does.  With OpenGL, the "interface"
  // is a set of C-style functions that all begin
  // with gl*.  OpenGL doesn't have an "INTERFACE"
  // in the OOP sense (but that set of gl* C functions
  // is still an 'interface' though, its just a very
  // different way of creating one!)

  // Anyway, on with it.
  #pragma endregion
};

///////////////////////////
// GLOBALS
// declare one struct Globals called g;
Globals g;
//
///////////////////////////

///////////////////////////
// FUNCTION PROTOTYPES
// Windows app functions.  If need help
// understanding these, see <a href="http://bobobobo.wordpress.com/2008/01/31/how-to-create-a-basic-window-in-c/">MostBasicWindow</a>
// and <a href="http://bobobobo.wordpress.com/2008/02/03/skeleton-of-a-fast-c-windows-program-for-games-using-peekmessage/">FastWindowsProgram</a>
LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam );
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow );

inline bool CHECK( HRESULT hr, char * msg, bool stop=true ) ;  // checks for errors on the HR passed.

bool initD3D() ;         // function to initialize the BEAST that is Direct3D9
void printSystemInfo() ; // function that prints some system info.  can ignore if not interested
void draw() ;            // drawing function containing Direct3D drawing calls

//
///////////////////////////

/// If there was an error, the ErrorString is printed out for you to see at the console.
inline bool CHECK( HRESULT hr, char * msg, bool stop )
{
  if( FAILED( hr ) )
  {
    printf( "%s. %s:  %s\n",
            msg, DXGetErrorString9A( hr ), DXGetErrorDescription9A( hr ) ) ;

    // Pause so we can see the error and deal with it.
    if( stop )  system("pause") ;

    return false ;
  }

  else
    return true ;

}

///////////////////////////
// FUNCTION IMPLEMENTATIONS
/// Initializes Direct3D9.  Returns true on success.
bool initD3D()
{
  // start by nulling out both pointers:
  g.d3d = 0 ;
  g.gpu = 0 ;

  // Create the IDirect3D9 (d3d) object now.  We need the d3d object
  // in order to be able to create the IDirect3DDevice9 interface.
  // We can also use the d3d object to find out additional information
  // about the system we are on (such as the number of displays it has, etc).

  // [[ I know, I know.  If you think its confusing/stupid to have
  // two separate Direct3D9 things both starting with I,
  // just bear with it because you'll see that these two objects
  // will do VERY different things, and you'll see it does
  // make a whole lot of sense to separate them out into two things.
  // Granted, they could have been named a little more distinctly,
  // but whaddya gonna do... ]]

  // So, the IDirect3D9 object (variable 'd3d') is the "interface"
  // or means by which we will access the Direct3D9
  // beast

  // And the IDirect3DDevice9 (called 'gpu') is THE
  // variable that IS OUR PROGRAMMATIC HANDLE TO THE GPU and
  // we will use it A LOT to send down triangles and stuff to the
  // gpu to be drawn.

  // we'll be using 'gpu' a lot more than 'd3d'.

  // So now, to create our 'd3d' interface.
  // Remember, FROM this interface will come
  // our 'gpu' interface.

  // <a href="http://msdn.microsoft.com/en-us/library/bb219676(VS.85).aspx">Direct3DCreate9</a>
  g.d3d = Direct3DCreate9( D3D_SDK_VERSION ) ;  // Always use D3D_SDK_VERSION

  if( g.d3d == NULL )
  {
    // DEVICE CREATION FAILED!!!! OH NO!!!
    puts( "Oh.. PHOOEY!!!!!  Device creation FAILED!!! WHAT NOW???\n" ) ;
    return false ;
  }

  // Ok, if we get here without returning, it means device creation succeeded.
  puts( "Device creation SUCCESS!!!!\nWe're in business now, son..\n" ) ;

  // Next we'll just print a few details about the system
  // just because we can..
  // Note how we use PURELY the 'd3d' object
  // to do this (NOT the 'gpu' device, which hasn't
  // even been created yet!)
  ///// printf( "I will now tell you some \nthings ABOUT your system.\n" );
  ///// printSystemInfo(); // BOOOOORING.

  puts( "Ok, Now to CREATE the 'gpu' device!!" ) ;

  // First, create the D3DPRESENT_PARAMETERS structure.
  // This structure will basically "explain" to the
  // IDirect3D9 interface EXACTLY WHAT we want the
  // GPU rendering surface to look like once
  // it has been created.

  // <a href="http://msdn.microsoft.com/en-us/library/bb172588(VS.85).aspx">D3DPRESENT_PARAMETERS</a> structure
  D3DPRESENT_PARAMETERS pps = { 0 } ;  // Start structure all 0'd out.

  // We're using a windowed mode, NOT fullscreen in this
  // example.  Its really annoying to program little test
  // apps in fullscreen mode.  Also when using windowed mode
  // we don't have to (in fact, we should not) specify
  // some of the other parameters, such as the refresh rate.
  pps.Windowed = true ;

  // How many backbuffers do we want?  One.
  pps.BackBufferCount = 1 ;

  // <a href="http://msdn.microsoft.com/en-us/library/bb172612(VS.85).aspx">This one's interesting</a>
  // Backbuffering.  Imagine Leonardo Davinci doing
  // a live animation for you.

  // Imagine he stood in front of the canvas,
  // and blazingly quickly, painted a live scene for you.
  // Then to make the animation effect happen, he'd have
  // to erase the canvas (paint over it in all white?) then
  // paint over that white the next frame.

  // Not that great for watching an "animation!"  even if
  // he moved blazing fast, it'd still be "flickery" having
  // to "see" the canvas get all cleared out, then see each
  // shape get drawn on.

  // So instead, Davinci has a better idea.  He will
  // use TWO canvases.  He will draw to the canvas
  // in a HIDDEN place, where you can't see it.

  // When he's done painting hte first frame, BAM,
  // he slams it in your face and you can see it.
  // He then takes a SECOND canvas, and paints to it
  // blazing fast, what should be the next frame you see.
  // Then, BAM, he slams that second canvas right in your face,
  // where you can see it.  He then quietly pulls away
  // that first canvas that had the first frame on it
  // (which you can't see anymore, because you're looking
  // at the SECOND canvas he just slammed in your face),
  // and quickly paints the NEXT (3rd) frame onto it.
  // Then, BAM, he slams that first canvas in your face
  // again, but now it has the 3rd frame on it.  He then
  // takes the SECOND canvas, and draws the 4th frame on it...

  // Do you see what's happening here?  Read it again
  // if not... the whole point is to give a MUCH smoother
  // and continuous presentation of image frames.  If you
  // didn't use a backbuffer, then the animation presented
  // would look all awful and flickery and horrible because
  // you'd basically be WATCHING the gpu do its drawing work,
  // instead of looking at nice finished product painted scenes instead.

  // <a href="http://msdn.microsoft.com/en-us/library/bb206356(VS.85).aspx">Swap chains</a>
  pps.SwapEffect = D3DSWAPEFFECT_DISCARD ; // You start with
  // 2 buffers, one that displays what you're currently
  // looking at (the "frontbuffer") and
  // one that is hidden from you (the "backbuffer").

  // Basically FLIP means that
  // d3d should DRAW to the BACKBUFFER first, then
  // when its done doing that, it should BAM, slam
  // that backbuffer in your face, so you can see it.
  // The former front buffer, is then DISCARDED.

  // SO, the former "backbuffer" is NOW the FRONTBUFFER.
  // And the former front buffer, we will treat
  // as the NEW "backbuffer".

  // SO draw to the OTHER buffer now (which is considered
  // as the backbuffer at the moment), when you're done,
  // BAM, slam that backbuffer in the user's face
  // (so again, the former "backbuffer" has flipped
  // and become the frontbuffer).

  // The OTHER way to do this is to DRAW TO
  // the backbuffer, then to COPY OUT the backbuffer
  // in its entirety to the front buffer.  That's
  // less efficient though, for obvious reasons
  // (copying about 2,000,000 pixels has gotta take
  // at least some time!).  Discard is nice, but
  // using it REQUIRES that you completely update
  // ALL the pixels of the backbuffer before presenting it
  // (because there's NO TELLING what will happen to
  // the frontbuffer once you've "discarded" it!
  // Microsoft says "we might do anything to it..."
  // The Clear() operation is sufficient to touch every
  // pixel on the buffer, so as long as you're calling
  // Clear() every frame, there's nothing to worry about.
  // You'll see Clear() in use a bit later in this tutorial.)

  // Pixel format to use on the backbuffer.
  pps.BackBufferFormat = D3DFMT_UNKNOWN ;   // So, this doesn't mean
  // we don't KNOW the pixel format we want.. its more
  // like saying "D3DFMT_CHOOSE_IT_FOR_ME!"

  // What really happens is "color conversion is done by the hardware"

  // But you can think of it as D3D should picking
  // the appropriate pixel format to use.

  // Now, we WANT Direct3D to create and manage
  // a depth buffer for this surface.  That means
  // if we draw two triangles and one is "closer"
  // than the other, then the "closer" one should
  // be drawn on top of the "further" one.  That's
  // achieved using the <a href="http://msdn.microsoft.com/en-us/library/aa915211.aspx">depth buffer</a>
  pps.EnableAutoDepthStencil = true ;
  // Now we have to say "how deep" is the depth buffer.
  // Kind of.  How precise are the depth values?
  // The more bits you use, the more "slots of depth"
  // your depth buffer can handle.  If your depth buffer
  // used 2 bits, it might be able to handle 4 levels
  // of depth.  With 16 bits, there's a lot more levels of
  // depth.  Having many different levels of depth is
  // really important because if two objects are
  // like thought by the gpu to be at the exact same
  // "depth", then there will be "z-fighting"
  // <a href="http://www.cg.tuwien.ac.at/~kchustl/zfighting.png">z-fighting sample1</a>
  // Apparently <a href="http://forums.amd.com/game/messageview.cfm?catid=279&amp;threadid=104957">some users</a> experienced problems
  // with z-fighting when playing GTA 4 on ATI hardware.

  // We choose a fairly "deep" pixel format (16 bits)
  // Could also choose 24 bits.
  pps.AutoDepthStencilFormat = D3DFMT_D16 ;

  // Finally, make the gpu device.
  HRESULT hr = g.d3d-&gt;CreateDevice(

    D3DADAPTER_DEFAULT, // primary display adapter
    D3DDEVTYPE_HAL,     // use HARDWARE rendering (fast!)
    g.win.hwnd,
    D3DCREATE_HARDWARE_VERTEXPROCESSING,
    &amp;pps,
    &amp;g.gpu  // THIS IS where you get
    // the ACTUAL return value (the
    // GPU device!) from this function.
    // Because this function has its
    // return value as an HRESULT,
    // the return value is used to
    // indicate success or failure.

  ) ;

  if( !CHECK( hr, "OH NOS!! I could not initialize Direct3D!  Bailing...\n" ) )
  {
    return false ;
  }

  // Successfully created direct3d9 devices
  printf( "WHOO!  We SUCCESSFULLY created the Direct3D9 GPU device\n" ) ;

  return true ;
}

////////////////////////
// DRAWING FUNCTION
void draw()
{
  HRESULT hr ;

  #pragma region clear
  // First, we will clear the backbuffer.  This is a VERY general use
  // function and has way more capabilities than we care to use
  // at the moment.  For example, you can choose to clear little
  // sub-rectangles of the screen ONLY instead of clearing the whole
  // screen with the first 2 params.  we're not interested in that though,
  // we just wanna clear the whole screen.

  // <a href="http://msdn.microsoft.com/en-us/library/bb174352(VS.85).aspx">IDirect3DDevice9::Clear()</a>
  hr = g.gpu-&gt;Clear(

    0, // NUMBER of sub rectangles to clear.  We set to 0 because
       // we don't want to even clear any subrectangles.. we just
       // want to clear the WHOLE thing!

    0, // you can choose to clear only a sub-region of the
       // backbuffer.  But we wanna clear the WHOLE back buffer!
       // so we pass 0 here and d3d will automatically clear the WHOLE THING for us.

    // <a href="http://msdn.microsoft.com/en-us/library/bb172514(VS.85).aspx">D3DCLEAR</a>
    D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER /* | D3DCLEAR_STENCIL */,  // next is weird, but
    // here we specify WHAT exactly we want cleared.  Because a 3d
    // buffer is actually made of several LAYERS (color layer,
    // and depth layer, and stencil layer), you choose
    // what exactly what you want cleared.  If you weren't
    // doing 3d graphics for example (you used direct3d9 to draw
    // 2d graphics, which you can!) you would have no need for
    // the depthbuffer.  So you could save a bit of time
    // (clearing a buffer is a relatively expensive operation)
    // by NOT clearing the buffers you aren't going to use.

    // In this example we are NOT using the stencil buffer,
    // but we ARE using the color BUFFER ITSELF (like color values)
    // hence specification of D3DCLEAR_TARGET,
    // and we ARE using the depth buffer (D3DCLEAR_ZBUFFER)
    // but we are NOT using the stencil buffer (hence me omitting
    // D3DCLEAR_STENCIL).  There's no sense in clearing out a
    // buffer that's not in use.  That's like vaccumming a room
    // that's just been vaccummed squeaky clean.
    // If you're not going to be picking up any extra dirt,
    // cleaning it again is really just a waste of time and energy.

    D3DCOLOR_ARGB( 255, 125, 25, 237 ),  // The color to clear
    // the backbuffer out to.

    1.0f, // value to clear the depth buffer to.  we clear
    // it to 1.0f because 1.0f means ("furthest away possible
    // before being out of range")

    // So we clear every value in the depth buffer to this
    // value so when something is rendered that is in view range,
    // it will definitely be closer than 1.0f!
    // (0.0f means right in our faces).

    0  // value to clear the stencil buffer to.  since we
    // chose NOT to clear the stencil buffer (omitted
    // D3DCLEAR_STENCIL from above), this value is
    // actually going to be ignored.

  ) ;
  CHECK( hr, "Clear FAILED!" ) ;

  #pragma endregion

  #pragma region set up the camera

  // First we start by setting up the viewport.
  // the viewport "Defines the window dimensions of
  // a render-target surface onto which a 3D volume projects."
  D3DVIEWPORT9 viewport ;

  // <a href="http://msdn.microsoft.com/en-us/library/bb172632(VS.85).aspx">Very clear explanations</a> of each (and advice! :) )
  // of these members are on msdn.
  viewport.X = 0 ;
  viewport.Y = 0 ;
  viewport.Width = g.win.width ;
  viewport.Height = g.win.height ;
  viewport.MinZ = 0.0f ;
  viewport.MaxZ = 1.0f ;

  g.gpu-&gt;SetViewport( &amp;viewport ) ;

  // Technically we don't need to set the viewport here
  // BUT you can use viewport setting to draw "picture in picture" -

  // Form the 

  // Set projection matrix
  D3DXMATRIX projx ;

  // <a href="http://msdn.microsoft.com/en-us/library/bb205351(VS.85).aspx">Create a perspective matrix</a>
  D3DXMatrixPerspectiveFovRH( &amp;projx, PI/4, (float)g.win.width/g.win.height, 1.0f, 1000.0f ) ;

  // set
  g.gpu-&gt;SetTransform( D3DTS_PROJECTION, &amp;projx ) ;

  // Create the view matrix
  D3DXMATRIX viewx ;

  D3DXVECTOR3 eye( 4, 2, 4 ) ;
  D3DXVECTOR3 look( 0, 0, 0 ) ;
  D3DXVECTOR3 up( 0, 1, 0 ) ;
  D3DXMatrixLookAtRH( &amp;viewx, &amp;eye, &amp;look, &amp;up ) ;
  g.gpu-&gt;SetTransform( D3DTS_VIEW, &amp;viewx ) ;
  #pragma endregion

  // Preparing to draw
  // FVF.  WTF is an FVF?
  // MSDN:  "Flexible Vertex Format Constants, or FVF codes,
  //   are used to describe the contents of vertices
  //   interleaved in a single data stream that will
  //   be processed by the fixed-function pipeline."

  // FVF stands for "FLEXIBLE VERTEX FORMAT".  If you're familiar with
  // OpenGL, this is a completely (but some might say a little bit better..)
  // way of allowing a person to say WHAT data each vertex has tagged along
  // with it.

  // So let's tell Direct3D what data exactly each VERTEX
  // will have.  A position?  A color?  A normal?  A texture
  // coordinate?  What do you WANT TO specify for each vertex.

  hr = g.gpu-&gt;SetFVF(

    D3DFVF_XYZ  // THe most OBVIOUS (and most important?) aspect of a VERTEX is
    // that it have a POSITION, XYZ.  Specifying that our vertex format
    // includes an XYZ position

    | D3DFVF_DIFFUSE // We also specify a diffuse color for each vertex.

  ) ;
  CHECK( hr, "SetFVF FAILED!" ) ;

  // So there we have it.  We just told d3d to expect
  // to get vertices that each have an XYZ coordinate
  // AND a color specified for them.

  // SO NOW, before DRAWING anything, we have to
  // do 2 more things:
  //   #1)  Create a D3DVERTEXELEMENT9 structure
  //       which will represent our vertex format.

  //   #2)  Create an array of vertices to draw!

  //   #3)  Just draw it!

  // #1)  This part is a bit confusing at first,
  // but if you read through it carefully, it should
  // make sense.

  // What we need to do here is create a SPECIAL
  // kind of structure called a "VERTEX DECLARATION"
  // This VertexDeclaration will MATCH UP with
  // the "FVF" format that we set up just a couple
  // of lines ago.  Read on!

  // In the specification, we actually have to
  // obey the <a href="http://msdn.microsoft.com/en-us/library/bb147173(VS.85).aspx">FVF mapping</a>
  // on msdn.

  /////////////
  #pragma region // &lt;position vertex element decl&gt;
  // <a href="http://msdn.microsoft.com/en-us/library/bb205919(VS.85).aspx">IDirect3DVertexDeclaration9</a>

  // OK in the FVF above, we promised d3d that
  // EACH AND EVERY vertex would have a POSITION
  // and a COLOR.

  // So we declare and set up TWO D3DVERTEXELEMENT9
  // structures which explain to d3d the EXACT format
  // and nature of each vertex -

  // IS this a bit redundant?  Kind of, yes.  Getting
  // on with it.

  D3DVERTEXELEMENT9 pos ;

  // Here is where we say that this part
  // of the vertex will specify a POSITION
  // in space.
  pos.Usage = D3DDECLUSAGE_POSITION ;

  // This part makes sense if you understand
  // that sometimes, you want to send MORE THAN
  // one position coordinate for each vertex.
  // If that makes less sense, then think about
  // sending down more than one COLOR for each
  // vertex, for some type of funky color blending.
  pos.UsageIndex = 0 ;

  pos.Stream = 0 ; // Vertex shaders have a concept
  // of "stream".

  // So what's a "stream" you ask?
  // This really is QUITE an advanced topic, so my honest advice
  // to you is to completely ignore the below unless you
  // REALLY want to know what streams are.

  // &lt;streams&gt;
  // There is a concept in GPU programming called "shader instancing".
  // Shader instancing is when you specify a model's geometry once,
  // then draw that same model like a million times.

  // <img src="http://bobobobo.files.wordpress.com/2009/04/mesh_instancing_j.jpg" />

  // So, you specify the model vertex data with POSITIONS on
  // channel 0, for example.  Then you specify a bunch of
  // positions on channel 1 (1,000,000 positions in your game world,
  // or something) that describe places to draw ALL the vertices
  // that are on channel 0.

  // So its really quite complicated and hard to understand.
  // Channels are like TV -- like the TV station sends like,
  // 500 channels down to your TV in parallel (hey, pretend
  // they do), the vertex data you send down to the GPU
  // all goes down to the GPU in parallel, work at drawing the same thing, kind of.

  // Your tv can tune into one channel at a time only, and the GPU
  // will actually tune into ALL the channels when drawing..
  // &lt;/streams&gt;

  // UH, where were we?  Next, we specify the actual data type of
  // the position data.

  pos.Type = D3DDECLTYPE_FLOAT3 ;  // "Vertices will use
  // 3 floats to specify their position in space".

  // If you are familiar with GPU datatypes and HLSL,
  // this would correspond directly with the "float3"
  // datatype in the vertex shader.

  // If you don't know what a vertex shader is,
  // just suffice it to say, that all this means
  // is 3 floats will be used for the POSITION
  // of the vertex.

  // Next we set the "offset":

  pos.Offset = 0 ;

  // In the Vertex STRUCT that WE defined,
  // this is the byte offset from the start
  // of the struct where D3D SHOULD expect
  // to find this data.

  // Using default method.
  pos.Method = D3DDECLMETHOD_DEFAULT ; // <a href="http://msdn.microsoft.com/en-us/library/bb172532(VS.85).aspx">here's more info</a>

  #pragma endregion // &lt;/position vertex element decl&gt;
  /////////////

  /////////////
  #pragma region // &lt;color vertex element decl&gt;
  // Next we declare the vertex element that
  // will represent the DIFFUSE COLOR component.
  D3DVERTEXELEMENT9 col;

  col.Usage = D3DDECLUSAGE_COLOR ; // its a color
  col.UsageIndex = 0 ; // COLOR0
  col.Stream = 0 ;

  col.Type = D3DDECLTYPE_D3DCOLOR ; // UNFORTUNATELY you MUST
  // chose D3DDECLTYPE_D3DCOLOR when using COLOR0
  // or COLOR1.  If you write your own shader,
  // then you can use a FLOAT4 color.

  // NEXT, the OFFSET.  The offset is
  // 3*sizeof(float) because the 'POSITION'
  // comes first and takes up 3 floats as we
  // specified above.
  col.Offset = 3*sizeof( float ) ;
  col.Method = D3DDECLMETHOD_DEFAULT ;
  #pragma endregion // &lt;/color vertex element decl&gt;
  /////////////

  /////////////
  #pragma region create and set vertex declaration
  // Now put the two D3DVERTEXELEMENT9's into
  // an array and create the VertexDeclaration:
  D3DVERTEXELEMENT9 vertexElements[] =
  {
    pos,
    col,

    // VERY IMPORTANT!  D3D doesn't konw
    // HOW MANY elements you will be specifying
    // in advance, so you TELL IT by passing
    // this SPECIAL D3DVERTEXELEMENT9 object
    // which is basically just like the null
    // terminator at the end of C string.
    D3DDECL_END()
  } ;

  IDirect3DVertexDeclaration9 * Vdecl ;

  // Now register in the "vertexElements" array
  // we just created above into the decl
  hr = g.gpu-&gt;CreateVertexDeclaration( vertexElements, &amp;Vdecl ) ;
  CHECK( hr, "CreateVertexDeclaration FAILED!" ) ;

  // Now SET IN that vertex declaration into the GPU
  hr = g.gpu-&gt;SetVertexDeclaration( Vdecl ) ;
  CHECK( hr, "SetVertexDeclaration FAILED!" ) ;
  #pragma endregion

  #pragma region set render states
  // FINALLY, last thing before drawing, we
  // have to set the renderstate to USE
  // the DIFFUSE component to determine the
  // color of each vertex
  // <a href="http://msdn.microsoft.com/en-us/library/bb147265(VS.85).aspx">Per-Vertex Color State</a>
  hr = g.gpu-&gt;SetRenderState( D3DRS_COLORVERTEX, TRUE ) ;
  CHECK( hr, "SetRenderState( COLORVERTEX ) FAILED!" ) ;

  // Turn LIGHTING off.  TRUE to enable Direct3D lighting,
  // or FALSE to disable it. The default value is TRUE.
  // __Only vertices that include a vertex normal are properly lit;
  // vertices that do not contain a normal ___employ a dot product of 0___
  // in all lighting calculations.__!

  // So if you don't disable lighting, what will actually happen is,
  // since we don't specify normals for any of our vertices,
  // they will all have a normal vertex of the 0 vector, so
  // the result is they will all be completely black.
  hr = g.gpu-&gt;SetRenderState( D3DRS_LIGHTING, FALSE ) ;
  CHECK( hr, "Lighting off" ) ;

  // Turn backface culling off.  Its good to turn this off
  // when starting out because triangles that you wind
  // ccw are discarded if this is on.
  // http://msdn.microsoft.com/en-us/library/bb204882(VS.85).aspx
  hr = g.gpu-&gt;SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ) ;
  CHECK( hr, "Culling off" ) ;

  #pragma endregion

  #pragma region declare a vertex structure, create verts
  // OK?? WHEW!!  THAT was a lot of work!
  // Now let's DRAW SOMETHING!!  First,
  // we have to create a STRUCT which
  // will match up the vertex declaration
  // we specified above.

  // Practically you'd probably want this struct
  // to be declared in global space, but its declared
  // inline here just to preserve the
  // flow of information for you.

  struct Vertex
  {
    float x,y,z ;
    DWORD color ;

    // Ctor starts you at origin in black
    // with alpha (opacity) set to 100%
    Vertex()
    {
      x=y=z = 0.0f;
      color = D3DCOLOR_XRGB( 0,0,0 ) ;
    }

    // Ctor.
    Vertex( float ix, float iy, float iz,
      unsigned char ir, unsigned char ig, unsigned char ib )
    {
      x=ix;y=iy;z=iz;
      color = D3DCOLOR_XRGB( ir, ig, ib ) ;
    }

    // Ctor that lets you pick alpha
    Vertex( float ix, float iy, float iz,
      unsigned char ir, unsigned char ig, unsigned char ib, unsigned char ALPHA )
    {
      x=ix;y=iy;z=iz;
      color = D3DCOLOR_ARGB( ALPHA, ir, ig, ib ) ;
    }
  } ;

  // Now create an array full of vertices!
  Vertex verts[] = {

    // Red vertex @ ( -1, 0, 0 )
    Vertex( -1, 0, 0, 255, 19, 0 ),

    // Green vertex @ ( 0, 1, 0 )
    Vertex(  0, 1, 0, 0, 255, 0 ),

    // Blue vertex @ ( 1, 0, 0 )
    Vertex(  1, 0, 0, 0, 0, 255 )

  } ;

  float axisLen = 2.0f ;
  Vertex axis[] = {

    // x-axis is red
    Vertex( -axisLen, 0, 0, 255, 0, 0 ),
    Vertex( +axisLen, 0, 0, 255, 0, 0 ),

    // y-axis green
    Vertex( 0, -axisLen, 0, 0, 255, 0 ),
    Vertex( 0, +axisLen, 0, 0, 255, 0 ),

    // z-axis blue
    Vertex( 0, 0, -axisLen, 0, 0, 255 ),
    Vertex( 0, 0, +axisLen, 0, 0, 255 )

  } ;

  #pragma endregion

  #pragma region ACTUALLY __draw__
  // <a href="http://msdn.microsoft.com/en-us/library/bb174350(VS.85).aspx">IDirect3DDevice9::BeginScene()</a>
  // You must call BeginScene() before you start drawing anything.
  hr = g.gpu-&gt;BeginScene() ;
  CHECK( hr, "BeginScene FAILED!" ) ;

  hr = g.gpu-&gt;DrawPrimitiveUP( D3DPT_TRIANGLELIST, 1, verts, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

  hr = g.gpu-&gt;DrawPrimitiveUP( D3DPT_LINELIST, 3, axis, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

  float pointSize = 8.0f ;

  // A DWORD is 4 bytes (a WORD is 2 bytes).
  // So, what we need to do is basically cast
  // pointSize to (DWORD).  Its a bit complicated
  // about how you actually do it, so I made a macro for it.
  // The general idea is you need to "trick" SetRenderState
  // into taking your float value.. SetRenderState "thinks"
  // its a DWORD, while its actually a float.. and D3D
  // internally somehow gets it and knows to treat it as a float.
  // Kind of clunky, eh, but what can you do.
  g.gpu-&gt;SetRenderState( D3DRS_POINTSIZE, CAST_AS_DWORD( pointSize ) ) ;

  // Draw points at end of axis.
  Vertex points[] = {
    Vertex( axisLen, 0, 0, 255, 0, 0 ),
    Vertex( 0, axisLen, 0, 0, 255, 0 ),
    Vertex( 0, 0, axisLen, 0, 0, 255 ),
  } ;
  hr = g.gpu-&gt;DrawPrimitiveUP( D3DPT_POINTLIST, 3, points, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

  // endscene, and present
  // <a href="http://msdn.microsoft.com/en-us/library/bb174375(VS.85).aspx">IDirect3DDevice9::EndScene()</a>
  // You must call EndScene() to signify to the gpu that
  // you are finished drawing.  Must pair up with
  // a BeginScene() call that happened earlier.
  hr = g.gpu-&gt;EndScene() ;
  CHECK( hr, "EndScene FAILED!" ) ;

  // And finally, PRESENT what we drew to the backbuffer
  g.gpu-&gt;Present( 0, 0, 0, 0 ) ;
  #pragma endregion

}

// function that prints some system info.  can ignore this part
// if you are not interested in it.
void printSystemInfo()
{
  UINT numAdapters = g.d3d-&gt;GetAdapterCount() ;
  printf( "\n\n* * * * System information * * * *\n" ) ;
  printf( "Owner name:  Dorky Dorkinson (haha, just kidding, little easter egg there..)\n" ) ;
  printf( "Ok, the rest of this information IS real!\n" ) ;

  printf( "You have %d adapters\n  * (this number is bigger than 1 if you have dualview)\n", numAdapters ) ;

  // Scroll through all adapters and print some info about each
  for( int i = 0 ; i &lt; numAdapters ; i++ )
  {
    printf( &quot;\n\n-- ADAPTER #%d --\n&quot;, i ) ;
    printf( &quot;On monitor #%d\n&quot;, g.d3d-&gt;GetAdapterMonitor( i ) ) ;

    // Object into which display mode info will be saved
    // by GetAdapterDisplayMode
    D3DDISPLAYMODE displayMode ;
    g.d3d-&gt;GetAdapterDisplayMode( i, &amp;displayMode ) ;

    printf( &quot;Has Format=%d Height=%d Width=%d RefreshRate=%d\n&quot;, displayMode.Format, displayMode.Height, displayMode.Width, displayMode.RefreshRate ) ;
    printf( &quot;  * (format refers to the D3DFMT_ pixel mode.. e.g. 22=D3DFMT_X8R8G8B8 which is 24 bit color)\n&quot; ) ;

    D3DADAPTER_IDENTIFIER9 id ; // Will hold info about the adapter
    // after call to GetAdapterIdentifier

    g.d3d-&gt;GetAdapterIdentifier( i, 0, &amp;id ) ;
    // At this point you can see how WEIRD the API gets.
    // All I want is the adapter identifier, and here MSDN
    // says the API offers to &quot;connect to the Internet
    // and download new MS Windows Hardware Quality Labs certificates.&quot;
    // Holy cow.  I don&#39;t want to do THAT.  So leave the flag at 0.

    // There&#39;s PLENTY of info here we don&#39;t care about,
    // but some of it is interesting!!  I&#39;ve printed
    // only the most interesting members, leaving parts
    // like the GUID out.
    printf( &quot;&lt;device driver info&gt;\n&quot; ) ;
    printf( &quot;  Description: %s\n  Device Id: %d\n  Device name: %s\n  Driver: %s\n&quot;,
      id.Description, id.DeviceId, id.DeviceName, id.Driver ) ;
    printf( &quot;&lt;/device driver info&gt;\n&quot; ) ;

    UINT modeCount ;

    // I guess this next part just shows.. how FEW modes are
    // actually supported on a GPU.. I have an NVIDIA 8800GTS,
    // and it only supports 28 modes on D3DFMT_X8R8G8B8,
    // and 28 modes on D3DFMT_R5G6B5.  The rest, 0 modes are
    // reported as supported!

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_R8G8B8 ) ;
    printf( &quot;D3DFMT_R8G8B8   %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_A8R8G8B8 ) ;
    printf( &quot;D3DFMT_A8R8G8B8 %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_X8R8G8B8 ) ;
    printf( &quot;D3DFMT_X8R8G8B8 %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_R5G6B5 ) ;
    printf( &quot;D3DFMT_R5G6B5   %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_X1R5G5B5 ) ;
    printf( &quot;D3DFMT_X1R5G5B5 %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_A1R5G5B5 ) ;
    printf( &quot;D3DFMT_A1R5G5B5 %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_A4R4G4B4 ) ;
    printf( &quot;D3DFMT_A4R4G4B4 %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_R3G3B2 ) ;
    printf( &quot;D3DFMT_R3G3B2   %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_A8 ) ;
    printf( &quot;D3DFMT_A8       %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_A8R3G3B2 ) ;
    printf( &quot;D3DFMT_A8R3G3B2 %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_X4R4G4B4 ) ;
    printf( &quot;D3DFMT_X4R4G4B4 %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_A2B10G10R10 ) ;
    printf( &quot;D3DFMT_A2B10G10R10 %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_A8B8G8R8 ) ;
    printf( &quot;D3DFMT_A8B8G8R8 %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_X8B8G8R8 ) ;
    printf( &quot;D3DFMT_X8B8G8R8 %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_G16R16 ) ;
    printf( &quot;D3DFMT_G16R16   %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_A2R10G10B10 ) ;
    printf( &quot;D3DFMT_A2R10G10B10 %d modes supported\n&quot;, modeCount ) ;

    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_A16B16G16R16 ) ;
    printf( &quot;D3DFMT_A16B16G16R16 %d modes supported\n&quot;, modeCount ) ;

    // This mode is the MOST LIKELY TO be supported on your machine.
    modeCount = g.d3d-&gt;GetAdapterModeCount( i, D3DFMT_X8R8G8B8 ) ;
    for( int j = 0 ; j &lt; modeCount; j++ )
    {
      g.d3d-&gt;EnumAdapterModes( i, D3DFMT_X8R8G8B8, j, &amp;displayMode ) ;

      printf( &quot;For format=%d (D3DFMT_X8R8G8B8) Height=%d Width=%d RefreshRate=%d is SUPPORTED\n&quot;, displayMode.Format, displayMode.Height, displayMode.Width, displayMode.RefreshRate ) ;

    }

    // At this point you&#39;re thinking, &quot;HEY!!  But i&#39;m SURE my gpu supports
    // alpha blending!  Why are all the modes like A8R8G8B8 NOT supported!?&quot;
    // My best stab at this is it makes no sense to DISPLAY something with
    // an alpha component still in it.  For the final image that gets displayed --
    // the alphas should already have been blended -- present day
    // monitors can only display RGB, they don&#39;t have the ability to
    // &quot;go transparent&quot;.  Maybe one day when we work with those enormous
    // glass screens that people work with in the movies -- kinda like this one:
    // http://business.timesonline.co.uk/multimedia/archive/00339/screen-385_339034a.jpg
    // then having an ALPHA component on the display WOULD make sense.  But for
    // now, all monitors are completely opaque, and they only display colors
    // RGB.  So an alpha component makes no sense on the display itself.
    // That&#39;s why displays don&#39;t support that display mode.

    // K, FINALLY we get to the device&#39;s capabilities.
    // I love how DirectX lets you &quot;reflect&quot; on what
    // the hardware is in fact capable of.  Its nice.

    D3DCAPS9 caps ;
    g.d3d-&gt;GetDeviceCaps( i, D3DDEVTYPE_HAL, &amp;caps ) ;

    // Now we have the capabilities of the device.
    // Printing all of them would be meaningless,
    // but if you want to inspect some of them, just
    // use the debugger.

  }
}

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow )
{
  //////////////////
  // First we&#39;ll start by saving a copy of
  // the hInstance parameter inside our
  // &quot;glob&quot; of globals &quot;g&quot;:
  g.win.hInstance = hInstance;
  // In case we need it later, we&#39;ll have it
  // with firsthand easy access.

  #pragma region part 0 - attach a console
  // Attach a console
  AllocConsole();
  AttachConsole( GetCurrentProcessId() ) ;
  freopen( &quot;CON&quot;, &quot;w&quot;, stdout ) ; // redirect stdout to console
  freopen( &quot;CON&quot;, &quot;w&quot;, stderr ) ; // redirect stderr to console

  // Move the console over to the top left
  g.win.hConsole = GetConsoleWindow();
  MoveWindow( g.win.hConsole, 0, 0, 400, 400, true ) ;

  printf( &quot;* * Computer Program Begin * *\n&quot; ) ;
  #pragma endregion

  #pragma region part 1 - create a window
  // The next few lines you should already
  // be used to:  create a WNDCLASSEX
  // that describes the properties of
  // the window we&#39;re going to soon create.
  // A.  Create the WNDCLASSEX
  WNDCLASSEX wcx = { 0 } ;
  wcx.cbSize = sizeof( WNDCLASSEX );
  wcx.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
  wcx.hCursor = LoadCursor( NULL, IDC_ARROW );
  wcx.hIcon = LoadIcon( NULL, IDI_APPLICATION );
  wcx.hInstance = hInstance;
  wcx.lpfnWndProc = WndProc;
  wcx.lpszClassName = TEXT(&quot;Philip&quot;);
  wcx.lpszMenuName = 0;
  wcx.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;

  // Register that class with the Windows O/S..
  RegisterClassEx( &amp;wcx );

  /////////////////
  // Ok, AT THIS POINT, we&#39;d normally
  // just go ahead and call CreateWindow().
  // And we WILL call CreateWindow(), but
  // there is something I must explain to
  // you first.  That thing is the RECT structure.

  /////////////////
  // RECT:
  //
  // A RECT is just a C struct meant to represent
  // a rectangle.
  //
  // The RECT structure WILL DESCRIBE EXACTLY WHERE
  // AND HOW WE WANT OUR WINDOW TO APPEAR WHEN WE
  // CREATE IT.
  //
  //         TOP
  //       --------
  //       |      |
  // LEFT  |      | RIGHT
  //       --------
  //        BOTTOM
  //
  // So, what we do is, we create the RECT
  // struct for our window as follows:
  RECT rect;
  SetRect( &amp;rect, 420,  // left
    25,  // top
    420 + 800, // right
    25  + 600 ); // bottom

  // Save width and height off.
  g.win.width = rect.right - rect.left;
  g.win.height = rect.bottom - rect.top;

  // Adjust it.
  DWORD windowStyle = WS_OVERLAPPEDWINDOW ; // typical features of a normal window
  DWORD windowExStyle = WS_EX_TOPMOST ; // I want the window to be topmost

  AdjustWindowRectEx( &amp;rect, windowStyle, false, windowExStyle );

  // AdjustWindowRect() expands the RECT
  // so that the CLIENT AREA (drawable region)
  // has EXACTLY the dimensions we specify
  // in the incoming RECT.

  // If you didn&#39;t just understand that, understand
  // this:  &quot;you have to call AdjustWindowRect()&quot;,
  // and move on.  Its not THAT important, but its
  // good for the performance of your app.

  ///////////////////
  // NOW we call CreateWindow, using
  // that adjusted RECT structure to
  // specify the width and height of the window.
  g.win.hwnd = CreateWindowEx(
    windowExStyle,
    TEXT(&quot;Philip&quot;),
    TEXT(&quot;TIGER-DIRECT3D WINDOW!&quot;),
    windowStyle,
    rect.left, rect.top,  // adjusted x, y positions
    rect.right - rect.left, rect.bottom - rect.top,  // adjusted width and height
    NULL, NULL,
    hInstance, NULL);

  // check to see that the window
  // was created successfully!
  if( g.win.hwnd == NULL )
  {
    FatalAppExit( NULL, TEXT(&quot;CreateWindow() failed!&quot;) );
  }

  // and show.
  ShowWindow( g.win.hwnd, iCmdShow );
  #pragma endregion

  #pragma region part 2 - initialize direct3d9

  // JUMP to the initD3D() method.
  if( !initD3D() )
  {
    FatalAppExit( 0, TEXT(&quot;SORRY!!!  DEVICE CREATION FAILED!!! YOU LOSE, WITHOUT EVEN PLAYING THE GAME!!!&quot; ) ) ;
  }

  #pragma endregion

  #pragma region message loop
  MSG msg;

  while( 1 )
  {
    if( PeekMessage( &amp;msg, NULL, 0, 0, PM_REMOVE ) )
    {
      if( msg.message == WM_QUIT )
      {
        break;
      }

      TranslateMessage( &amp;msg );
      DispatchMessage( &amp;msg );
    }

    // 3.  DRAW USING Direct3D.
    // This region right here is the
    // heart of our application.  THE MOST
    // execution time is spent just repeating
    // this draw() function.
    draw();

  }
  #pragma endregion

  //////////////
  // clean up
  #pragma region clean up

  // Release COM objects.
  // What&#39;s SAFE_RELEASE()?  Well, lots of people use
  // if( pointer ) pointer-&gt;Release() ; to guard
  // against null pointer exceptions.

  // Like the MS examples do, I&#39;ve defined
  // SAFE_RELEASE at the top of this file and
  // I&#39;m using it here.  All it does is
  // make sure the pointer is not null before releasing it.
  SAFE_RELEASE( g.gpu ) ;
  SAFE_RELEASE( g.d3d ) ;

  #pragma endregion

  // and a cheesy fade exit
  AnimateWindow( g.win.hwnd, 200, AW_HIDE | AW_BLEND );

  printf( &quot;* * This Computer Program Has Ended * *\n&quot; ) ;

  return msg.wParam;
}

////////////////////////
// WNDPROC
// Notice that WndProc is very very neglected.
// We hardly do anything with it!  That&#39;s because
// we do all of our processing in the draw()
// function.
LRESULT CALLBACK WndProc(   HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam )
{
  switch( message )
  {
  case WM_CREATE:
    Beep( 50, 10 );
    return 0;
    break;

  case WM_PAINT:
    {
      HDC hdc;
      PAINTSTRUCT ps;
      hdc = BeginPaint( hwnd, &amp;ps );
      // don&#39;t draw here.  would be waaay too slow.
      // draw in the draw() function instead.
      EndPaint( hwnd, &amp;ps );
    }
    return 0;
    break;

  case WM_KEYDOWN:
    switch( wparam )
    {
    case VK_ESCAPE:
      PostQuitMessage( 0 );
      break;
    default:
      break;
    }
    return 0;

  case WM_SIZE:
    {
      int width = LOWORD( lparam ) ;
      int height = HIWORD( lparam ) ;
      printf( &quot;RESIZED TO width=%d height=%d\n&quot;, width, height ) ;
    }
    break;

  case WM_DESTROY:
    PostQuitMessage( 0 ) ;
    return 0;
    break;
  }

  return DefWindowProc( hwnd, message, wparam, lparam );
}

/*
    ____   __   __      __   __  ___
   / _  \ /  / /  /    /  /  \ \/  /
  / _/ / /  / /  /    /  /    \   /
 / _/ \ /  / /  /__  /  /__   /  /
/_____//__/ /______//______/ /__/

*/
</pre>
</blockquote>
<h3><a href="http://www.esnips.com/nsdoc/964c2fa2-0ff0-48d5-92f4-486a05de9909/?action=forceDL">Code package on esnips</a> (thanks esnips!)</h3>
Posted in C C++, C++, d3d, DirectX Tagged: C++, d3d, tutorial <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bobobobo.wordpress.com/1213/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bobobobo.wordpress.com/1213/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bobobobo.wordpress.com/1213/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bobobobo.wordpress.com/1213/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bobobobo.wordpress.com/1213/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bobobobo.wordpress.com/1213/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bobobobo.wordpress.com/1213/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bobobobo.wordpress.com/1213/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bobobobo.wordpress.com/1213/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bobobobo.wordpress.com/1213/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1213&subd=bobobobo&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://bobobobo.wordpress.com/2009/07/03/getting-started-with-direct3d-in-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a4ec51727310397c9e592dd84ae74dc2?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">bobobobo</media:title>
		</media:content>

		<media:content url="http://bobobobo.files.wordpress.com/2009/04/mesh_instancing_j.jpg" medium="image" />
	</item>
		<item>
		<title>visual studio 2008 mfc projects &#8211; gorgeous ribbon style</title>
		<link>http://bobobobo.wordpress.com/2009/06/04/visual-studio-2008-mfc-projects-gorgeous-ribbon-style/</link>
		<comments>http://bobobobo.wordpress.com/2009/06/04/visual-studio-2008-mfc-projects-gorgeous-ribbon-style/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 22:06:05 +0000</pubDate>
		<dc:creator>bobobobo</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://bobobobo.wordpress.com/?p=1067</guid>
		<description><![CDATA[I didnt&#8217; know this but Visual Studio 2008 has a GORGEOUS ribbon style that you can select when building an MFC app.  Fully explore the project creation wizard when you build an MFC app, its worth it!

This was jaw-dropping, for me.
Posted in C++       <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1067&subd=bobobobo&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I didnt&#8217; know this but Visual Studio 2008 has a GORGEOUS ribbon style that you can select when building an MFC app.  Fully explore the project creation wizard when you build an MFC app, its worth it!</p>
<p><img src="http://bobobobo.files.wordpress.com/2009/06/gorgeous_ribbon_style.png" /></p>
<p>This was jaw-dropping, for me.</p>
Posted in C++  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bobobobo.wordpress.com/1067/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bobobobo.wordpress.com/1067/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bobobobo.wordpress.com/1067/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bobobobo.wordpress.com/1067/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bobobobo.wordpress.com/1067/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bobobobo.wordpress.com/1067/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bobobobo.wordpress.com/1067/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bobobobo.wordpress.com/1067/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bobobobo.wordpress.com/1067/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bobobobo.wordpress.com/1067/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1067&subd=bobobobo&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://bobobobo.wordpress.com/2009/06/04/visual-studio-2008-mfc-projects-gorgeous-ribbon-style/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a4ec51727310397c9e592dd84ae74dc2?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">bobobobo</media:title>
		</media:content>

		<media:content url="http://bobobobo.files.wordpress.com/2009/06/gorgeous_ribbon_style.png" medium="image" />
	</item>
		<item>
		<title>Understanding EXTERN variables in C++</title>
		<link>http://bobobobo.wordpress.com/2009/06/04/understanding-extern-variables-in-c/</link>
		<comments>http://bobobobo.wordpress.com/2009/06/04/understanding-extern-variables-in-c/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 17:03:20 +0000</pubDate>
		<dc:creator>bobobobo</dc:creator>
				<category><![CDATA[C C++]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[extern]]></category>

		<guid isPermaLink="false">http://bobobobo.wordpress.com/?p=1064</guid>
		<description><![CDATA[Understanding how to use extern variables in C/C++
Start with a visual studio project.
create 5 files, and copy/paste the contents as show below in them.
Alternatively, esnips code package! (thanks esnips!)
externVarDeclaration.h


#ifndef EXTERN_VAR_DECL_H
#define EXTERN_VAR_DECL_H

extern int i ;  // This is like a "function prototype", only
// for variables.

// The extern declaration says, "this variable doesn't exist yet,
// but [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1064&subd=bobobobo&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h1>Understanding how to use extern variables in C/C++</h1>
<p>Start with a visual studio project.</p>
<p>create 5 files, and copy/paste the contents as show below in them.</p>
<p>Alternatively, <a href="http://www.esnips.com/doc/bbabc651-4f29-489e-b1fd-45b3f941c550/Extern">esnips code package!</a> (thanks esnips!)</p>
<h2>externVarDeclaration.h</h2>
<blockquote>
<pre>
#ifndef EXTERN_VAR_DECL_H
#define EXTERN_VAR_DECL_H

extern int i ;  // This is like a "function prototype", only
// for variables.

// The extern declaration says, "this variable doesn't exist yet,
// but it WILL exist, and its value is going to be defined
// in another file that will be part of this project when it compiles."
// (see externVarDefinition.cpp)

// So, using an EXTERN is how you share a single global variable
// ACROSS MULTIPLE FILES.
// Call it a SUPERGLOBAL.  TO understand this, think about
// functions and function prototypes.

// Defining a global function, you kind of expect it to have
// "superglobal" status..
// like, if you define a function somewhere, you should be
// able to break it apart into some prototypes and #include
// those prototypes in ANY FILE that you want
// to use those functions.  Right?

// So, the reason you have prototypes is so that multiple
// files can #include the same prototypes (function
// DECLARATIONS) then the actual code for the
// DEFINITION of the functions is in one place,
// a .cpp file (like "function_set.cpp").  This way you don't
// have multiple re-definitions of the functions declared in
// function_set.h, but you may have multiple re-declarations
// (the compiler might see the same prototype several times
// in a row, which is fine, as long as it sees the BODY
// definition only once.)

// So, an extern'd variable is a lot like that.
// You basically treat it like a function prototype, where the

///// extern int i ;

// part is the DECLARATION (like a function prototype),
// and the part in externVarDefinition.cpp:

// int i = 500 ;

// is like the DEFINITION, or function body.

// C++ can only come across the DEFINITION (value giving part) __ONCE__ for any
// given variable.

// So with externs, you can #include the "extern variable declaration" into as
// many files as you like (just like you can #include the function prototypes
// into as many different files as you wish), so long as
// the "DEFINITION" (the int i = 500 part) only occurs once, in one file.

// If you uncomment this line below, you will see
// its ILLEGAL.

//////////int j = 50 ; ////ILLEGAL

// Surprised?  Well, very illegal!

// Reason:  EVEN WITH the #ifndef #include guards
// on this file.. because this "externVarDeclaration.h" file is
// #included in more than one other file, for some reason the C++
// LINKER (__NOT__ the compiler) will flag it as an error:

// "int j" already defined in main.obj.

// One day I'd like to be able to fully understand why this is
// myself, but for now, "EXTERN solves this problem".

#endif //EXTERN_VAR_DECL_H
</pre>
</blockquote>
<h2>function_set.h</h2>
<blockquote>
<pre>
#ifndef FUNCTION_SET_H
#define FUNCTION_SET_H

#include &lt;stdio.h&gt;
#include "externVarDeclaration.h"

void print() ;
void print2() ;
void print3() ;
void changeI() ;

#endif //FUNCTION_SET_H
</pre>
</blockquote>
<h2>externVarDefinition.cpp</h2>
<blockquote>
<pre>
#include "externVarDeclaration.h"

int i = 500 ;

// HERE we define the VALUE of the extern'd variable i.
</pre>
</blockquote>
<h2>function_set.cpp</h2>
<blockquote>
<pre>
#include "function_set.h"

void print()
{
  printf("func1 %d\n", i);
}

void print2()
{
  printf("func2 %d\n", i);
}

void print3()
{
  printf("func3 %d\n", i);
}

void changeI()
{
  // i is shared across the whole project
  i = 2000402;
}
</pre>
</blockquote>
<h2>main.cpp</h2>
<blockquote>
<pre>
#include &lt;stdio.h&gt;

#include "externVarDeclaration.h"
#include "function_set.h"

int main()
{
  printf( "The extern'd var is %d\n", i ) ;

  i = 20 ;
  print();

  i = 333 ;
  print2();

  changeI();

  printf("My oh my!  the extern'd var has changed to %d\n", i ) ;
}
</pre>
</blockquote>
Posted in C C++, C++ Tagged: C++, extern <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bobobobo.wordpress.com/1064/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bobobobo.wordpress.com/1064/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bobobobo.wordpress.com/1064/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bobobobo.wordpress.com/1064/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bobobobo.wordpress.com/1064/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bobobobo.wordpress.com/1064/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bobobobo.wordpress.com/1064/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bobobobo.wordpress.com/1064/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bobobobo.wordpress.com/1064/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bobobobo.wordpress.com/1064/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1064&subd=bobobobo&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://bobobobo.wordpress.com/2009/06/04/understanding-extern-variables-in-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a4ec51727310397c9e592dd84ae74dc2?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">bobobobo</media:title>
		</media:content>
	</item>
		<item>
		<title>THERE IS A C# IS keyword equivalent in C++</title>
		<link>http://bobobobo.wordpress.com/2009/06/01/there-is-a-c-is-keyword-equivalent-in-c/</link>
		<comments>http://bobobobo.wordpress.com/2009/06/01/there-is-a-c-is-keyword-equivalent-in-c/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 17:06:25 +0000</pubDate>
		<dc:creator>bobobobo</dc:creator>
				<category><![CDATA[C C++]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://bobobobo.wordpress.com/?p=1037</guid>
		<description><![CDATA[IS THERE an IS keyword in C++ like in C#?
YES, there is an IS keyword in C++.  Just like in C#.
WRONG
WRONG
A few days ago I had this question and I saw this answer &#8220;NO&#8221; and I took it and accepted it.
Only today I saw in some sample code just use of typeid().  And [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1037&subd=bobobobo&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h1>IS THERE an IS keyword in C++ like in C#?</h1>
<p>YES, there is an IS keyword in C++.  Just like in C#.</p>
<p><a href="http://bytes.com/groups/net-vc/617475-there-keyword-c#">WRONG</a><br />
<a href="http://forums.whirlpool.net.au/forum-replies-archive.cfm/980264.html">WRONG</a></p>
<p>A few days ago I had this question and I saw this answer &#8220;NO&#8221; and I took it and accepted it.</p>
<p>Only today I saw in some sample code just use of typeid().  And guess what?  typeid() turns BLUE in the IDE!</p>
<blockquote>
<pre>

#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

class Entity
{
public:
  int hp ;
};

class Grunt : public Entity
{
public:
  string name ;
};

int main()
{
  Grunt grom ;
  grom.hp = 500 ;
  grom.name = "GROM HELLSCREAM!" ;

  const type_info * typeOfG = &amp;typeid( grom ) ;

  cout &lt;&lt; typeOfG-&gt;name() &lt;&lt; endl;

  Entity wisp ;
  wisp.hp = 120 ;

  const type_info * typeOfWisp = &amp;typeid( wisp ) ;

  cout &lt;&lt; typeOfWisp-&gt;name() &lt;&lt; endl; 

  // equivalent of C# is:
  //if( grom is Grunt )
  //{
  //}

  // accomplished by
  string classGrunt = "class Grunt" ;
  if( typeid(grom).name() == classGrunt )
  {
    cout &lt;&lt; "Grom is a grunt" &lt;&lt; endl;
  }
  else
  {
    cout &lt;&lt; "Grom is NOT a grunt" &lt;&lt; endl;
  }

  // so we coudl make this a bit more elegant by
#define is( obj, type ) typeid(obj).name()==type
  if( is( grom, classGrunt ) )
  {
    cout &lt;&lt; "Grom is a grunt" &lt;&lt; endl;
  }
  else
  {
    cout &lt;&lt; "Grom is NOT a grunt" &lt;&lt; endl;
  }

  /*
  class type_info {
    bool operator==( type_info rhs ) ;
    bool operator!=( type_info rhs ) ;
    int before( type_info rhs ) ;
    const char* name();
    const char* raw_name();
  } ;
  */

}
</pre>
</blockquote>
Posted in C C++, C++  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bobobobo.wordpress.com/1037/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bobobobo.wordpress.com/1037/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bobobobo.wordpress.com/1037/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bobobobo.wordpress.com/1037/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bobobobo.wordpress.com/1037/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bobobobo.wordpress.com/1037/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bobobobo.wordpress.com/1037/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bobobobo.wordpress.com/1037/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bobobobo.wordpress.com/1037/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bobobobo.wordpress.com/1037/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1037&subd=bobobobo&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://bobobobo.wordpress.com/2009/06/01/there-is-a-c-is-keyword-equivalent-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a4ec51727310397c9e592dd84ae74dc2?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">bobobobo</media:title>
		</media:content>
	</item>
		<item>
		<title>always using methods, and not using public members</title>
		<link>http://bobobobo.wordpress.com/2009/05/31/always-using-methods-and-not-using-public-members/</link>
		<comments>http://bobobobo.wordpress.com/2009/05/31/always-using-methods-and-not-using-public-members/#comments</comments>
		<pubDate>Sun, 31 May 2009 21:54:15 +0000</pubDate>
		<dc:creator>bobobobo</dc:creator>
				<category><![CDATA[C C++]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[encapsulation]]></category>

		<guid isPermaLink="false">http://bobobobo.wordpress.com/?p=1034</guid>
		<description><![CDATA[I&#8217;m one of those programmers who HATES it when he sees things like:



public class Grunt
{
  private int m_hp ;

  public int HP
  {
    get
    {
      return m_hp ;
    }
    set
    {
  [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1034&subd=bobobobo&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I&#8217;m one of those programmers who HATES it when he sees things like:</p>
<blockquote>
<pre>

public class Grunt
{
  private int m_hp ;

  public int HP
  {
    get
    {
      return m_hp ;
    }
    set
    {
      m_hp = value ;
    }
  }
}
</pre>
</blockquote>
<p>Encapsulation or no encapsulation, this just SEEMS dumb.</p>
<p>Sometimes you&#8217;ll see this written as:</p>
<blockquote>
<pre>

public class Grunt
{
  private int m_hp ;

  public int HP
  {
    get { return m_hp ; }
    set { m_hp = value ; }
  }
}
</pre>
</blockquote>
<p>Which further proves my point:  You can compress code like that when its not meant to be looked at.</p>
<p>The point is, THERE IS NO POINT in having pass-thru getters/setters like this.</p>
<p>In languages other than C#, you&#8217;ll see people using functions of course instead of C# properties.</p>
<blockquote>
<pre>

class Grunt
{
private:
  int m_hp ;

public:
  void ChangeHp( int toVal )
  {
    m_hp = toVal ;
  }

  int Hp()
  {
    return m_hp ;
  }
} ;
</pre>
</blockquote>
<p>VERSUS:</p>
<blockquote>
<pre>

class Grunt
{
public:
  int hp ;
} ;
</pre>
</blockquote>
<p>Isn&#8217;t there a very slight performance hit for writing code that always uses methods?  Yes.  ++points for public members.</p>
<p>HOWEVER.  Recently I have thought of ONE major benefit to this &#8220;methods only/no public members&#8221; style that I never really credited to the style before.</p>
<p>Readability.</p>
<p>Think of client code using the Grunt class:</p>
<blockquote>
<pre>

Grunt g ;

if( g.Hp() &gt; 10 )
{
  g.ChangeHp( 12 ) ;
}
</pre>
</blockquote>
<p>VERSUS:</p>
<blockquote>
<pre>

Grunt g ;

if( g.hp &gt; 10 )
{
  g.hp = 12 ;
}
</pre>
</blockquote>
<p>What reads better?  g.ChangeHp( 12 ) or g.hp = 12?</p>
<p>Really, g.hp = 12 ; LOOKS more cryptic because even though you know what its doing if you think about it for a fraction of a second, (changing hp to 12), for the method way g.ChangeHp(12) you CANNOT READ IT without knowing exactly what it does like, even faster than the one with the =.</p>
<p>SO.  Maybe all private members and all accessor methods aren&#8217;t such a bad idea after all.</p>
Posted in C C++, C++ Tagged: C++, encapsulation <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bobobobo.wordpress.com/1034/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bobobobo.wordpress.com/1034/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bobobobo.wordpress.com/1034/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bobobobo.wordpress.com/1034/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bobobobo.wordpress.com/1034/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bobobobo.wordpress.com/1034/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bobobobo.wordpress.com/1034/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bobobobo.wordpress.com/1034/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bobobobo.wordpress.com/1034/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bobobobo.wordpress.com/1034/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=1034&subd=bobobobo&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://bobobobo.wordpress.com/2009/05/31/always-using-methods-and-not-using-public-members/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a4ec51727310397c9e592dd84ae74dc2?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">bobobobo</media:title>
		</media:content>
	</item>
		<item>
		<title>Getting started with MySQL in C++</title>
		<link>http://bobobobo.wordpress.com/2009/04/05/getting-started-with-mysql-in-c/</link>
		<comments>http://bobobobo.wordpress.com/2009/04/05/getting-started-with-mysql-in-c/#comments</comments>
		<pubDate>Sun, 05 Apr 2009 21:49:14 +0000</pubDate>
		<dc:creator>bobobobo</dc:creator>
				<category><![CDATA[C C++]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://bobobobo.wordpress.com/?p=840</guid>
		<description><![CDATA[

/////
// Connects to MySQL database server from
// C or C++ program.
/////

/////////////////////////////////////////////
//                                         //
// Connecting C++ Win32 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=840&subd=bobobobo&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><blockquote>
<pre>
/////
// Connects to MySQL database server from
// C or C++ program.
/////

/////////////////////////////////////////////
//                                         //
// Connecting C++ Win32 App To MySQL       //
//                                         //
// You found this at bobobobo's weblog,    //
// http://bobobobo.wordpress.com           //
//                                         //
// Creation date:  Apr 5/09                //
// Last modified:  Apr 5/09                //
//                                         //
/////////////////////////////////////////////

// !! Note!  I've included copies of the MySQL
// include headers and library files.. I've done this
// so that the project will compile and run
// more easily for you, but this DOES NOT mean
// that you should skip the SETUP-Y stuff section
// below!

// If you want MySQL to work easily for you in new
// projects, you really should set up Visual Studio
// as explained below.

#pragma region all the setup-y stuff
/////////
// MAKINET WORK: (any prince of persia 2 the shadow and the flame fans out there?)
//
// 1)  First, you OBVIOUSLY must install MySQL.
//     Be sure to download the 32-BIT VERSION (NOT THE x64)
//     of MySQL 5.1 - "Windows MSI Installer"
//     Located at http://dev.mysql.com/downloads/mysql/5.1.html#win32
//     DO NOT GET THE "WINDOWS ESSENTIALS" PACKAGE
//     DO NOT GET __ANY__ x64 crap EVEN IF you are on
//     windows 64 bit, ALWAYS use the NORMAL (non-64 bit)
//     stuff (see Ancient Dragon's comments for why:
//     http://www.programmingforums.org/thread16958.html)

//     Done that?  GOOD!!  Onto step 2.

// 2)  ENSURE THAT mysql.h is in your VISUAL STUDIO
//     PROJECT PATH SETTINGS.  If you don't do this,
//     then you'll may an error of the form of:

// Error	1	fatal error C1083: Cannot open include file: 'mysql.h':
//          No such file or directory

// For me, mysql.h is in :
// C:\Program Files\MySQL\MySQL Server 5.1\include

// But you have to tell VISUAL STUDIO THAT!!  IT doesn't know.

// Need to edit Visual Studio INCLUDE Directory settings.  here's how.

// SO I, click
//   1  TOOLS -&gt; OPTIONS
//   2  PROJECTS AND SOLUTIONS -&gt; VC++ DIRECTORIES (left hand panel)

//   3  (now in right hand panel),
//    from the two dropdowns there
//      (hanging like two microsoft eyes..), uh,

//   4  you just make sure under PLATFORM,
//      it says Win32,

//   5  and under SHOW DIRECTORIES FOR,
//      it says INCLUDE FILES.

//   6  THEN, click the SHINY YELLOW FOLDER,
//      and then click the '...'
//   7  and navigate to your MySQL INSTALL DIR\INCLUDE
//      add that folder there.

//    For me, I end up with an extra entry in that list that says:

//       C:\Program Files\MySQL\MySQL Server 5.1\include

//    yours may be slightly different, but not too different,
//    hey, don't try and be cool here by being REALLY different please.
//   

// OK?  So now the #include below should work for you.
// If it doesn't, INSTALL MYSQL FIRST!

// YOU MUST #INCLUDE WINDOWS.H FIRST IF YOU WANT MYSQL
// TO WORK ON WINDOWS!!
#include &lt;windows.h&gt;
#include &lt;stdio.h&gt;

// To get autocomplete to work, you may have to right-click
// your Header Files -&gt; Add Existing Item... and pick
// mysql.h and add it to your project.  I've copy and pasted
// the file into this project, though.

// !!
// You may only use the form below if you have followed the
// installation instructions above.
/////#include &lt;mysql.h&gt;

#include "mysql_include/mysql.h"  // use this form if you haven't "installed"
// MySQL header files into visual studio as explained above.

// You must also add C:\Program Files\MySQL\MySQL Server 5.1\lib\debug
// to your Visual Studio LIBRARY directory settings (follow steps above again, except
// at step 5, you choose "SHOW DIRECTORIES FOR -&gt; LIBRARY FILES"
// and at step 7, you add C:\Program Files\MySQL\MySQL Server 5.1\lib\debug
// (or whatever yours really is)

// !!
// You may only use the form below if you have followed the
// installation instructions above.
/////#pragma comment( lib, "libmysql.lib" )

#pragma comment( lib, "mysql_lib/debug/libmysql.lib" )  // use this form if you haven't "installed"
// MySQL header files into visual studio as explained above.

// libmysql.lib is what is termed an "import library" - basically
// it is what wires up function calls in this program to MYSQL
// functionality to the libmysql.dll file.

// So what about libmysql.dll?

// FINALLY, ENSURE TO COPY libmysql.dll to EITHER:  the \Debug folder
// of this project (WHERE THE FINAL .EXE RESIDES), __OR__, to
// C:\WINDOWS\System32 (if that doesn't work, then copy it to C:\WINDOWS\System).

// For me, libmysql.dll lives in
// C:\Program Files\MySQL\MySQL Server 5.1\lib\debug
// Its also included in the mysql_lib/debug folder of
// this project.

// To quote Charlie Charlie Petzold, Programming windows 5th ed:
// You can put a DLL file:

// A dynamic library must be present on the disk
// when a program is run that uses the library.
// When Windows needs to load a DLL module before running
// a program that requires it, the librar must be stored:
//   1.  In the directory containing the .exe program
//   2.  the current directory
//   3.  the Windows system directory
//   4.  the windows directory
//   5.  or a directory accessibel through the PATH string in the MS-DOC environment

// The directories are searched in the above order.

#pragma endregion

#pragma region CODING WITH MYSQL

////
// Globals
MYSQL mysql;    // the MYSQL global object.  Passed to mysql_init,
                // and there's only one of this.

MYSQL * conn ;  // represents connection to database
//
////

int main()
{
  // OK!!  Now that you've got all the setup-y stuff out of the way, its
  // time to connect to MySQL!!

  // here are some great references:
  // 1)  http://c-programming.suite101.com/article.cfm/using_a_mysql_databases_with_c
  // 2)  http://dev.mysql.com/doc/refman/5.1/en/windows-client-compiling.html
  mysql_init( &amp;mysql ) ;

  // PLEASE SEE DOCS PAGE FOR MORE DETAILS
  // ABOUT mysql_real_connect():
  //   http://dev.mysql.com/doc/refman/5.0/en/mysql-real-connect.html
  conn = mysql_real_connect(  &amp;mysql,
                              "localhost",// synonymous with 127.0.0.1
                              "root",     // connect as user="root".  Uh, bad security here..
                              "",         // my root password is blank.  REALLY bad security :)
                              "mysql",    // connect to the 'mysql' _database_ within MySQL itself.
                                          // if you create another database, then you can
                                          // specify you'd like to connect to that one here.

                              0,          // port.  Mine is on 3306, but you can leave it as 0
                                          // and it seems to work automatically.

                              0,          // unix_socket (not in use)

                              0 ) ;       // client flag:  usually 0, unless you want special features (see docs page)

  // At this point you may be wondering, ok,
  // so if this is real_connect, what's fake_connect?
  // There is a mysql_connect() function!  Which is
  // basically the "fake" connect... see docs, but
  // the "fake" functions (mysql_query(), mysql_connect()),
  // are like watered down version of their _real_ counterparts.
  // Sometimes useful, sometimes not.  Again, see docs pages.

  // Check if connection succeeded.
  if( conn == NULL )
  {
    printf("Couldn't connect to MySQL database server!\n");
    printf("Error: %s\n", mysql_error( &amp;mysql ) ) ;
    return 1 ;
  }
  else
  {
    printf("Connect success\n") ;
  }

  #pragma region running an actual query
  // Here, we are connected.
  // form a sql string to execute.

  char * query = "select * from user" ;
  int queryState;

  queryState = mysql_query( conn, query ) ;

  if( queryState != 0 )
  {
    printf("Whoops!  The query failed.  Error:  %s\n", mysql_error( conn ) );
    return 1 ;
  }

  // here, query succeeded, so we can proceed
  // to pull out results.
  MYSQL_RES * resultset ;
  MYSQL_ROW row;  // MYSQL_ROW is #defined as (char **)
  // Data ALWAYS comes back from MySQL as
  // an array of strings.  To convert it
  // to ints or whatever is YOUR JOB as the programmer.

  // mysql_store_result basically fetches
  // the entire array of results and dumps them
  // into our local program memory space (all
  // in the resultset variable.
  resultset = mysql_store_result( conn );

  // How many rows will there be?
  int numRows = mysql_num_rows( resultset ) ;
  printf( "There are %d ROWS (records) of data\n", numRows ) ;

  // Now tell me what columns there are
  // in the result set.
  int numFields = mysql_num_fields( resultset ) ;
  printf( "There are %d FIELDS (columns) of data\n", numFields ) ;

  // Print all those column by name
  MYSQL_FIELD * fields = mysql_fetch_fields( resultset ) ;
  for( int i = 0 ; i &lt; numFields ; i++ )
  {
    printf( "%25s", fields[i].name ) ;
  }

  printf( "\n" ) ;
  // print all results
  while( row = mysql_fetch_row( resultset ) )
  {
    // row is 2d array of char
    // underlying type is char **
    for ( int i = 0; i &lt; numFields ; i++ )
    {
      printf( "%25s", row[ i ] ) ;
    }

    // next row
    printf( "\n" ) ;
  }

  #pragma endregion

  // Now free the result
  mysql_free_result( resultset );

  // And close down.
  mysql_close( conn ) ;
  return 0;
}

#pragma endregion // CODING WITH MYSQL

// Your hands quiver with power.

// You are now a MySQL GURU.

// For the record, there's also:
// Connector C++:  http://forge.mysql.com/wiki/Connector_C%2B%2B
// MySQL++:  http://tangentsoft.net/mysql++/

// I chose not to use either library because.. well, I dislike
// additional layers.

// TROUBLESHOOTING:
//
// "This application has failed to start because LIBMYSQL.dll
// was not found.  Re-installing the application may fix this problem."

// So, like internet superhero says, you have 3 options:
// [ http://blog.ulf-wendel.de/?p=215 ]
// 1.  Copy LIBMYSQL.dll into you Windows system directory (C:\Windows\system and/or C:\windows\system32, whichever spins your wheels)
// 2.  You copy LIBMYSQL.dll into the current working directory
// 3.  You add the location of the LIBMYSQL.dll to your path setting, for example using SET PATH=%PATH%;C:\path\to\LIBMYSQL.dll

// LIBMYSQL.dll is somewhere in your MYSQL INSTALLATION directory..
// so find it, and copy LIBYMSQL.dll to C:\Windows\System32 and/or C:\Windows\System
// OR copy it to the \Debug directory for this project (where the final .exe resides)

// Final note:  static lib compiling.
//#pragma comment( lib, "mysqlclient.lib" )   // doesn't work.. produces 76 errors of the form
// Error	1	error LNK2005: __aligned_malloc already defined in MSVCRTD.lib(MSVCR90D.dll)	       (from file LIBCMTD.lib)
//
// root of problem seems to be in the warning:
//  Warning 44 warning LNK4098: defaultlib 'MSVCRTD' conflicts with use of other libs; use /NODEFAULTLIB:library

// Problem docs:
//     http://curl.haxx.se/mail/lib-2006-04/0101.html
//     http://www.codeguru.com/forum/archive/index.php/t-375084.html

// MikeAThon, at the bottom of the second post there, says
// LIBCMT is the static C-runtime library (and is multi-threaded),
// whereas MSVCRTD is the dynamic linking C-runtime. See
// "How to link with the correct C Run-Time (CRT) library" at
// http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q140584&amp; .
// According to that KB article, "the linker will issue a warning
// (LNK4098) if a resulting module attempts to combine more than
// one copy of the CRT library"

// So go into linker -&gt; input -&gt; ignore all default libraries (/NODEFAULTLIB)
// See Internet Superhero again for more help http://blog.ulf-wendel.de/?p=215
</pre>
</blockquote>
<h3>Download <a href="http://www.esnips.com/nsdoc/1dbc4f8a-7ca5-42a9-881f-8bd2abdc7ee3/?action=forceDL">Visual Studio 2008 project files on esnips</a> (thanks esnips!)</h3>
Posted in C C++, C++, mysql, programming, sql  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bobobobo.wordpress.com/840/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bobobobo.wordpress.com/840/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bobobobo.wordpress.com/840/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bobobobo.wordpress.com/840/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bobobobo.wordpress.com/840/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bobobobo.wordpress.com/840/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bobobobo.wordpress.com/840/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bobobobo.wordpress.com/840/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bobobobo.wordpress.com/840/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bobobobo.wordpress.com/840/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bobobobo.wordpress.com&blog=2331964&post=840&subd=bobobobo&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://bobobobo.wordpress.com/2009/04/05/getting-started-with-mysql-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a4ec51727310397c9e592dd84ae74dc2?s=96&#38;d=http%3A%2F%2Fa.wordpress.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">bobobobo</media:title>
		</media:content>
	</item>
	</channel>
</rss>