c++ cli - how to assign pointer in a managed array of pointers c++/cli? -
i new managed code , need pass array of pointers different structures windows form using c++/cli , didn`t work !
my problem in managed array, how can correctly access elements .
the code sequence :
array<void*> ^ ptr;//here ptr value undefined , type array<void*> ^ ptr = gcnew array<void*> (2);// length 0x2 , 0x0 , 0x1 values undefined of type void class1::struct1 structobj1; class2::struct2 structobj2; ptr[0] = &structobj1;// value empty of type void!! ptr[1] = &structobj2;//value empty of type void!! when watched ptr , found above comments.
notice repeating code using unmanaged array works
void* ptr[2];//here ptr value undefined , type void*[] class1::struct1 structobj1; class2::struct2 structobj2; ptr[0] = &structobj1;// value address1 of type void* ptr[1] = &structobj2;//value address2 of type void* can see problem??
do need use unmanaged array convert managed? if yes, how can ??
passing unmanaged pointers in managed array may valid c++/cli, it's not ideal way things. consider creating custom managed class (ref class in c++/cli) hold structures, instead of passing around pointers.
for this, i'm assuming struct1 , struct2 unmanged structs. answer applies if case.
your existing code works me. here's version, debugging added in.
public struct struct1 { int foo; }; public struct struct2 { float bar; }; int main(array<system::string ^> ^args) { array<void*> ^ ptr; ptr = gcnew array<void*> (2); for(int = 0; < ptr->length; i++) debug::writeline("ptr[{0}] = {1:x8}", i, reinterpret_cast<int>(ptr[i])); struct1 structobj1; struct2 structobj2; ptr[0] = &structobj1; ptr[1] = &structobj2; for(int = 0; < ptr->length; i++) debug::writeline("ptr[{0}] = {1:x8}", i, reinterpret_cast<int>(ptr[i])); struct1* pointertostructobj1 = reinterpret_cast<struct1*>(ptr[0]); structobj1.foo = 4; debug::writeline("pointertostructobj1->foo = {0}", pointertostructobj1->foo); } output:
ptr[0] = 00000000 ptr[1] = 00000000 ptr[0] = 0013f390 ptr[1] = 0013f394 pointertostructobj1->foo = 4
edit
to use debug::writeline, add using namespace system::diagnostics.
the debugger doesn't know how display contents of void*, displays blank. display null pointer differently, though: null shows <undefined value>, non-null shows blank.
my philosophy on c++/cli is: if you're going write managed code, write managed code. consider replacing vector managed list. if still need unmanaged objects, urge consider writing managed class typed pointers, rather void* array.
to implement such class, create whatever fields need, sure they're pointers, not direct. (vector<foo>* instead of vector<foo>.) create objects new in constructor, , delete them in destructor (which called on dispose) & finalizer.
Comments
Post a Comment