Hello,
This is an extension of this thread: http://www.daniweb.com/software-development/c/threads/357681/1525001#post1525001
My purpose is to create a class that handles a network message. Irrelevant, anyway.
CMyMessage:
#include "stdafx.h"
#pragma once
#include <conio.h>
#include <stdio.h>
#include <iostream>
#pragma once
using namespace std;
typedef unsigned char byte;
class CMyMessage {
protected:
byte type;
byte textlen;
byte namelen;
char *text;
char *name;
public:
CMyMessage(byte* message)
{
}
CMyMessage(byte Type, char *Name, byte Namelen, char *Text, byte Textlen){
printf("\ns-a apelat constructorul\n");
type= Type;
name=( char*) malloc (Namelen+1);
strcpy(name,Name);
namelen=Namelen;
text=( char* ) malloc (Textlen+1);
strcpy(text, Text);
textlen=Textlen;
printf("\nType is: %d",type);
printf("\nName is:");
while (*name)
printf("%c",*name++);
printf("\nText is: ");
while (*text){
printf("%c",*text++);
}
printf("\nNamelen= %d",this->namelen);
printf("\nTextlen= %d",this->textlen);
// The variables are stored correctly. Is it possible they are invalidated once the
// function exists?
}
virtual ~CMyMessage(){
free(text);
free(name);
}
void GetMessageAsByteStream(byte *message, int *length){
message[0]=GetMyMsgType();
message[1]=namelen;
message[2]=textlen;
message[3]=(byte ) (this->GetMyMsgText());
printf("\nmessage[0]= %d %c\n",message[0], message[0]);
printf("\nmessage[1]= %d %c\n",message[1], message[1]);
printf("\nmessage[2]= %d %c\n",message[2], message[2]);
printf("\nmessage[3]= %d %c\n",message[3], message[3]);
char *xxx=this->GetMyMsgText();
char *yyy; yyy=this->GetMyMsgText();
printf("\nName is :"); getch();
while (*name)
printf("%c",*name++); getch();
if (xxx != NULL)
printf("Msg is: %s\n", xxx);
while (*yyy)
printf("%c",*yyy++);
// there is absolutely NO WAY of accessing my NAME variable.. which is what I need to do.
memcpy(message+3, this->GetMyMsgName(), this->namelen);
printf("\n\nTEXTLEN= %d\n\n", this->textlen);
memcpy(message+3+namelen, this->GetMyMsgText(), this->textlen);
printf("Resulting message: ");
//while (*message)
// printf("%c %d ",*message++, message);
for (int i=0; i<55; i++)
printf("%c", (char)message[i]);
}
char* GetMyMsgText() {return this->text;}
char* GetMyMsgName() {return this->name;}
byte GetMyMsgType() {return this->tip;}
};
Main.cpp:
#include "stdafx.h"
#include <stdio.h>
#pragma once
#include "conio.h"
#include <string.h>
#include "CMyMessage.cpp"
void main()
{
char *name="JOHN.";
char *msg = "testing123.";
byte *message= (byte *) malloc(256);
int *ptrInt = (int *)malloc(sizeof(int));
byte type=1;
CMyMessage *mesaj=new CMyMessage(type, name, strlen(name), msg, strlen(msg));
mesaj->GetMessageAsByteStream(message, ptrInt);
printf("\ninside main(), type is: %d", *(message));
printf("\ninside main(), name length is: %d", *(message+1));
printf("\ninside main(), text length is: %d", *(message+2));
getch();
}
How do I properly use GetMyMsgText() or GetMyMsgName() ?
Thank you.