Idov
Idov

Reputation: 5124

c++ casting char* to object?


Is it possible in C++ to convert an array of chars to an object like so:

char* bytes = some bytes...
MyObject obj = (MyObject)(bytes);

?
How do I have to define the cast operator?
thanks :)

Upvotes: 1

Views: 8256

Answers (4)

Fred Foo
Fred Foo

Reputation: 363567

If the bytestring actually represents a valid object of type MyObject, you can get a MyObject* with

reinterpret_cast<MyObject *>(bytes)

This is very unlikely to work though, unless the char* is the result of casting a pointer to a properly constructed MyObject.

Upvotes: 2

Tim
Tim

Reputation: 9172

You probably want to define a constructor for MyObject:

class MyObject {
public:
  explicit MyObject(const char* bytes);
  ...
};

MyObject::MyObject(const char* bytes) {
  // do whatever you want to initialize "MyObject" from the byte string
}

and then you can use it:

char* bytes = some bytes...
MyObject obj = MyObject(bytes);  // this will work
MyObject obj(bytes);             // so will this

Upvotes: 9

T.E.D.
T.E.D.

Reputation: 44804

I like Jerry Coffin and larsman's answers, depending on wheather the location in question already has a constructed object in it or not.

There is one further wrinkle though. If the type of MyObject happens to qualify as a POD class, then it might be OK to just use a reintreprent cast on the pointer like larsman suggested, as no constructor is really required for the object.

I say "might" because it is remotely possible that your platform uses different representations for char * and class pointers. Most I've used don't do that though.

Upvotes: -2

Jerry Coffin
Jerry Coffin

Reputation: 490108

I can see two possibilities here. If you have data that you know represents the target type, you can use a reinterpret_cast to get them treated as an object of that type:

MyObject *obj = reinterpret_cast<MyObject *>(bytes);

If you want to create an object of the specified type in the designated memory, you use the placement new operator to construct an object at the specified address:

char *bytes = whatever;

MyObject *obj = new(bytes) MyObject;

When you're finished using the object, you don't delete it, you directly invoke the dtor:

obj->~MyObject();

Note that for this to work, you need to ensure that (if nothing else) bytes points to data that's aligned correctly for the destination type.

Upvotes: 3

Related Questions