gcroot in c++/cli - c++-cli

What does gcroot mean? I found it in code I am reading.

gcroot is a C++/cli template class that eases holding managed types in C++/cli classes.
You can for example have the following:
#include <msclr/gcroot.h>
using namespace msclr;
class Native {
public:
Native(Object ^obj) :
netstring(obj->ToString()) { // Initializing the gcroot<String ^>
}
~Native() {
}
void Print() {
array<Char> ^chars = netstring->GetChars(); // Dereferencing the gcroot<String ^>
_wprintf("netstring is:");
if (chars->Length > 0) {
pin_ptr<Char> charptr = &(chars[0]);
_wprintf("%s", (wchar_t const *)charptr);
}
}
private:
gcroot<String ^> netstring;
};
gcroot acts as a reference to the managed object or value type instance and is doing all the work when copying the object or value type instance.
Normally you need to work with GCHandle and some C functions of the .NET framework. This is all encapsulated in gcroot.

When the .NET garbage collector runs, it determines which objects are still in use by doing reachability analysis. Only the managed heap is analyzed while looking for pointers to objects, so if you have a pointer from a native object to a managed object, you need to let the garbage collector know, so it can include it in reachability analysis, and so it can update the pointer if the target moves during compaction.
As rstevens said, the .NET GCHandle class does this, and C++/CLI is a C++-oriented wrapper for GCHandle which adds type safety and convenient syntax.

Related

Are managed pointers in c++/cli initialized to nullptr automatically using GCRoot?

I need to initialize to a variable only once in C++/CLI class accessible to managed code. Is a managed pointer initialized to nullptr when using gcroot? Specifically will the Initialize function below work as I expect? And only create the MyOtherClass once no matter how many times MyClass::Intialize is called?
class MyClass
{
public:
void Initialize();
private:
#ifdef _MANAGED
gcroot<MyOtherClass^> _myOtherClass;
#endif
};
void MyClass::Initialize()
{
if(_myOtherClass == nullptr)
{
_myOtherClass = gcnew MyOtherClass();
}
}
I'm using Visual Studio 2019. And the managed object accessing this is written in C#. I'm relatively new to CLI code. And I wasn't able to find the answer quickly by Googling it. And I'm sure someone in this community knows the answer.
Managed handles are default initialized to nullptr, per Default initialization: "when handles are declared and not explicitly initialized, they are default initialized to nullptr".
if(_myOtherClass == nullptr)
The above fails to compile with error C2088: '==': illegal for struct because gcroot wraps a GCHandle structure, which cannot be directly compared against nullptr.
To check the target handle (not the wrapper handle), use the following, which works as expected.
if(static_cast<MyOtherClass^>(_myOtherClass) == nullptr)

Cannot assign to an element of an initonly array?

It seems commonly thought that C++/CLI's initonly is the equivalent of C#'s readonly keyword. However, the following:
ref class C {
C();
void Method();
initonly array<int>^ m_array;
};
C::C() {
m_array = gcnew array<int>(10);
}
void C::Method() {
m_array[0] = 5; // Fails with C3893
}
The full error is "'C::m_array': l-value use of initonly data member is only allowed in an instance constructor of class 'C'".
The error message seems strange as I'm not using m_array as the target of an assignment, this is the equivalent of writing
m_array->SetValue(5, 0);
which incidentally compiles fine and does the same thing.
Is this bugged in C++/CLI or by design? By the way, is there any performance penalty to using Array::SetValue vs using the accessor?
A similar (but not identical) case was reported and apparently filed as a bug for VS2008: http://bytes.com/topic/net/answers/847520-initonly-but-not-bug-vc-2008-clr . I'm using Visual Studio 2012.
Yes, that's a bug. It's enforcing something which is not implied by the .NET type system, and the enforcement is ineffective.
But don't use Array::SetValue, which involves boxing and is not type safe. You can just do:
auto array = m_array; // another handle to same array
array[0] = 5;

How can I use a 'native' pointer in a reference class in C++/CLI?

I am trying to write a small library which will use DirectShow. This library is to be utilised by a .NET application so I thought it would be best to write it in C++/CLI.
I am having trouble with this line however:
HRESULT hr = CoCreateInstance( CLSID_FilterGraph,
NULL,
CLSCTX_INPROC_SERVER,
IID_IGraphBuilder,
(void**)(&graphBuilder) ); //error C2440:
Where graphBuilder is declared:
public ref class VideoPlayer
{
public:
VideoPlayer();
void Load(String^ filename);
IGraphBuilder* graphBuilder;
};
If I am understanding this page correctly, I can use */& as usual to denote 'native' pointers to unmanaged memory in my C++/CLI library; ^ is used to denote a pointer to a managed object. However, this code produces:
error C2440: 'type cast' : cannot convert from 'cli::interior_ptr' to 'void **'
The error suggests that graphBuilder is considered to be a 'cli::interior_ptr<Type>'. That is a pointer/handle to managed memory, isn't it? But it is a pure native pointer. I am not trying to pass the pointer to a method expecting a handle or vice versa - I simply want to store it in my managed class) If so, how do I say graphBuilder is to be a 'traditional' pointer?
(This question is similar but the answer, to use a pin_ptr, I do not see helping me, as it cannot be a member of my class)
The error message is a bit cryptic, but the compiler is trying to remind you that you cannot pass a pointer to a member of a managed class to unmanaged code. That cannot work by design, disaster strikes when the garbage collector kicks in while the function is executing and moves the managed object. Invalidating the pointer to the member in the process and causing the native code to spray bytes into the gc heap at the wrong address.
The workaround is simple, just declare a local variable and pass a pointer to it instead. Variables on the stack can't be moved. Like this:
void init() {
IGraphBuilder* builder; // Local variable, okay to pass its address
HRESULT hr = CoCreateInstance(CLSID_FilterGraph,
NULL,
CLSCTX_INPROC_SERVER,
IID_IGraphBuilder,
(void**)(&builder) );
if (SUCCEEDED(hr)) {
graphBuilder = builder;
// etc...
}
}

Capturing return type of unmanaged class using C++/CLI

I have a method in my native dll, that I want to use. The method returns an object of a type that is also in my native dll.I am trying to write a c++/CLI wrapper.
Now,
Can I get a return value as the object using C++/CLI and how do I do that?
Can we store and pass the native C++ object?
Should I need to create my own class resembling the native C++ class?
How would I marshal a class?
For Example,My native dll has these classes,
class X
{
/* some props and methods. */
};
Class Y
{
X* someMethod();
};
I need to wrap the someMethod class using C++/CLI. Will I be able to get the return value in the CLI?
Returning pointers to C++ objects from an exported function in a DLL is a pretty bad idea. It is a nasty memory management problem, you'd expect the client code to release the object. That can only come to a good end when both DLLs use the exact same version of the DLL version of the CRT (/MD compile option). If you can't recompile the native DLL then stop right now, you cannot make it work reliably or you'll have a big maintenance problem in the future.
Anyhoo, you need a wrapper for both classes. They should resemble this:
#pragma managed(push, off)
#include "xandy.h"
#pragma managed(pop)
using namespace System;
namespace something {
public ref class XWrapper {
X* mX;
public:
XWrapper(X* obj) : mX(obj) {}
~XWrapper() { this->!XWrapper(); }
!XWrapper() {
// Trouble is here!!!
delete mX;
}
};
public ref class YWrapper {
Y* mY;
public:
YWrapper() { mY = new Y; }
~YWrapper() { this->!YWrapper(); }
!YWrapper() { delete mY; }
XWrapper^ someMethod() {
return gcnew XWrapper(mY->someMethod());
}
};
}

What does the C++/CLI Object^% (caret percent-sign) declaration mean?

This apparently is a Google-proof term since I can't get any search engines to not throw away the "extra" characters. I did also look on MSDN in the C++ reference but I can't seem to find the C++/CLI reference because there is nothing in the declarations section on it.
It means "pass by reference":
void bar::foo(Object^% arg) {
arg = gcnew Object; // Callers argument gets updated
}
Same thing in C++:
void foo(Object** arg) {
*arg = new Object;
}
or C#:
void foo(out object arg) {
arg = new Object();
}
C++/CLI doesn't distinguish between ref and out, it does not have the definite assignment checking feature that the C# language has so no need to distinguish between the two. Same in VB.NET, ByRef vs ByVal.
% is a tracking reference.
It is similar to a native reference (Object&), but a tracking reference can reference a CLR object while a native reference cannot. The distinction is necessary because the garbage collector can move CLR objects around, so a CLR-object's memory address may change.
The ^ is a handle. This simply means it is managed. See MSDN and also this SO post.
Essentially, it's the "managed" version of Object*&, and equivalent to ref or out on a reference type in C#.
This is a managed pointer by reference. So if you had something like:
void DoSomething(System::String^% stringObject)
in C# it would look like:
void DoSomething(ref System.String stringObject)
This is a C++/CLI Tracking Reference. This is kind of like a C++ reference, but to a managed object.