智能指针
此示例演示了如何使用 -smartptr
模式编译器选项生成简单数据库Parts的 C++ 接口。
示例路径:\native\core\20-languages\cpp_smartptr
该项目的 makefile 或 Visual Studio 中的自定义构建步骤展示了在 mcocomp 命令行中使用 -hpp 选项的方法:
\host\bin\mcocomp.exe -hpp -smartptr schema.mco
模式编译器将生成文件 cppdemo.hpp
,其中包含类 Part、MyPart 以及索引类 ByCode 和 ByType 的实现。
运行
有关如何在您的开发平台上构建此示例及其他示例的说明,请参阅目标平台构建指南。
构建完成后,可以从 \target\bin
目录运行该示例:
20_languages_cpp_smartptr
相关代码
该模式如下所示,其中包含为利用在 cppdemo.hpp
中实现的生成类接口而编写的应用程序代码片段。请注意函数 populate_db()
中的代码与示例 20_languages\cpp 中的代码之间的差异。
/* 模式定义代码片段 */
struct Dimensions
{
float width, length, height;
};
class Part
{
string type;
string name;
float price;
unsigned<4> code;
Dimensions dim;
hash< code > ByCode [ 10000 ];
tree< type, name > ByType; // ordered by type, name
};
/* 应用程序代码片段 */
class MyPart: public Part
{
public:
MCO_RET stype_put(const char* s)
{
return type_put(s, (uint2)strlen(s) + 1);
}
MCO_RET sname_put(const char* s)
{
return name_put(s, (uint2)strlen(s) + 1);
}
void print(mco_trans_h t);
const char* name()
{
static char bf[200];
uint2 len;
name_get(bf, sizeof(bf), len);
bf[len] = 0;
return bf;
}
const char* type()
{
static char bf[200];
uint2 len;
type_get(bf, sizeof(bf), len);
bf[len] = 0;
return bf;
}
};
void MyPart::print(mco_trans_h t)
{
if (!is_valid())
{
return ;
}
uint4 code;
code_get(code);
printf("\n[%d] %s : %s\n", code, name(), type());
Dimensions dim;
dim_read(dim);
float w, h, l;
dim.width_get(w);
dim.length_get(l);
dim.height_get(h);
printf("%g x %g x %g \n", l, w, h);
}
...
MCO_RET populate_db(mco_db_h db)
{
mco_trans_h t = 0;
MCO_RET rc = MCO_S_OK;
int j;
for (j = 0; j < 1000 && MCO_S_OK == rc; j++)
{
MyPart part;
Dimensions dim;
char temp[200];
rc = mco_trans_start(db, MCO_READ_WRITE, MCO_TRANS_FOREGROUND, &t);
if ( MCO_S_OK == rc )
{
part.create(t);
part.stype_put(i2s(j % 100));
sprintf(temp, "part # %d", j);
part.name = (const char *)temp;
part.price = (float)(2.0 + j % 100 / 200.0);
part.code = 1000000+j;
part.dim_write(dim);
dim.height = (float)rand2(20, 40);
dim.width = (float)rand2(20, 50);
dim.length = (float)rand2(35, 90);
std::vector<uint4> options_arr(Part_options_length);
for (i = 0; i < Part_options_length; i++)
{
options_arr[i] = rand2(0, 30);
}
part.options = options_arr;
}
}
printf("Inserted %d parts to the database\n", j);
return rc;
}