user987316
user987316

Reputation: 942

Type casting in C++\CLI project

I have project which I am compiling with /clr. I have a class like below..

ref class A
{
public:
 void CheckValue(void * test);
 typedef ref struct val
{
 std::string *x;
}val_t;

};

in my implementation I ahve to use something like below..

void A::CheckValue(void *test)
{
 a::val_t^ allVal = (a::val_t^)test;
}

in my main I have used like..

int main()
{
A^ obj = gcnew A();
a::val_t valObj = new std::string("Test");
obj->CheckValue((void*)valObj);
}

I am getting type cast error and two places - obj->CheckValue((void*)valObj); and at obj->CheckValue((void*)valObj); error C2440: 'type cast' : cannot convert from 'void*' to 'A::val_t ^'

This snippet is just to show behavior at my end and I ahve to use it this way only. Earlier I was running it using non /clr so it compiled fine.

Now question I have how can I make this type casting work in C++/CLI type project?

Upvotes: 0

Views: 2762

Answers (2)

Aaron Peavy
Aaron Peavy

Reputation: 11

Here is how I would get around the limitation you are seeing, just remove the struct from the managed object, since it contains native pointer types.

struct val_t
{
  char* x;
};

ref class A
{
public:
  void CheckValue(void* test);
};

void A::CheckValue(void* test)
{
  val_t* allVal = (val_t*)test;
}

int main()
{
  A^ obj = gcnew A();
  val_t valObj;
  valObj.x = "Test";
  obj->CheckValue((void*)&valObj);
}

Now, if you absolutely need the struct to be managed, here is how to do it:

ref class A
{
public:
  void CheckValue(void * test);
  value struct val_t
  {
    char* x;
  };
};

void A::CheckValue(void *test)
{
  a::val_t* allVal = (a::val_t*)test;
}

int main()
{
  A^ obj = gcnew A();
  a::val_t valObj;
  valObj.x = "Test";
  pin_ptr<a::val_t> valPin = &valObj;
  obj->CheckValue((void*)valPin);
}

Upvotes: 0

Sheng Jiang 蒋晟
Sheng Jiang 蒋晟

Reputation: 15261

Replace void * with Object^. You can also write a generic version of CheckValue but then there is not much point of having a weak-typed parameter when you have the type in the generic parameter.

A reference handle represents an object on the managed heap. Unlike a native pointer, CLR could move the object around during a function call, so the behavior of a pointer and a reference handle is different, and a type cast would fail. You can also pin the object being referenced using pin_ptr if you really need a void* so CLR would not be moving the object during the function call.

Upvotes: 1

Related Questions