A Closer Look at the HnxGC 'HelloWorld'
Now that you've seen the HnxGC 'HelloWorld' (and perhaps even compiled and run it), you might be wondering how it works. Here again is its code:
#include <stdio.h>
#include <string.h>
#include "hnxGC/hnxGC.h"
using namespace harnix;
class CPerson {
public:
char m_sName[20];
char m_sAdress[200];
CPerson(char * name);
~CPerson();
HNXGC_ENABLE(CPerson)
};
CPerson::CPerson(char * name) {
strcpy(m_sName, name);
printf("Hello, %s\n", name);
}
CPerson::~CPerson() {
printf("Goodbye, %s\n", m_sName);
}
int main() {
lp<CPerson> p = gcnew CPerson("John");
return 0;
}
The HnxGC 'HelloWorld' application consists of three primary components: Create HnxGC managed object, Upgrade C++ class to HnxGC class, Upgrade C++ pointer to HnxGC pointer. The following explanation will provide you with a basic understanding of the code, but the deeper implications will only become apparent after you've finished reading the HnxGC Programing Guide.
Create HnxGC managed object
HnxGC managed objects are those which were allocated via HnxGC macro HNXGC_NEW (the alternate macro is gcnew) or HNXGC_NEW_NATIVE (the alternate macro is gcnew_native).
You never have to worry about destroying C++ objects if they are upgraded to HnxGC objects.
The following bold text create an HnxGC managed object:
int main() {
lp<CPerson> p = gcnew CPerson("John");
return 0;
}
Upgrade C++ class to HnxGC class
An C++ class is an encapsulation of data members and functions that manipulate the data. C++ uses the manual approach for managing dynamic memory. After upgrading an C++ class to HnxGC class, you can create an HnxGC managed object that HnxGC will manage its lifetime automatically.
The following bold text upgrade C++ class to HnxGC class:
class CPerson {
public:
char m_sName[20];
char m_sAdress[200];
CPerson(char * name);
~CPerson();
HNXGC_ENABLE(CPerson)
};
There are 2 ways to upgrade: Enable Way and Traverse Way. They will be described in the next article:HnxGC Programming Guide.
Upgrade C++ pointer to HnxGC pointer
If an C++ Class has upgraded to an HnxGC class, and you create a HnxGC managed object of such HnxGC class, Now, you need an HnxGC pointer to access it. If you use C++ pointer, not HnxGC pointer, HnxGC will consider the managed object is not-referenced and collect it as garbage, that maybe not what you want. That's why upgrading C++ pointer to HnxGC pointer is so important.
The following bold text upgrade C++ pointer to HnxGC pointer and create an HnxGC managed object:
int main() {
lp<CPerson> p = gcnew CPerson("John");
return 0;
}
There are 3 types of HnxGC pointer CLockedPtr (the alternate word is lp), CMemberPtr (the alternate word is mp), and CWeakPtr (the alternate word is wp). They will be described in the next article:HnxGC programming guide.
Prev: Hello World
Next: HnxGC Programing Guide