c++ cli - Should I use a reference or an instance of C# objects in a C++/CLI class? -
in managed c++ class, should using reference or instance of c# class i've implemented in library?
consider example:
// mymanagedclass.h #pragma once using namespace system::collections::generic; using namespace my::namespace::mycsharplib; namespace my::namespace::mymanagedlib { public ref class mymanagedclass { public: mycsharpclass myinst; // have instance! mycsharpclass ^myref; // need gcnew list<mycsharpclass ^> listinst; // have instance! list<mycsharpclass ^> ^listref; // need gcnew }; } and managed class called c# code:
// driver.cs using my.namespace.mycsharplib; using my.namespace.mymanagedlib; public class driver { private static void main(string[] args) { mymanagedclass mmc = new mymanagedclass(); dostuff(mmc); } } my gut tells me should using myref , listref because that's i'd doing if implemented in c#. why allowed directly instantiate instance of mycsharpclass? repercussions of doing this? if class ever has 1 collection of mycsharpclass objects, there harm directly initializing collection?
c++/cli has feature called stack semantics, using when declare reference type member though value type (mycsharpclass myinst;).
gcnew still being called, don't see code because compiler inject automatically default constructor. beware generate code dispose myinst!
below (pseudo) c++/cli code equivalent of msil compiler emit class:
constructor:
mymanagedclass() { myinst = gcnew mycsharpclass(); } dispose:
void dispose(bool dispose) { if (dispose) { try { this->~mymanagedclass(); } { delete myinst; } } } edit:
regarding question repercussions: manually allocating gcnew means when mymanagedclass objects die, object pointed myref still hang around until garbage collector cleans up; whereas using stack semantics have more deterministic means of controlling object lifetimes without having write dispose method yourself.
it means when using stack semantics must careful share objects with...
Comments
Post a Comment