{"id":533,"date":"2011-01-06T20:23:12","date_gmt":"2011-01-06T20:23:12","guid":{"rendered":"https:\/\/ibex.tech\/visualcpp\/?p=533"},"modified":"2022-02-17T06:24:04","modified_gmt":"2022-02-17T06:24:04","slug":"pointers-handles-and-references","status":"publish","type":"post","link":"https:\/\/ibex.tech\/visualcpp\/memory\/pointers\/pointers-handles-and-references","title":{"rendered":"Pointers, Handles and References"},"content":{"rendered":"<p>\nModern C++ programs should almost always use vectors and iteriators in preference to the lower-level arrays and pointers, and strings to replace C-style array based character strings. Well designed programs use arrays and pointers only in the internals of class implementations where speed is essential. As well as being less powerful, C-style strings are the root cause of many many security problems.\n<\/p>\n<p>\nIn CLI instead of using pointers you use use tracking handles. Tracking handles are very similar to pointers but they behave differently since they refer to managed objects, not native objects. They are delibertly implemented differently to clearly differentiate them from standard C++ pointers (which of course you can still use). Whether a type is native or managed depends on wether it is declared with C++ syntax or with the C++\/CLI syntax for managed types, and both can be used in the same project.\n<\/p>\n<p>\nThere are 2 heaps in a C++\/CLI application, the native heap and the managed heap. The native heap is used when you use the new statement and you must explicitally manage the lifetime of objects on it yourself. The managed heap is a seperate pool of memory that is managed by the garbage collector. Instead of a normal pointer into the native heap you use a tracking handle to to point to objects in the managed heap and it is expressed usign the ^ symbol instead of *. The reason these new pointer like entities are called trackigng handles is that the garbage colletor also moves around objects in memory to keep the heap efficient. This means that unlike a native pointer a tracking handles address may change during execution, so you don&#39;t normally access the address of a handle.<br \/>\nTherefore, native C++ = vectors or pointers, C++\/CLI = handles.\n<\/p>\n<h4>\nDoing Pointer Type Things In C++\/CLI<br \/>\n<\/h4>\n<pre>\r\n<code>\r\n\tint count;\r\n\tcount = 0;\r\n\tsendBytes[count++] = &#39;A&#39;;\r\n\tsendBytes[count++] = &#39;B&#39;;\r\n\tsendBytes[count++] = &#39;C&#39;;\r\n<\/code><\/pre>\n<h4>\nHandles ^ (Use reference to pass back of values)<br \/>\n<\/h4>\n<p>\nNote that handles are typically used to pass classes and when used work in much the same way as an old C pointer.<br \/>\nMember selection through a handle (^) uses the pointer-to-member operator (-&gt;).\n<\/p>\n<h5>\nTo pass a handle to a function<br \/>\n<\/h5>\n<pre>\r\n<code>\r\n\tvoid SomeFunction(int channelsCount, array&lt;unsigned int&gt;^MyData)\r\n<\/code><\/pre>\n<h5>\nTo call the function<br \/>\n<\/h5>\n<pre>\r\n<code>\r\n\tarray&lt;unsigned int&gt;^ MyData = gcnew array&lt;unsigned int&gt;(512);\r\n\r\n\tartNetOutput1-&gt;TxArtDmxPacket(160, MyData);\r\n<\/code><\/pre>\n<p>\n<em><strong>However if you do this with a variable, then the original value doesn&#39;t get updated. The issue here is that when you box a value-type (which is what happens when you pass a handle the runtime creates a copy of your value-type on the GC heap: so any modifications to this copy are not reflected in the orginial instance of the value-type. Instead, for variable you need to use a reference.<\/strong><\/em>\n<\/p>\n<h5>\nUsing with strings<br \/>\n<\/h5>\n<pre>\r\n<code>\r\n\tString ^our_sentance = L&rdquo;Hellow world&rdquo;;\t\/\/The &lsquo;^&rsquo; is the handler character\r\n\tarray&lt;String^&gt; ^ports;\r\n\tString ^port;\r\n\tString ^PasswordEncrypt::EncryptString(String ^password)\r\n<\/code><\/pre>\n<h4>\nReference %<br \/>\n<\/h4>\n<p>\nIf you want to pass a memory location to a function and have the function modify it (i.e. pass a class that can be modified by a function or pass a variable as part of the function arguments that can be used to return values in) you need to use a reference. In C++\\cli you use the % character for a tracking reference, which means a reference to a managed location.<br \/>\nTo pass a reference to a function:\n<\/p>\n<pre>\r\n<code>\r\nvoid MMTimer::GetResolution (UInt32 %minimum, UInt32 %maximum, String ^%name, MyClass ^%Class1)\r\n<\/code><\/pre>\n<h5>\nTo call the function<br \/>\n<\/h5>\n<pre>\r\n<code>\r\n\tUInt32 max;\r\n\tUInt32 min;\r\n\tString ^theName;\r\n\tMyClass ^theClass;\r\n\tMySendTimer-&gt;GetResolution(min, max, theName, theClass);\r\n<\/code><\/pre>\n<p>\nYou use handle and a reference say in a function definition (e.g. for strings and classes):\n<\/p>\n<pre>\r\n<code>\r\n\tEndPoint ^%endPoint\r\n<\/code><\/pre>\n<p>\nUpdating a class to a new class\n<\/p>\n<p style=\"padding-left: 30px;\">\nIf you pass a class handle to another class, say as ^% arguments in its constructor, the contents of the class can be modified at any time by the called class. This is because you store the handle to the classes location in managed memory and then when you modify a component of the class you are modifying that original location in memory.\n<\/p>\n<p style=\"padding-left: 30px;\">\nHowever, say you want to modify a passed class by re-creating it, for instance to re-create it as a different size if it contains arrays. You can call a function and have it do this using ^% but it only works if the actual function you call re-assigns the handle to the newly created class. This is because the function has the ^%MyClass in its arguments so it knows to change the handle when you use MyClass = MyNewlyCreatedClass;<br \/>\nHowever you can&#39;t store the handle to a global handle and then do this later on in some other independant function, as if you use MyClass = MyNewlyCreatedClass; you are just updating the local handle MyClass, not refering back to the original handle. In this instance you can instead use a delegate. With a delegate you can pass a pointer to a function in another class and then when that other class has modified the class and wants to update the original class, it can call the passed function with the new handle as an argument, which the original class can then use to update its original handle. See delegates for an example&#8230;\n<\/p>\n<h4>\nPointer to a function<br \/>\n<\/h4>\n<p>\nA callback function is a pointer to a function &#8211; see delegates<br \/>\nAlternatively if you want to create a way for the user of a class to have one of their own functions called, use an event.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Modern C++ programs should almost always use vectors and iteriators in preference to the lower-level arrays and pointers, and strings to replace C-style array based character strings. Well designed programs use arrays and pointers only in the internals of class implementations where speed is essential. As well as being less powerful, C-style strings are the [&hellip;]<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32,70],"tags":[],"class_list":["post-533","post","type-post","status-publish","format-standard","hentry","category-pointers","category-pointer-handles-and-references"],"_links":{"self":[{"href":"https:\/\/ibex.tech\/visualcpp\/wp-json\/wp\/v2\/posts\/533","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ibex.tech\/visualcpp\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ibex.tech\/visualcpp\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ibex.tech\/visualcpp\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/ibex.tech\/visualcpp\/wp-json\/wp\/v2\/comments?post=533"}],"version-history":[{"count":3,"href":"https:\/\/ibex.tech\/visualcpp\/wp-json\/wp\/v2\/posts\/533\/revisions"}],"predecessor-version":[{"id":960,"href":"https:\/\/ibex.tech\/visualcpp\/wp-json\/wp\/v2\/posts\/533\/revisions\/960"}],"wp:attachment":[{"href":"https:\/\/ibex.tech\/visualcpp\/wp-json\/wp\/v2\/media?parent=533"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ibex.tech\/visualcpp\/wp-json\/wp\/v2\/categories?post=533"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ibex.tech\/visualcpp\/wp-json\/wp\/v2\/tags?post=533"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}