How to wrap class that passes unmanaged class in constructor? - visual-c++

I am trying to understand C++/CLI so I can create Wrapper classes for C++ code. My problem is that I have a class which stores a pointer to a parent object of that class, therefore I need to pass it into the class.
Below is an example, but the full class has more functions and stores extra data.
class A
{
private:
A* parent;
public:
A(A* Parent)
{
parent = Parent;
}
~A()
{
delete parent;
}
A* GetParent()
{
return parent;
}
}
My current idea is to have a non-public constructor so that you can construct a managed class with the unmanaged one without it being accessible outside the class.
public ref class ManagedA
{
A* unmanaged;
ManagedA(A* unmanaged)
{
this->unmanaged = unmanaged;
}
public:
ManagedA(ManagedA^ Parent)
{
unmanaged = new A(Parent->unmanaged);
}
~ManagedA()
{
delete unmanaged;
unmanaged = NULL;
}
ManagedA^ GetParent()
{
return gcnew ManagedA(unmanaged->GetParent());
}
}
While this works for functions inside the class, I still have issues if I want to create an object or if I have a function that needs the unmanaged class to be passed in.
Is there a way I can work around this?

ManagedA^ GetParent()
{
return gcnew ManagedA(unmanaged->GetParent());
}
You are shooting your leg off with code like this, it is very dangerous. Problem is, you are creating multiple ManagedA objects that refer to the exact same A*. As soon as one of them gets destroyed, all the other ManagedA objects now have a dangling pointer. That's almost guaranteed to cause memory corruption.
The solution is very simple, just store the parent reference in the constructor:
public ref class ManagedA {
private:
A* unmanaged;
ManagedA^ parent;
public:
ManagedA(ManagedA^ Parent) : parent(Parent) {
A* unmanagedParent = Parent == nullptr ? nullptr : Parent->unmanaged;
unmanaged = new A(unmanagedParent);
}
ManagedA^ GetParent() {
return parent;
}
~ManagedA() {
this->!ManagedA();
unmanaged = NULL;
}
!ManagedA() {
delete unmanaged;
}
};
Note the added nullptr check in the constructor, the only sane way I could see how the very first A* could ever get created.
That was the easy case, the exact same object identity problem occurs when you ever need to map an A* back to a ManagedA^. First check if this is really needed, the client code is expected to only ever manipulate ManagedA objects. When necessary, you'll need to create an lookup table so you can reliably find the corresponding ManagedA^ back. That requires a static Dictionary<IntPtr, ManagedA^>. Add objects to the dictionary in the constructor, remove them in the finalizer. Note that you forgot to include a finalizer, it is not optional. I added it to the snippet.

Related

How to maintain List of mutable objects inside immutable class

I have Immutable class and which has list of Mutable class objects.
class Immutable
{
final int id;
final String name;
final List<Mutable> list;
Immutable(int id,String name,List<Mutable> list)
{
this.id=id;
this.name=name;
this.list=list;
}
public List<Mutable> getMutables()
{
List<Mutable> l=new ArrayList<>(this.list);
return l;
}
}
class Mutable
{
String name;
Mutable(String name)
{
this.name=name;
}
}
Here My getMutables method is creating the objects and returning the cloned objects. But if so many threads or request access getMutables method then it will end up in creating multiple objects and soon out of memory error will come.
what to do in getMutables method so that, original Objects does not modified and more objects are not created.
Please help
Instead of returning new ArrayList in getMutables(), we can return unmodifibleList of Mutable objects from getMutables().
public List<Mutable> getMutables()
{
return Collections.unmodifiableList(this.list);
}
The unmodifiable Collection method of Collections class is used to return an unmodifiable view of the specified collection. This method allows modules to provide users with “read-only” access to internal collections.
Collections.unmodifiableList(mutableList);
Collections.unmodifiableSet(mutableSet);
Collections.unmodifiableMap(mutableMap);

How to find the parent object from the child(property) object in C#?

I have a situation where the child to be able to reference the parent. The reason for this is that I want the child to have the ability to update the parent object.
configuration.Range.Next(configuration)
I do not want to pass the parent object reference instead the Range object should be able to find its parent object. How would I do this?
Class Range { ....MethodX(){How do I access the Configuration Object here } }
Class Configuration { public Range range{get;set;} ..... }
Part of the difficulty with answering your question is that people use the terms "child" and "parent" to mean different things to different people.
One of the most common uses of the terms is as synonyms for subclass (child) and superclass (parent) in an inheritance structure. Assuming that is your meaning, you already have access to anything from the superclass (i.e. "parent") that is declared as public or protected. For example:
public class Parent
{
protected int Foo { get; set; }
}
public class Child : Parent
{
public void DoSomething()
{
Foo = 42;
// or
base.Foo = 42;
}
}
If this isn't the situation you're working with please add more information to your original question to better describe what you mean when you use the terms "child" and "parent."

initializing derived class member variables using base class reference object

I came across a lot of code in our company codebase with the following structure
class Base
{
public Base (var a, var b)
{
base_a = a;
base_b = b;
}
var base_a;
var base_b;
}
class Derived:Base
{
publc Derived (var a,b,c,d): base (a,d)
{
der_c = c;
der_d = d;
}
var der_c;
var der_d;
var der_e;
}
class Ref
{
Base _ref;
public Ref( var a,b,c,d)
{
_ref = new Derived (a,b,c,d)
}
public void method( )
{
_ref.der_e = 444; // won't compile
}
}
What is the correct way to initialize der_e ? What is the advantages of having a reference of base class and using an object derived class for _ref ? Just the fact that using a base class reference can hold multiple derived class objects ? If that's the case, should all the member variables of derived class be initialized during construction itself (like this: _ref = new Derived (a,b,c,d) ). What if I want to initialize _ref.der_e later in a method ? I know I can do this (var cast_ref = _ref as Derived; cast_ref.der_e = 444) but this look doesn't seem to the best practice. What is the idea of having such a structure and what is the correct of initializing a member of a derived class object after it has been constructed ?
Those are too many questions in a single post.
What is the correct way to initialize der_e ?
For initializing der_e you will have to have Reference of Derived class as it knows about the der_e property and not Base class.
What is the advantages of having a reference of base class and using
an object derived class for _ref ?
Yes that's called Polymorphism which is the essence of Object Oriented Programming. It allows us to hold various concrete implementations without knowing about the actual implementation.
If that's the case, should all the member variables of derived class
be initialized during construction itself (like this: _ref = new
Derived (a,b,c,d) )
There is no such rule. It depends on your scenario. If the values are not meant to be changed after the creation of the object and the values are known before hand during construction of the object then they should be initialized during construction.
Again if there are various scenarios like sometimes values are known and sometimes not then there can be Overloaded Constructors, which take different arguments.
What if I want to initialize _ref.der_e later in a method ?
That is perfectly fine, it depends on what you are trying to achieve. The question is not a concrete one but an abstract one in which it is difficult to comment on what you are trying to achieve.
I know I can do this (var cast_ref = _ref as Derived; cast_ref.der_e =
444) but this look doesn't seem to the best practice.
I am sharing some Java code which is similar to C# as I am from Java background
//This class knows about Base and nothing about the Derived class
class UserOfBase{
Base ref;
//Constructor of UserOfBase gets passed an instance of Base
public UserOfBase(Base bInstance){
this.ref = bInstance;
}
//Now this class should not cast it into Derived class as that would not be a polymorphic behavior. In that case you have got your design wrong.
public void someMethod(){
Derived derivedRef = (Derived)ref; //This should not happen here
}
}
I am sharing some references which would help you with this, as I think the answer can be very long to explain.
Factory Pattern
Dependency Injection
Head First Design Patterns
Posts on SO regarding polymorphism
You can create a constructor in your derived class and map the objects or create an extension method like this:
public static class Extensions
{
public static void FillPropertiesFromBaseClass<T1, T2>(this T2 drivedClass, T1 baseClass) where T2 : T1
{
//Get the list of properties available in base class
System.Reflection.PropertyInfo[] properties = typeof(T1).GetProperties();
properties.ToList().ForEach(property =>
{
//Check whether that property is present in derived class
System.Reflection.PropertyInfo isPresent = drivedClass.GetType().GetProperty(property.Name);
if (isPresent != null && property.CanWrite)
{
//If present get the value and map it
object value = baseClass.GetType().GetProperty(property.Name).GetValue(baseClass, null);
drivedClass.GetType().GetProperty(property.Name).SetValue(drivedClass, value, null);
}
});
}
}
for example when you have to class like this:
public class Fruit {
public float Sugar { get; set; }
public int Size { get; set; }
}
public class Apple : Fruit {
public int NumberOfWorms { get; set; }
}
you can initialize derived class by this code:
//constructor
public Apple(Fruit fruit)
{
this.FillPropertiesFromBaseClass(fruit);
}

How to return a vector of objects to managed code efficiently?

I have a ref class that contains a pointer to an unmanaged class. the class has some basic types and also a vector of objects of another class. I would like to know the best way to get and set the vector from managed code. Will a memcpy between unmangedb objects be efficient or setting each member variable of unmanagedb?
for ex (assume the class is complete. I am writing what is relevant to the question)
Assume we already have a managed wrapped for struct UnmanagedB called B.
struct UnmanagedA
{
int a;
vector<UnmanagedB> list;
};
public ref class A : public System::IDisposable
{
public:
// properties
property System::UInt32 a
{
System::UInt32 get();
void set(System::UInt32 value);
}
property array<B^>^ list
{
System::array<B^>^ get(); // what is the best way to set and get the vector
void set(array<B^>^ value);
}
private:
UnmanagedA* obj1;
};
This obviously won't be cleanly possible, since UnmanagedA contains a vector of UnmanagedB values, while A exposes an property of type array<B^>. If this is intended and not a typo, you will need to marshall the content of B^ into instances of UnmanagedB. Otherwise, let UnmanagedA hold a std::vector< B* > and take care of proper lifetime management.

efficiently calling unmanaged method taking unmanaged objects as parameters from managed code

I have the following scenario. The managed code will initialize lots of object of a class which is a wrapper around an unmanaged struct. There are two approaches that I can do for this. One is to have a managed class wrapper that just has a pointer to the unmanaged object. The other is to have a full fledged managed class and create the unmanaged object when required to call into unmanaged methods. I have provided both the methods below. I was told that if I use the approach 1(having a pointer to unmanged object), the GC will have lots of issue knowing about the unmanaged portion and it is better to do approach 2. Does someone tell me which is better or if there is some other approach that is even better. My concern with Approach 2 is that there are copying to and fro everytime a unmanaged method is called. I am not sure if the GC issue outweighs it.
EDIT- the first approach has a ref class and the second has a value class. The reason the second is value is so that it can be added to lists more efficiently
In unmanaged:
struct A_UNMANAGED
{
int a;
int b[20];
};
void GetData(A_UNMANAGED& a); // populates A
In managed (First Approach)
public ref class A_MANAGED
{
A_UNMANGED* ap;
public:
property System::UInt32 a
{
System::UInt32 get() { return ap->a; }
void set(System::UInt32 value) { ap->a = value; }
}
property array<System::UInt32>^ b
{
array<System::UInt32>^ get() { return ap->b; }
void set(array<System::UInt32>^ value) { b = value; } // assume this copy works
}
internal:
void GetData()
{
GetData(ap);
}
};
In managed (Second Approach) (EDIT: updated to ref. Assume all the garbage collection and pointer creation is written correctly)
public value class A_MANAGED
{
System::UInt32 a;
array<System::UInt32>^ b;
public:
property System::UInt32 a
{
System::UInt32 get() { return a; }
void set(System::UInt32 value) { a = value; }
}
property array<System::UInt32>^ b
{
array<System::UInt32>^ get() { return b; }
void set(array<System::UInt32>^ value) { b = value; }
}
internal:
void GetUnmanaged(A_UNMANAGED& obj1)
{
obj1.a = a;
pin_ptr<System::UInt32> bp = &b[0];
memcpy(obj1.b, bp, 20);
}
void GetData()
{
A_UNMANAGED obj2;
GetUnmanaged(obj2);
GetData(obj2);
// copy from obj2 to member variables
}
};
No, the 1st snippet it the canonical way. The garbage collector only moves the pointer, it doesn't move the pointed-to object. That one should have been allocated with malloc() or the new operator, it cannot be moved.
There are otherwise several serious problems in your code. You don't seem to allocate the memory for A_UNMANAGED unless GetData() takes its argument by reference. GetData() is never called. This must normally be a ref class (not ref value) so you can provide a destructor and a finalizer to release the memory. The b property setter will bomb your program with a StackOverflowException. Be sure to study the language before tackling this project.
Check this answer for sample code.
As Hans said, the first way is the usual approach (though personally, I think P/Invoke would be more succinct in this particular case...). However, your A_MANAGED::b implementation will not work, which would be obvious if one were to try simply compiling it. Try this instead:
public ref class A_MANAGED
{
A_UNMANAGED* ap;
public:
A_MANAGED() : ap(new A_UNMANAGED() ) { }
~A_MANAGED() { this->!A_MANAGED(); }
!A_MANAGED() { delete ap; ap = nullptr; }
property int a
{
int get() { return ap->a; }
void set(int value) { ap->a = value; }
}
property array<int>^ b
{
array<int>^ get()
{
using System::Runtime::InteropServices::Marshal;
array<int>^ arr = gcnew array<int>(20);
Marshal::Copy(System::IntPtr(ap->b), arr, 0, 20);
return arr;
}
void set(array<int>^ value)
{
using System::Runtime::InteropServices::Marshal;
Marshal::Copy(value, 0, System::IntPtr(ap->b), 20);
}
}
internal:
void GetData()
{
::GetData(*ap);
}
};
And then there's the usual caveat about returning arrays from properties: it's a bad idea. Unless you really want to maintain parity with the unmanaged class' public interface, b should really be a pair of set/get functions rather than a property.

Resources