Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As an alternative, there <em>is</em> a way of using unmanaged C++ types in your code, but it does still involve some typing. In a VS C++ project, create your unmanaged struct:</p> <pre><code>struct Date_s { union { struct { unsigned nWeekDay : 3; // 0..7 (3 bits) unsigned nMonthDay : 6; // 0..31 (6 bits) unsigned : 0; // Force alignment to next boundary. unsigned nMonth : 5; // 0..12 (5 bits) unsigned nYear : 8; // 0..100 (8 bits) }; unsigned bob; }; }; </code></pre> <p>Now we create a managed type which wraps this structure:</p> <pre><code>public ref struct Date_ms { AutoPtr&lt;Date_s&gt; data; Date_ms() { data = new Date_s(); } property unsigned nWeekDay { unsigned get() { return data-&gt;nWeekDay; } void set(unsigned value) { data-&gt;nWeekDay = value; } } property unsigned nMonthDay { unsigned get() { return data-&gt;nMonthDay; } void set(unsigned value) { data-&gt;nMonthDay = value; } } property unsigned nMonth { unsigned get() { return data-&gt;nMonth; } void set(unsigned value) { data-&gt;nMonth = value; } } property unsigned nYear { unsigned get() { return data-&gt;nYear; } void set(unsigned value) { data-&gt;nYear = value; } } property unsigned bob { unsigned get() { return data-&gt;bob; } void set(unsigned value) { data-&gt;bob = value; } } }; </code></pre> <p>There's some copy and pasting to do there. There's also an external item I use here: it's <a href="http://weblogs.asp.net/kennykerr/archive/2007/03/26/AutoPtr.aspx" rel="nofollow">AutoPtr</a> from Kerr. I've also added the line <code>T* operator=(T* rhs) { return (m_ptr = rhs); }</code> to the AutoPtr code (as suggested in the comments to Kerr's post) to make the initialiser work.</p> <p>You can now use this new structure in your C# code, and everything should work as expected:</p> <pre><code>var test = new Date_ms(); test.nMonth = 3; test.nMonthDay = 28; test.nYear = 98; Console.WriteLine("{0}, {1}, {2}", test.nMonth, test.nMonthDay, test.nYear); Console.WriteLine("{0}", test.bob); </code></pre> <p>results in <code>3, 28, 98</code> and <code>224</code>.</p> <h1>BIG GIANT WARNING</h1> <p>Mixing managed and unmanaged code like this is dangerous, which is why Kerr wrote AutoPtr in the first place (BTW, his <a href="http://weblogs.asp.net/kennykerr/archive/2005/07/12/Mixing-Native-and-Managed-Types-in-C_2B002B00_.aspx" rel="nofollow">blog post</a> on the topic is well worth a read). This works for me, but I can't guarantee that it won't cause memory leaks. You should <em>definately</em> check that this works as intended before deploying it. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload