PageRenderTime 57ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/trunk/Doc/Manual/CSharp.html

#
HTML | 1908 lines | 1577 code | 329 blank | 2 comment | 0 complexity | d40273460f28f5a3adc7becc17368b36 MD5 | raw file
Possible License(s): LGPL-2.1, Cube, GPL-3.0, 0BSD, GPL-2.0
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <html>
  3. <head>
  4. <title>SWIG and C#</title>
  5. <link rel="stylesheet" type="text/css" href="style.css">
  6. </head>
  7. <body bgcolor="#FFFFFF">
  8. <H1><a name="CSharp"></a>19 SWIG and C#</H1>
  9. <!-- INDEX -->
  10. <div class="sectiontoc">
  11. <ul>
  12. <li><a href="#CSharp_introduction">Introduction</a>
  13. <li><a href="#CSharp_differences_java">Differences to the Java module</a>
  14. <li><a href="#CSharp_void_pointers">Void pointers</a>
  15. <li><a href="#CSharp_arrays">C# Arrays</a>
  16. <ul>
  17. <li><a href="#CSharp_arrays_swig_library">The SWIG C arrays library</a>
  18. <li><a href="#CSharp_arrays_pinvoke_default_array_marshalling">Managed arrays using P/Invoke default array marshalling</a>
  19. <li><a href="#CSharp_arrays_pinning">Managed arrays using pinning</a>
  20. </ul>
  21. <li><a href="#CSharp_exceptions">C# Exceptions</a>
  22. <ul>
  23. <li><a href="#CSharp_exception_example_check_typemap">C# exception example using "check" typemap</a>
  24. <li><a href="#CSharp_exception_example_percent_exception">C# exception example using %exception</a>
  25. <li><a href="#CSharp_exception_example_exception_specifications">C# exception example using exception specifications</a>
  26. <li><a href="#CSharp_custom_application_exception">Custom C# ApplicationException example</a>
  27. </ul>
  28. <li><a href="#CSharp_directors">C# Directors</a>
  29. <ul>
  30. <li><a href="#CSharp_directors_example">Directors example</a>
  31. <li><a href="#CSharp_directors_implementation">Directors implementation</a>
  32. <li><a href="#CSharp_director_caveats">Director caveats</a>
  33. </ul>
  34. <li><a href="#CSharp_multiple_modules">Multiples modules</a>
  35. <li><a href="#CSharp_typemap_examples">C# Typemap examples</a>
  36. <ul>
  37. <li><a href="#CSharp_memory_management_member_variables">Memory management when returning references to member variables</a>
  38. <li><a href="#CSharp_memory_management_objects">Memory management for objects passed to the C++ layer</a>
  39. <li><a href="#CSharp_date_marshalling">Date marshalling using the csin typemap and associated attributes</a>
  40. <li><a href="#CSharp_date_properties">A date example demonstrating marshalling of C# properties</a>
  41. <li><a href="#CSharp_partial_classes">Turning wrapped classes into partial classes</a>
  42. <li><a href="#CSharp_extending_proxy_class">Extending proxy classes with additional C# code</a>
  43. <li><a href="#CSharp_enum_underlying_type">Underlying type for enums</a>
  44. </ul>
  45. </ul>
  46. </div>
  47. <!-- INDEX -->
  48. <H2><a name="CSharp_introduction"></a>19.1 Introduction</H2>
  49. <p>
  50. The purpose of the C# module is to offer an automated way of accessing existing C/C++ code from .NET languages.
  51. The wrapper code implementation uses C# and the Platform Invoke (PInvoke) interface to access natively compiled C/C++ code.
  52. The PInvoke interface has been chosen over Microsoft's Managed C++ interface as it is portable to both Microsoft Windows and non-Microsoft platforms.
  53. PInvoke is part of the ECMA/ISO C# specification.
  54. It is also better suited for robust production environments due to the Managed C++ flaw called the
  55. <a href="http://msdn.microsoft.com/en-us/library/aa290048(VS.71).aspx">Mixed DLL Loading Problem</a>.
  56. SWIG C# works equally well on non-Microsoft operating systems such as Linux, Solaris and Apple Mac using
  57. <a href="http://www.mono-project.com/Main_Page">Mono</a> and <a href="http://www.dotgnu.org/pnet.html">Portable.NET</a>.
  58. </p>
  59. <p>
  60. To get the most out of this chapter an understanding of interop is required.
  61. The <a href="http://msdn.microsoft.com">Microsoft Developer Network (MSDN)</a> has a good reference guide in a section titled "Interop Marshaling".
  62. Monodoc, available from the Mono project, has a very useful section titled <a href="http://www.mono-project.com/Interop_with_Native_Libraries">Interop with native libraries</a>.
  63. </p>
  64. <H2><a name="CSharp_differences_java"></a>19.2 Differences to the Java module</H2>
  65. <p>
  66. The C# module is very similar to the Java module, so until some more complete documentation has been written,
  67. please use the <a href="Java.html#Java">Java documentation</a> as a guide to using SWIG with C#.
  68. The C# module has the same major SWIG features as the Java module.
  69. The rest of this section should be read in conjunction with the Java documentation as it lists the main differences.
  70. The most notable differences to Java are the following:
  71. <ul>
  72. <li>
  73. When invoking SWIG use the <tt>-csharp</tt> command line option instead of <tt>-java</tt>.
  74. </li>
  75. <li>
  76. The <tt>-nopgcpp</tt> command line option does not exist.
  77. </li>
  78. <li>
  79. The <tt>-package</tt> command line option does not exist.
  80. </li>
  81. <li>
  82. The <tt>-namespace &lt;name&gt;</tt> commandline option will generate all code into the namespace specified by <tt>&lt;name&gt;</tt>.
  83. C# supports nested namespaces that are not lexically nested, so nested namespaces will of course also work. For example:
  84. <tt>-namespace com.bloggs.widget</tt>, will generate code into C# namespaces:
  85. <div class="code"><pre>
  86. namespace com.bloggs.widget {
  87. ...
  88. }
  89. </pre></div>
  90. Note that by default, the generated C# classes have no namespace and the module name is unrelated to namespaces. The module name is just like in Java and is merely used to name some of the generated classes.
  91. </li>
  92. <li>
  93. The <a href="SWIGPlus.html#SWIGPlus_nspace">nspace feature</a> is also supported as described in this general section with a C# example.
  94. Unlike Java which requires the use of the -package option when using the <tt>nspace</tt> feature, the -namespace option is not mandatory for C#.
  95. </li>
  96. <li>
  97. The <tt>-dllimport &lt;name&gt;</tt> commandline option specifies the name of the DLL for the <tt>DllImport</tt> attribute for every PInvoke method. If this commandline option is not given, the <tt>DllImport</tt> DLL name is the same as the module name. This option is useful for when one wants to invoke SWIG multiple times on different modules, yet compile all the resulting code into a single DLL.
  98. </li>
  99. <li>
  100. C/C++ variables are wrapped with C# properties and not JavaBean style getters and setters.
  101. </li>
  102. <li>
  103. Global constants are generated into the module class. There is no constants interface.
  104. </li>
  105. <li>
  106. There is no implementation for type unsafe enums - not deemed necessary.
  107. </li>
  108. <li>
  109. The default enum wrapping approach is proper C# enums, not typesafe enums.
  110. <br>
  111. Note that %csconst(0) will be ignored when wrapping C/C++ enums with proper C# enums.
  112. This is because C# enum items must be initialised from a compile time constant.
  113. If an enum item has an initialiser and the initialiser doesn't compile as C# code,
  114. then the %csconstvalue directive must be used as %csconst(0) will have no effect.
  115. If it was used, it would generate an illegal runtime initialisation via a PInvoke call.
  116. </li>
  117. <li>
  118. C# doesn't support the notion of throws clauses.
  119. Therefore there is no 'throws' typemap attribute support for adding exception classes to a throws clause.
  120. Likewise there is no need for an equivalent to <tt>%javaexception</tt>.
  121. In fact, throwing C# exceptions works quite differently, see <a href="CSharp.html#CSharp_exceptions">C# Exceptions</a> below.
  122. </li>
  123. <li>
  124. The majority of the typemaps are in csharp.swg, not java.swg.
  125. </li>
  126. <li>
  127. <p>Typemap equivalent names:</p>
  128. <div class="code"><pre>
  129. jni -&gt; ctype
  130. jtype -&gt; imtype
  131. jstype -&gt; cstype
  132. javain -&gt; csin
  133. javaout -&gt; csout
  134. javadirectorin -&gt; csdirectorin
  135. javadirectorout -&gt; csdirectorout
  136. javainterfaces -&gt; csinterfaces and csinterfaces_derived
  137. javabase -&gt; csbase
  138. javaclassmodifiers -&gt; csclassmodifiers
  139. javacode -&gt; cscode
  140. javaimports -&gt; csimports
  141. javabody -&gt; csbody
  142. javafinalize -&gt; csfinalize
  143. javadestruct -&gt; csdestruct
  144. javadestruct_derived -&gt; csdestruct_derived
  145. </pre></div>
  146. </li>
  147. <li>
  148. <p>Typemap macros:</p>
  149. <div class="code"><pre>
  150. SWIG_JAVABODY_PROXY -&gt; SWIG_CSBODY_PROXY
  151. SWIG_JAVABODY_TYPEWRAPPER -&gt; SWIG_CSBODY_TYPEWRAPPER
  152. </pre></div>
  153. </li>
  154. <li>
  155. <p>Additional typemaps:</p>
  156. <div class="code"><pre>
  157. csvarin C# code property set typemap
  158. csvarout C# code property get typemap
  159. csattributes C# attributes for attaching to proxy classes/enums
  160. </pre></div>
  161. </li>
  162. <li>
  163. <p>Feature equivalent names:</p>
  164. <div class="code"><pre>
  165. %javaconst -&gt; %csconst
  166. %javaconstvalue -&gt; %csconstvalue
  167. %javamethodmodifiers -&gt; %csmethodmodifiers
  168. </pre></div>
  169. </li>
  170. <li>
  171. <p>Pragma equivalent names:</p>
  172. <div class="code"><pre>
  173. %pragma(java) -&gt; %pragma(csharp)
  174. jniclassbase -&gt; imclassbase
  175. jniclassclassmodifiers -&gt; imclassclassmodifiers
  176. jniclasscode -&gt; imclasscode
  177. jniclassimports -&gt; imclassimports
  178. jniclassinterfaces -&gt; imclassinterfaces
  179. </pre></div>
  180. </li>
  181. <li>
  182. <p>Special variable equivalent names:</p>
  183. <div class="code"><pre>
  184. $javaclassname -&gt; $csclassname
  185. $&amp;javaclassname -&gt; $&amp;csclassname
  186. $*javaclassname -&gt; $*csclassname
  187. $javaclazzname -&gt; $csclazzname
  188. $javainput -&gt; $csinput
  189. $jnicall -&gt; $imcall
  190. </pre></div>
  191. </li>
  192. <li>
  193. <p>
  194. Unlike the "javain" typemap, the "csin" typemap does not support the 'pgcpp' attribute as the C# module does not have a premature garbage collection prevention parameter.
  195. The "csin" typemap supports additional optional attributes called 'cshin' and 'terminator'.
  196. The 'cshin' attribute should contain the parameter type and name whenever a <a href="Java.html#Java_constructor_helper_function">constructor helper function</a> is generated due to the 'pre' or 'post' attributes.
  197. The 'terminator' attribute normally just contains a closing brace for when the 'pre' attribute contains an opening brace, such as when a C# <tt>using</tt> or <tt>fixed</tt> block is started.
  198. Note that 'pre', 'post', 'terminator' and 'cshin' attributes are not used for marshalling the property set.
  199. Please see the <a href="#CSharp_date_marshalling">Date marshalling example</a> and <a href="#CSharp_date_properties">Date marshalling of properties example</a> for further understanding of these "csin" applicable attributes.
  200. </p>
  201. </li>
  202. <li>
  203. <p>
  204. Support for asymmetric type marshalling. The 'ctype', 'imtype' and 'cstype' typemaps support an optional <tt>out</tt> attribute which is used for output types.
  205. If this typemap attribute is specified, then the type specified in the attribute is used for output types and
  206. the type specified in the typemap itself is used for the input type.
  207. If this typemap attribute is not specified, then the type used for both input and output is the type specified in the typemap.
  208. An example shows that <tt>char *</tt> could be marshalled in different ways,
  209. </p>
  210. <div class="code">
  211. <pre>
  212. %typemap(imtype, out="IntPtr") char * "string"
  213. char * function(char *);
  214. </pre>
  215. </div>
  216. <p>
  217. The output type is thus IntPtr and the input type is string. The resulting intermediary C# code is:
  218. </p>
  219. <div class="code">
  220. <pre>
  221. public static extern IntPtr function(string jarg1);
  222. </pre>
  223. </div>
  224. </li>
  225. <li>
  226. <p>
  227. Support for type attributes.
  228. The 'imtype' and 'cstype' typemaps can have an optional <tt>inattributes</tt> and <tt>outattributes</tt> typemap attribute.
  229. The 'imtype' typemap can also have an optional <tt>directorinattributes</tt> and <tt>directoroutattributes</tt>
  230. typemap attribute which attaches to director delegates, an implementation detail of directors, see <a href="#CSharp_directors_implementation">directors implementation</a>.
  231. Note that there are C# attributes and typemap attributes, don't get confused between the two!!
  232. The C# attributes specified in these typemap attributes are generated wherever the type is used in the C# wrappers.
  233. These can be used to specify any C# attribute associated with a C/C++ type, but are more typically used for the C# <tt>MarshalAs</tt> attribute.
  234. For example:
  235. </p>
  236. <div class="code">
  237. <pre>
  238. %typemap(imtype,
  239. inattributes="[MarshalAs(UnmanagedType.LPStr)]",
  240. outattributes="[return: MarshalAs(UnmanagedType.LPStr)]") const char * "String"
  241. const char * GetMsg() {}
  242. void SetMsg(const char *msg) {}
  243. </pre>
  244. </div>
  245. <p>
  246. The intermediary class will then have the marshalling as specified by everything in the 'imtype' typemap:
  247. </p>
  248. <div class="code">
  249. <pre>
  250. class examplePINVOKE {
  251. ...
  252. [DllImport("example", EntryPoint="CSharp_GetMsg")]
  253. [return: MarshalAs(UnmanagedType.LPStr)]
  254. public static extern String GetMsg();
  255. [DllImport("example", EntryPoint="CSharp_SetMsg")]
  256. public static extern void SetMsg([MarshalAs(UnmanagedType.LPStr)]String jarg1);
  257. }
  258. </pre>
  259. </div>
  260. <p>
  261. Note that the <tt>DllImport</tt> attribute is always generated, irrespective of any additional attributes specified.
  262. </p>
  263. <p>
  264. These attributes are associated with the C/C++ parameter type or return type, which is subtly different to
  265. the attribute features and typemaps covered next.
  266. Note that all these different C# attributes can be combined so that a method has more than one attribute.
  267. </p>
  268. <p>
  269. The <tt>directorinattributes</tt> and <tt>directoroutattributes</tt> typemap attribute are attached to the delegates in the director class, for example, the SwigDelegateBase_0
  270. </p>
  271. </li>
  272. <li>
  273. <p>
  274. Support for attaching C# attributes to wrapped methods, variables and enum values.
  275. This is done using the <tt>%csattributes</tt> feature, see <a href="Customization.html#Customization_features">%feature directives</a>.
  276. Note that C# attributes are attached to proxy classes and enums using the <tt>csattributes</tt> typemap.
  277. For example, imagine we have a custom attribute class, <tt>ThreadSafeAttribute</tt>, for labelling thread safety.
  278. The following SWIG code shows how to attach this C# attribute to some methods and the class declaration itself:
  279. </p>
  280. <div class="code">
  281. <pre>
  282. %typemap(csattributes) AClass "[ThreadSafe]"
  283. %csattributes AClass::AClass(double d) "[ThreadSafe(false)]"
  284. %csattributes AClass::AMethod() "[ThreadSafe(true)]"
  285. %inline %{
  286. class AClass {
  287. public:
  288. AClass(double a) {}
  289. void AMethod() {}
  290. };
  291. %}
  292. </pre>
  293. </div>
  294. <p>
  295. will generate a C# proxy class:
  296. </p>
  297. <div class="code">
  298. <pre>
  299. [ThreadSafe]
  300. public class AClass : IDisposable {
  301. ...
  302. [ThreadSafe(false)]
  303. public AClass(double a) ...
  304. [ThreadSafe(true)]
  305. public void AMethod() ...
  306. }
  307. </pre>
  308. </div>
  309. <p>
  310. If C# attributes need adding to the <tt>set</tt> or <tt>get</tt> part of C# properties, when wrapping C/C++ variables,
  311. they can be added using the 'csvarin' and 'csvarout' typemaps respectively.
  312. Note that the type used for the property is specified in the 'cstype' typemap.
  313. If the 'out' attribute exists in this typemap, then the type used is from the 'out' attribute.
  314. </p>
  315. <p>
  316. An example for attaching attributes to the enum and enum values is shown below.
  317. </p>
  318. <div class="code">
  319. <pre>
  320. %typemap(csattributes) Couleur "[System.ComponentModel.Description(\"Colours\")]"
  321. %csattributes Rouge "[System.ComponentModel.Description(\"Red\")]"
  322. %csattributes Vert "[System.ComponentModel.Description(\"Green\")]"
  323. %inline %{
  324. enum Couleur { Rouge, Orange, Vert };
  325. %}
  326. </pre>
  327. </div>
  328. <p>
  329. which will result in the following C# enum:
  330. </p>
  331. <div class="code">
  332. <pre>
  333. [System.ComponentModel.Description("Colours")]
  334. public enum Couleur {
  335. [System.ComponentModel.Description("Red")]
  336. Rouge,
  337. Orange,
  338. [System.ComponentModel.Description("Green")]
  339. Vert
  340. }
  341. </pre>
  342. </div>
  343. </li>
  344. <li>
  345. <p>
  346. The intermediary classname has <tt>PINVOKE</tt> appended after the module name instead of <tt>JNI</tt>, for example <tt>modulenamePINVOKE</tt>.
  347. </p>
  348. </li>
  349. <li>
  350. <p>
  351. The <tt>%csmethodmodifiers</tt> feature can also be applied to variables as well as methods.
  352. In addition to the default <tt>public</tt> modifier that SWIG generates when <tt>%csmethodmodifiers</tt> is not
  353. specified, the feature will also replace the <tt>virtual</tt>/<tt>new</tt>/<tt>override</tt> modifiers that SWIG thinks is appropriate.
  354. This feature is useful for some obscure cases where SWIG might get the <tt>virtual</tt>/<tt>new</tt>/<tt>override</tt> modifiers incorrect, for example with multiple inheritance.
  355. </p>
  356. </li>
  357. <li>
  358. <a name="CSharp_module_directive"></a>
  359. <p>
  360. The name of the intermediary class can be changed from its default, that is, the module name with PINVOKE appended after it.
  361. The module directive attribute <tt>imclassname</tt> is used to achieve this:
  362. </p>
  363. <div class="code">
  364. <pre>
  365. %module (imclassname="name") modulename
  366. </pre>
  367. </div>
  368. <p>
  369. If <tt>name</tt> is the same as <tt>modulename</tt> then the module class name gets changed
  370. from <tt>modulename</tt> to <tt>modulenameModule</tt>.
  371. </p>
  372. </li>
  373. <li>
  374. There is no additional 'premature garbage collection prevention parameter' as the marshalling of the <tt>HandleRef</tt> object
  375. takes care of ensuring a reference to the proxy class is held until the unmanaged call completed.
  376. </li>
  377. </ul>
  378. <p>
  379. <b><tt>$dllimport</tt></b><br>
  380. This is a C# only special variable that can be used in typemaps, pragmas, features etc.
  381. The special variable will get translated into the value specified by the <tt>-dllimport</tt> commandline option
  382. if specified, otherwise it is equivalent to the <b>$module</b> special variable.
  383. </p>
  384. <p>
  385. <b><tt>$imclassname</tt></b><br>
  386. This special variable expands to the intermediary class name. For C# this is usually the same as '$modulePINVOKE' ('$moduleJNI' for Java),
  387. unless the imclassname attribute is specified in the <a href="CSharp.html#CSharp_module_directive">%module directive</a>.
  388. </p>
  389. <p>
  390. The directory <tt>Examples/csharp</tt> has a number of simple examples.
  391. Visual Studio .NET 2003 solution and project files are available for compiling with the Microsoft .NET C# compiler on Windows.
  392. If your SWIG installation went well on a Unix environment and your C# compiler was detected, you should be able to type <tt>make</tt> in each example directory,
  393. then <tt>ilrun runme.exe</tt> (Portable.NET C# compiler) or <tt>mono runme.exe</tt> (Mono C# compiler) to run the examples.
  394. Windows users can also get the examples working using a
  395. <a href="http://www.cygwin.com">Cygwin</a> or <a href="http://www.mingw.org">MinGW</a> environment for automatic configuration of the example makefiles.
  396. Any one of the three C# compilers (Portable.NET, Mono or Microsoft) can be detected from within a Cygwin or Mingw environment if installed in your path.
  397. <H2><a name="CSharp_void_pointers"></a>19.3 Void pointers</H2>
  398. <p>
  399. By default SWIG treats <tt>void *</tt> as any other pointer and hence marshalls it as a type wrapper class called <tt>SWIGTYPE_p_void</tt>.
  400. If you want to marshall with the .NET <tt>System.IntPtr</tt> type instead, there is a simple set of named typemaps called
  401. <tt>void *VOID_INT_PTR</tt> that can be used.
  402. They can be applied like any other named typemaps:
  403. </p>
  404. <div class="code">
  405. <pre>
  406. %apply void *VOID_INT_PTR { void * }
  407. void * f(void *v);
  408. </pre>
  409. </div>
  410. <H2><a name="CSharp_arrays"></a>19.4 C# Arrays</H2>
  411. <p>
  412. There are various ways to pass arrays from C# to C/C++.
  413. The default wrapping treats arrays as pointers and as such simple type wrapper classes are generated,
  414. eg <tt>SWIGTYPE_p_int</tt> when wrapping the C type <tt>int []</tt> or <tt>int *</tt>.
  415. This gives a rather restricted use of the underlying unmanaged code and the most practical way to use arrays is to enhance or customise
  416. with one of the following three approaches; namely the SWIG C arrays library, P/Invoke default array marshalling or
  417. pinned arrays.
  418. </p>
  419. <H3><a name="CSharp_arrays_swig_library"></a>19.4.1 The SWIG C arrays library</H3>
  420. <p>
  421. The C arrays library keeps all the array memory in the unmanaged layer.
  422. The library is available to all language modules and is documented in the <a href="Library.html#Library_carrays">carrays.i library</a> section.
  423. Please refer to this section for details, but for convenience, the C# usage for the two examples outlined there is shown below.
  424. </p>
  425. <p>
  426. For the <tt>%array_functions</tt> example, the equivalent usage would be:
  427. </p>
  428. <div class="code">
  429. <pre>
  430. SWIGTYPE_p_double a = example.new_doubleArray(10); // Create an array
  431. for (int i=0; i&lt;10; i++)
  432. example.doubleArray_setitem(a,i,2*i); // Set a value
  433. example.print_array(a); // Pass to C
  434. example.delete_doubleArray(a); // Destroy array
  435. </pre>
  436. </div>
  437. <p>
  438. and for the <tt>%array_class</tt> example, the equivalent usage would be:
  439. </p>
  440. <div class="code">
  441. <pre>
  442. doubleArray c = new doubleArray(10); // Create double[10]
  443. for (int i=0; i&lt;10; i++)
  444. c.setitem(i, 2*i); // Assign values
  445. example.print_array(c.cast()); // Pass to C
  446. </pre>
  447. </div>
  448. <H3><a name="CSharp_arrays_pinvoke_default_array_marshalling"></a>19.4.2 Managed arrays using P/Invoke default array marshalling</H3>
  449. <p>
  450. In the P/Invoke default marshalling scheme, one needs to designate whether the invoked function will treat a managed
  451. array parameter as input, output, or both. When the function is invoked, the CLR allocates a separate chunk of memory as big as the given managed array,
  452. which is automatically released at the end of the function call. If the array parameter is marked as being input, the content of the managed array is copied
  453. into this buffer when the call is made. Correspondingly, if the array parameter is marked as being output, the contents of the reserved buffer are copied
  454. back into the managed array after the call returns. A pointer to this buffer
  455. is passed to the native function.
  456. </p>
  457. <p>
  458. The reason for allocating a separate buffer is to leave the CLR free to relocate the managed array object
  459. during garbage collection. If the overhead caused by the copying is causing a significant performance penalty, consider pinning the managed array and
  460. passing a direct reference as described in the next section.
  461. </p>
  462. <p>
  463. For more information on the subject, see the
  464. <a href="http://msdn.microsoft.com/en-us/library/z6cfh6e6(VS.80).aspx">Default Marshaling for Arrays</a> article
  465. on MSDN.
  466. </p>
  467. <p>
  468. The P/Invoke default marshalling is supported by the <tt>arrays_csharp.i</tt> library via the INPUT, OUTPUT and INOUT typemaps.
  469. Let's look at some example usage. Consider the following C function:
  470. </p>
  471. <div class="code">
  472. <pre>
  473. void myArrayCopy(int *sourceArray, int *targetArray, int nitems);
  474. </pre>
  475. </div>
  476. <p>
  477. We can now instruct SWIG to use the default marshalling typemaps by
  478. </p>
  479. <div class="code">
  480. <pre>
  481. %include "arrays_csharp.i"
  482. %apply int INPUT[] {int *sourceArray}
  483. %apply int OUTPUT[] {int *targetArray}
  484. </pre>
  485. </div>
  486. <p>
  487. As a result, we get the following method in the module class:
  488. </p>
  489. <div class="code">
  490. <pre>
  491. public static void myArrayCopy(int[] sourceArray, int[] targetArray, int nitems) {
  492. examplePINVOKE.myArrayCopy(sourceArray, targetArray, nitems);
  493. }
  494. </pre>
  495. </div>
  496. <p>
  497. If we look beneath the surface at the corresponding intermediary class code, we see
  498. that SWIG has generated code that uses attributes
  499. (from the System.Runtime.InteropServices namespace) to tell the CLR to use default
  500. marshalling for the arrays:
  501. </p>
  502. <div class="code">
  503. <pre>
  504. [DllImport("example", EntryPoint="CSharp_myArrayCopy")]
  505. public static extern void myArrayCopy([In, MarshalAs(UnmanagedType.LPArray)]int[] jarg1,
  506. [Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
  507. int jarg3);
  508. </pre>
  509. </div>
  510. <p>
  511. As an example of passing an inout array (i.e. the target function will both read from and
  512. write to the array), consider this C function that swaps a given number of elements
  513. in the given arrays:
  514. </p>
  515. <div class="code">
  516. <pre>
  517. void myArraySwap(int *array1, int *array2, int nitems);
  518. </pre>
  519. </div>
  520. <p>
  521. Now, we can instruct SWIG to wrap this by
  522. </p>
  523. <div class="code">
  524. <pre>
  525. %include "arrays_csharp.i"
  526. %apply int INOUT[] {int *array1}
  527. %apply int INOUT[] {int *array2}
  528. </pre>
  529. </div>
  530. <p>
  531. This results in the module class method
  532. </p>
  533. <div class="code">
  534. <pre>
  535. public static void myArraySwap(int[] array1, int[] array2, int nitems) {
  536. examplePINVOKE.myArraySwap(array1, array2, nitems);
  537. }
  538. </pre>
  539. </div>
  540. <p>
  541. and intermediary class method
  542. </p>
  543. <div class="code">
  544. <pre>
  545. [DllImport("example", EntryPoint="CSharp_myArraySwap")]
  546. public static extern void myArraySwap([In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg1,
  547. [In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
  548. int jarg3);
  549. </pre>
  550. </div>
  551. <H3><a name="CSharp_arrays_pinning"></a>19.4.3 Managed arrays using pinning</H3>
  552. <p>
  553. It is also possible to pin a given array in memory (i.e. fix its location in memory), obtain a
  554. direct pointer to it, and then pass this pointer to the wrapped C/C++ function. This approach
  555. involves no copying, but it makes the work of the garbage collector harder as
  556. the managed array object can not be relocated before the fix on the array is released. You should avoid
  557. fixing arrays in memory in cases where the control may re-enter the managed side via a callback and/or
  558. another thread may produce enough garbage to trigger garbage collection.
  559. </p>
  560. <p>
  561. For more information, see the <a href="http://msdn.microsoft.com/en-us/library/f58wzh21(VS.80).aspx">fixed statement</a> in the C# language reference.
  562. </p>
  563. <p>
  564. Now let's look at an example using pinning, thus avoiding the CLR making copies
  565. of the arrays passed as parameters. The <tt>arrays_csharp.i</tt> library file again provides the required support via the <tt>FIXED</tt> typemaps.
  566. Let's use the same function from the previous section:
  567. </p>
  568. <div class="code">
  569. <pre>
  570. void myArrayCopy(int *sourceArray, int *targetArray, int nitems);
  571. </pre>
  572. </div>
  573. <p>
  574. We now need to declare the module class method unsafe, as we are using pointers:
  575. </p>
  576. <div class="code">
  577. <pre>
  578. %csmethodmodifiers myArrayCopy "public unsafe";
  579. </pre>
  580. </div>
  581. <p>
  582. Apply the appropriate typemaps to the array parameters:
  583. </p>
  584. <div class="code">
  585. <pre>
  586. %include "arrays_csharp.i"
  587. %apply int FIXED[] {int *sourceArray}
  588. %apply int FIXED[] {int *targetArray}
  589. </pre>
  590. </div>
  591. <p>
  592. Notice that there is no need for separate in, out or inout typemaps as is the
  593. case when using P/Invoke default marshalling.
  594. </p>
  595. <p>
  596. As a result, we get the following method in the module class:
  597. </p>
  598. <div class="code">
  599. <pre>
  600. public unsafe static void myArrayCopy(int[] sourceArray, int[] targetArray, int nitems) {
  601. fixed ( int *swig_ptrTo_sourceArray = sourceArray ) {
  602. fixed ( int *swig_ptrTo_targetArray = targetArray ) {
  603. {
  604. examplePINVOKE.myArrayCopy((IntPtr)swig_ptrTo_sourceArray, (IntPtr)swig_ptrTo_targetArray,
  605. nitems);
  606. }
  607. }
  608. }
  609. }
  610. </pre>
  611. </div>
  612. <p>
  613. On the method signature level the only difference to the version using P/Invoke default
  614. marshalling is the "unsafe" quantifier, which is required because we are handling pointers.
  615. </p>
  616. <p>
  617. Also the intermediary class method looks a little different from the default marshalling
  618. example - the method is expecting an IntPtr as the parameter type.
  619. </p>
  620. <div class="code">
  621. <pre>
  622. [DllImport("example", EntryPoint="CSharp_myArrayCopy")]
  623. public static extern void myArrayCopy(IntPtr jarg1, IntPtr jarg2, int jarg3);
  624. </pre>
  625. </div>
  626. <H2><a name="CSharp_exceptions"></a>19.5 C# Exceptions</H2>
  627. <p>
  628. It is possible to throw a C# Exception from C/C++ code.
  629. SWIG already provides the framework for throwing C# exceptions if it is able to detect that a C++ exception could be thrown.
  630. Automatically detecting that a C++ exception could be thrown is only possible when a C++ exception specification is used,
  631. see <a href="SWIGPlus.html#SWIGPlus_exception_specifications">Exception specifications</a>.
  632. The <a href="Customization.html#Customization_exception">Exception handling with %exception</a> section details the <tt>%exception</tt> feature.
  633. Customised code for handling exceptions with or without a C++ exception specification is possible and the details follow.
  634. However anyone wishing to do this should be familiar with the contents of the sections referred to above.
  635. </p>
  636. <p>
  637. Unfortunately a C# exception cannot simply be thrown from unmanaged code for a variety of reasons.
  638. Most notably being that throwing a C# exception results in exceptions being thrown across the C PInvoke interface and C does not understand exceptions.
  639. The design revolves around a C# exception being constructed and stored as a pending exception, to be thrown only when the unmanaged code has completed.
  640. Implementing this is a tad involved and there are thus some unusual typemap constructs.
  641. Some practical examples follow and they should be read in conjunction with the rest of this section.
  642. </p>
  643. <p>
  644. First some details about the design that must be followed.
  645. Each typemap or feature that generates <b>unmanaged code</b> supports an attribute called <tt>canthrow</tt>.
  646. This is simply a flag which when set indicates that the code in the typemap/feature has code which might want to throw a C# exception.
  647. The code in the typemap/feature can then raise a C# exception by calling one of the C functions,
  648. <tt>SWIG_CSharpSetPendingException()</tt> or <tt>SWIG_CSharpSetPendingExceptionArgument()</tt>.
  649. When called, the function makes a callback into the managed world via a delegate.
  650. The callback creates and stores an exception ready for throwing when the unmanaged code has finished.
  651. The typemap/feature unmanaged code is then expected to force an immediate return from the unmanaged wrapper function,
  652. so that the pending managed exception can then be thrown.
  653. The support code has been carefully designed to be efficient as well as thread-safe.
  654. However to achieve the goal of efficiency requires some optional code generation in the <b>managed code</b> typemaps.
  655. Code to check for pending exceptions is generated if and only if the unmanaged code has code to set a pending exception,
  656. that is if the <tt>canthrow</tt> attribute is set.
  657. The optional managed code is generated using the <tt>excode</tt> typemap attribute and <tt>$excode</tt> special variable in the relevant managed code typemaps.
  658. Simply, if any relevant unmanaged code has the <tt>canthrow</tt> attribute set, then any occurrences of <tt>$excode</tt>
  659. is replaced with the code in the <tt>excode</tt> attribute.
  660. If the <tt>canthrow</tt> attribute is not set, then any occurrences of <tt>$excode</tt> are replaced with nothing.
  661. </p>
  662. <p>
  663. The prototypes for the <tt>SWIG_CSharpSetPendingException()</tt> and <tt>SWIG_CSharpSetPendingExceptionArgument()</tt> functions are
  664. </p>
  665. <div class="code">
  666. <pre>
  667. static void SWIG_CSharpSetPendingException(SWIG_CSharpExceptionCodes code,
  668. const char *msg);
  669. static void SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpExceptionArgumentCodes code,
  670. const char *msg,
  671. const char *param_name);
  672. </pre>
  673. </div>
  674. <p>
  675. The first parameter defines which .NET exceptions can be thrown:
  676. </p>
  677. <div class="code">
  678. <pre>
  679. typedef enum {
  680. SWIG_CSharpApplicationException,
  681. SWIG_CSharpArithmeticException,
  682. SWIG_CSharpDivideByZeroException,
  683. SWIG_CSharpIndexOutOfRangeException,
  684. SWIG_CSharpInvalidCastException,
  685. SWIG_CSharpInvalidOperationException,
  686. SWIG_CSharpIOException,
  687. SWIG_CSharpNullReferenceException,
  688. SWIG_CSharpOutOfMemoryException,
  689. SWIG_CSharpOverflowException,
  690. SWIG_CSharpSystemException
  691. } SWIG_CSharpExceptionCodes;
  692. typedef enum {
  693. SWIG_CSharpArgumentException,
  694. SWIG_CSharpArgumentNullException,
  695. SWIG_CSharpArgumentOutOfRangeException,
  696. } SWIG_CSharpExceptionArgumentCodes;
  697. </pre>
  698. </div>
  699. <p>
  700. where, for example, <tt>SWIG_CSharpApplicationException</tt> corresponds to the .NET exception, <tt>ApplicationException</tt>.
  701. The <tt>msg</tt> and <tt>param_name</tt> parameters contain the C# exception message and parameter name associated with the exception.
  702. </p>
  703. <p>
  704. The <tt>%exception</tt> feature in C# has the <tt>canthrow</tt> attribute set.
  705. The <tt>%csnothrowexception</tt> feature is like <tt>%exception</tt>, but it does not have the <tt>canthrow</tt> attribute
  706. set so should only be used when a C# exception is not created.
  707. </p>
  708. <H3><a name="CSharp_exception_example_check_typemap"></a>19.5.1 C# exception example using "check" typemap</H3>
  709. <p>
  710. Lets say we have the following simple C++ method:
  711. </p>
  712. <div class="code">
  713. <pre>
  714. void positivesonly(int number);
  715. </pre>
  716. </div>
  717. <p>
  718. and we want to check that the input <tt>number</tt> is always positive and if not throw a C# <tt>ArgumentOutOfRangeException</tt>.
  719. The "check" typemap is designed for checking input parameters. Below you will see the <tt>canthrow</tt> attribute is set because
  720. the code contains a call to <tt>SWIG_CSharpSetPendingExceptionArgument()</tt>. The full example follows:
  721. </p>
  722. <div class="code">
  723. <pre>
  724. %module example
  725. %typemap(check, canthrow=1) int number %{
  726. if ($1 &lt; 0) {
  727. SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
  728. "only positive numbers accepted", "number");
  729. return $null;
  730. }
  731. // SWIGEXCODE is a macro used by many other csout typemaps
  732. %define SWIGEXCODE
  733. "\n if ($modulePINVOKE.SWIGPendingException.Pending)"
  734. "\n throw $modulePINVOKE.SWIGPendingException.Retrieve();"
  735. %enddef
  736. %typemap(csout, excode=SWIGEXCODE) void {
  737. $imcall;$excode
  738. }
  739. %}
  740. %inline %{
  741. void positivesonly(int number) {
  742. }
  743. %}
  744. </pre>
  745. </div>
  746. <p>
  747. When the following C# code is executed:
  748. </p>
  749. <div class="code">
  750. <pre>
  751. public class runme {
  752. static void Main() {
  753. example.positivesonly(-1);
  754. }
  755. }
  756. </pre>
  757. </div>
  758. <p>
  759. The exception is thrown:
  760. </p>
  761. <div class="code">
  762. <pre>
  763. Unhandled Exception: System.ArgumentOutOfRangeException: only positive numbers accepted
  764. Parameter name: number
  765. in &lt;0x00034&gt; example:positivesonly (int)
  766. in &lt;0x0000c&gt; runme:Main ()
  767. </pre>
  768. </div>
  769. <p>
  770. Now let's analyse the generated code to gain a fuller understanding of the typemaps. The generated unmanaged C++ code is:
  771. </p>
  772. <div class="code">
  773. <pre>
  774. SWIGEXPORT void SWIGSTDCALL CSharp_positivesonly(int jarg1) {
  775. int arg1 ;
  776. arg1 = (int)jarg1;
  777. if (arg1 &lt; 0) {
  778. SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
  779. "only positive numbers accepted", "number");
  780. return ;
  781. }
  782. positivesonly(arg1);
  783. }
  784. </pre>
  785. </div>
  786. <p>
  787. This largely comes from the "check" typemap. The managed code in the module class is:
  788. </p>
  789. <div class="code">
  790. <pre>
  791. public class example {
  792. public static void positivesonly(int number) {
  793. examplePINVOKE.positivesonly(number);
  794. if (examplePINVOKE.SWIGPendingException.Pending)
  795. throw examplePINVOKE.SWIGPendingException.Retrieve();
  796. }
  797. }
  798. </pre>
  799. </div>
  800. <p>
  801. This comes largely from the "csout" typemap.
  802. </p>
  803. <p>
  804. The "csout" typemap is the same as the default void "csout" typemap so is not strictly necessary for the example.
  805. However, it is shown to demonstrate what managed output code typemaps should contain,
  806. that is, a <tt>$excode</tt> special variable and an <tt>excode</tt> attribute.
  807. Also note that <tt>$excode</tt> is expanded into the code held in the <tt>excode</tt> attribute.
  808. The <tt>$imcall</tt> as always expands into <tt>examplePINVOKE.positivesonly(number)</tt>.
  809. The exception support code in the intermediary class, <tt>examplePINVOKE</tt>, is not shown, but is contained within the inner classes,
  810. <tt>SWIGPendingException</tt> and <tt>SWIGExceptionHelper</tt> and is always generated.
  811. These classes can be seen in any of the generated wrappers.
  812. However, all that is required of a user is as demonstrated in the "csin" typemap above.
  813. That is, is to check <tt>SWIGPendingException.Pending</tt> and to throw the exception returned by <tt>SWIGPendingException.Retrieve()</tt>.
  814. </p>
  815. <p>
  816. If the "check" typemap did not exist, then
  817. the following module class would instead be generated:
  818. </p>
  819. <div class="code">
  820. <pre>
  821. public class example {
  822. public static void positivesonly(int number) {
  823. examplePINVOKE.positivesonly(number);
  824. }
  825. }
  826. </pre>
  827. </div>
  828. <p>
  829. Here we see the pending exception checking code is omitted.
  830. In fact, the code above would be generated if the <tt>canthrow</tt> attribute was not in the "check" typemap, such as:
  831. </p>
  832. <div class="code">
  833. <pre>
  834. %typemap(check) int number %{
  835. if ($1 &lt; 0) {
  836. SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
  837. "only positive numbers accepted", "number");
  838. return $null;
  839. }
  840. %}
  841. </pre>
  842. </div>
  843. <p>
  844. Note that if SWIG detects you have used <tt>SWIG_CSharpSetPendingException()</tt> or <tt>SWIG_CSharpSetPendingExceptionArgument()</tt>
  845. without setting the <tt>canthrow</tt> attribute you will get a warning message similar to
  846. </p>
  847. <div class="code">
  848. <pre>
  849. example.i:21: Warning 845: Unmanaged code contains a call to a SWIG_CSharpSetPendingException
  850. method and C# code does not handle pending exceptions via the canthrow attribute.
  851. </pre>
  852. </div>
  853. <p>
  854. Actually it will issue this warning for any function beginning with <tt>SWIG_CSharpSetPendingException</tt>.
  855. </P>
  856. <H3><a name="CSharp_exception_example_percent_exception"></a>19.5.2 C# exception example using %exception</H3>
  857. <p>
  858. Let's consider a similar, but more common example that throws a C++ exception from within a wrapped function.
  859. We can use <tt>%exception</tt> as mentioned in <a href="Customization.html#Customization_exception">Exception handling with %exception</a>.
  860. </p>
  861. <div class="code">
  862. <pre>
  863. %exception negativesonly(int value) %{
  864. try {
  865. $action
  866. } catch (std::out_of_range e) {
  867. SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
  868. }
  869. %}
  870. %inline %{
  871. #include &lt;stdexcept&gt;
  872. void negativesonly(int value) {
  873. if (value &gt;= 0)
  874. throw std::out_of_range("number should be negative");
  875. }
  876. %}
  877. </pre>
  878. </div>
  879. <p>
  880. The generated unmanaged code this time catches the C++ exception and converts it into a C# <tt>ApplicationException</tt>.
  881. </p>
  882. <div class="code">
  883. <pre>
  884. SWIGEXPORT void SWIGSTDCALL CSharp_negativesonly(int jarg1) {
  885. int arg1 ;
  886. arg1 = (int)jarg1;
  887. try {
  888. negativesonly(arg1);
  889. } catch (std::out_of_range e) {
  890. SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
  891. return ;
  892. }
  893. }
  894. </pre>
  895. </div>
  896. <p>
  897. The managed code generated does check for the pending exception as mentioned earlier as the C# version of <tt>%exception</tt> has the <tt>canthrow</tt> attribute set by default:
  898. </p>
  899. <div class="code">
  900. <pre>
  901. public static void negativesonly(int value) {
  902. examplePINVOKE.negativesonly(value);
  903. if (examplePINVOKE.SWIGPendingException.Pending)
  904. throw examplePINVOKE.SWIGPendingException.Retrieve();
  905. }
  906. </pre>
  907. </div>
  908. <H3><a name="CSharp_exception_example_exception_specifications"></a>19.5.3 C# exception example using exception specifications</H3>
  909. <p>
  910. When C++ exception specifications are used, SWIG is able to detect that the method might throw an exception.
  911. By default SWIG will automatically generate code to catch the exception and convert it into a managed <tt>ApplicationException</tt>,
  912. as defined by the default "throws" typemaps.
  913. The following example has a user supplied "throws" typemap which is used whenever an exception specification contains a <tt>std::out_of_range</tt>,
  914. such as the <tt>evensonly</tt> method below.
  915. </p>
  916. <div class="code">
  917. <pre>
  918. %typemap(throws, canthrow=1) std::out_of_range {
  919. SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, $1.what(), NULL);
  920. return $null;
  921. }
  922. %inline %{
  923. #include &lt;stdexcept&gt;
  924. void evensonly(int input) throw (std::out_of_range) {
  925. if (input%2 != 0)
  926. throw std::out_of_range("number is not even");
  927. }
  928. %}
  929. </pre>
  930. </div>
  931. <p>
  932. Note that the type for the throws typemap is the type in the exception specification.
  933. SWIG generates a try catch block with the throws typemap code in the catch handler.
  934. </p>
  935. <div class="code">
  936. <pre>
  937. SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) {
  938. int arg1 ;
  939. arg1 = (int)jarg1;
  940. try {
  941. evensonly(arg1);
  942. }
  943. catch(std::out_of_range &amp;_e) {
  944. {
  945. SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, (&amp;_e)-&gt;what(), NULL);
  946. return ;
  947. }
  948. }
  949. }
  950. </pre>
  951. </div>
  952. <p>
  953. Multiple catch handlers are generated should there be more than one exception specifications declared.
  954. </p>
  955. <H3><a name="CSharp_custom_application_exception"></a>19.5.4 Custom C# ApplicationException example</H3>
  956. <p>
  957. This example involves a user defined exception.
  958. The conventional .NET exception handling approach is to create a custom <tt>ApplicationException</tt> and throw it in your application.
  959. The goal in this example is to convert the STL <tt>std::out_of_range</tt> exception into one of these custom .NET exceptions.
  960. </p>
  961. <p>
  962. The default exception handling is quite easy to use as the <tt>SWIG_CSharpSetPendingException()</tt> and <tt>SWIG_CSharpSetPendingExceptionArgument()</tt>
  963. methods are provided by SWIG.
  964. However, for a custom C# exception, the boiler plate code that supports these functions needs replicating.
  965. In essence this consists of some C/C++ code and C# code.
  966. The C/C++ code can be generated into the wrapper file using the <tt>%insert(runtime)</tt> directive and
  967. the C# code can be generated into the intermediary class using the <tt>imclasscode</tt> pragma as follows:
  968. </p>
  969. <div class="code">
  970. <pre>
  971. %insert(runtime) %{
  972. // Code to handle throwing of C# CustomApplicationException from C/C++ code.
  973. // The equivalent delegate to the callback, CSharpExceptionCallback_t, is CustomExceptionDelegate
  974. // and the equivalent customExceptionCallback instance is customDelegate
  975. typedef void (SWIGSTDCALL* CSharpExceptionCallback_t)(const char *);
  976. CSharpExceptionCallback_t customExceptionCallback = NULL;
  977. extern "C" SWIGEXPORT
  978. void SWIGSTDCALL CustomExceptionRegisterCallback(CSharpExceptionCallback_t customCallback) {
  979. customExceptionCallback = customCallback;
  980. }
  981. // Note that SWIG detects any method calls named starting with
  982. // SWIG_CSharpSetPendingException for warning 845
  983. static void SWIG_CSharpSetPendingExceptionCustom(const char *msg) {
  984. customExceptionCallback(msg);
  985. }
  986. %}
  987. %pragma(csharp) imclasscode=%{
  988. class CustomExceptionHelper {
  989. // C# delegate for the C/C++ customExceptionCallback
  990. public delegate void CustomExceptionDelegate(string message);
  991. static CustomExceptionDelegate customDelegate =
  992. new CustomExceptionDelegate(SetPendingCustomException);
  993. [DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")]
  994. public static extern
  995. void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback);
  996. static void SetPendingCustomException(string message) {
  997. SWIGPendingException.Set(new CustomApplicationException(message));
  998. }
  999. static CustomExceptionHelper() {
  1000. CustomExceptionRegisterCallback(customDelegate);
  1001. }
  1002. }
  1003. static CustomExceptionHelper exceptionHelper = new CustomExceptionHelper();
  1004. %}
  1005. </pre>
  1006. </div>
  1007. <p>
  1008. The method stored in the C# delegate instance, <tt>customDelegate</tt> is what gets called by the C/C++ callback.
  1009. However, the equivalent to the C# delegate, that is the C/C++ callback, needs to be assigned before any unmanaged code is executed.
  1010. This is achieved by putting the initialisation code in the intermediary class.
  1011. Recall that the intermediary class contains all the PInvoke methods, so the static variables in the intermediary class will be initialised
  1012. before any of the PInvoke methods in this class are called.
  1013. The <tt>exceptionHelper</tt> static variable ensures the C/C++ callback is initialised with the value in <tt>customDelegate</tt> by calling
  1014. the <tt>CustomExceptionRegisterCallback</tt> method in the <tt>CustomExceptionHelper</tt> static constructor.
  1015. Once this has been done, unmanaged code can make callbacks into the managed world as <tt>customExceptionCallback</tt> will be initialised with a valid callback/delegate.
  1016. Any calls to <tt>SWIG_CSharpSetPendingExceptionCustom()</tt> will make the callback to create the pending exception in the same way that
  1017. <tt>SWIG_CSharpSetPendingException()</tt> and <tt>SWIG_CSharpSetPendingExceptionArgument()</tt> does.
  1018. In fact the method has been similarly named so that SWIG can issue the warning about missing <tt>canthrow</tt> attributes as discussed earlier.
  1019. It is an invaluable warning as it is easy to forget the <tt>canthrow</tt> attribute when writing typemaps/features.
  1020. </p>
  1021. <p>
  1022. The <tt>SWIGPendingException</tt> helper class is not shown, but is generated as an inner class into the intermediary class.
  1023. It stores the pending exception in Thread Local Storage so that the exception handling mechanism is thread safe.
  1024. </p>
  1025. <p>
  1026. The boiler plate code above must be used in addition to a handcrafted <tt>CustomApplicationException</tt>:
  1027. </p>
  1028. <div class="code">
  1029. <pre>
  1030. // Custom C# Exception
  1031. class CustomApplicationException : System.ApplicationException {
  1032. public CustomApplicationException(string message)
  1033. : base(message) {
  1034. }
  1035. }
  1036. </pre>
  1037. </div>
  1038. <p>
  1039. and the SWIG interface code:
  1040. </p>
  1041. <div class="code">
  1042. <pre>
  1043. %typemap(throws, canthrow=1) std::out_of_range {
  1044. SWIG_CSharpSetPendingExceptionCustom($1.what());
  1045. return $null;
  1046. }
  1047. %inline %{
  1048. void oddsonly(int input) throw (std::out_of_range) {
  1049. if (input%2 != 1)
  1050. throw std::out_of_range("number is not odd");
  1051. }
  1052. %}
  1053. </pre>
  1054. </div>
  1055. <p>
  1056. The "throws" typemap now simply calls our new <tt>SWIG_CSharpSetPendingExceptionCustom()</tt> function so that the exception can be caught, as such:
  1057. </p>
  1058. <div class="code">
  1059. <pre>
  1060. try {
  1061. example.oddsonly(2);
  1062. } catch (CustomApplicationException e) {
  1063. ...
  1064. }
  1065. </pre>
  1066. </div>
  1067. <H2><a name="CSharp_directors"></a>19.6 C# Directors</H2>
  1068. <p>
  1069. The SWIG directors feature adds extra code to the generated C# proxy classes that enable these classes to be used in cross-language polymorphism.
  1070. Essentially, it enables unmanaged C++ code to call back into managed code for virtual methods so that a C# class can derive from a wrapped C++ class.
  1071. </p>
  1072. <p>
  1073. The following sections provide information on the C# director implementation and contain most of the information required to use the C# directors.
  1074. However, the <a href="Java.html#Java_directors">Java directors</a> section should also be read in order to gain more insight into directors.
  1075. </p>
  1076. <H3><a name="CSharp_directors_example"></a>19.6.1 Directors example</H3>
  1077. <p>
  1078. Imagine we are wrapping a C++ base class, <tt>Base</tt>, from which we would like to inherit in C#.
  1079. Such a class is shown below as well as another class, <tt>Caller</tt>, which calls the virtual method <tt>UIntMethod</tt>
  1080. from pure unmanaged C++ code.
  1081. </p>
  1082. <div class="code">
  1083. <pre>
  1084. // file: example.h
  1085. class Base {
  1086. public:
  1087. virtual ~Base() {}
  1088. virtual unsigned int UIntMethod(unsigned int x) {
  1089. std::cout &lt;&lt; "Base - UIntMethod(" &lt;&lt; x &lt;&lt; ")" &lt;&lt; std::endl;
  1090. return x;
  1091. }
  1092. virtual void BaseBoolMethod(const Base &amp;b, bool flag) {}
  1093. };
  1094. class Caller {
  1095. public:
  1096. Caller(): m_base(0) {}
  1097. ~Caller() { delBase(); }
  1098. void set(Base *b) { delBase(); m_base = b; }
  1099. void reset() { m_base = 0; }
  1100. unsigned int UIntMethodCall(unsigned int x) { return m_base-&gt;UIntMethod(x); }
  1101. private:
  1102. Base *m_base;
  1103. void delBase() { delete m_base; m_base = 0; }
  1104. };
  1105. </pre>
  1106. </div>
  1107. <p>
  1108. The director feature is turned off by default and the following simple interface file shows how directors are enabled
  1109. for the class <tt>Base</tt>.
  1110. </p>
  1111. <div class="code">
  1112. <pre>
  1113. /* File : example.i */
  1114. %module(directors="1") example
  1115. %{
  1116. #include "example.h"
  1117. %}
  1118. %feature("director") Base;
  1119. %include "example.h"
  1120. </pre>
  1121. </div>
  1122. <p>
  1123. The following is a C# class inheriting from <tt>Base</tt>:
  1124. </p>
  1125. <div class="code">
  1126. <pre>
  1127. public class CSharpDerived : Base
  1128. {
  1129. public override uint UIntMethod(uint x)
  1130. {
  1131. Console.WriteLine("CSharpDerived - UIntMethod({0})", x);
  1132. return x;
  1133. }
  1134. }
  1135. </pre>
  1136. </div>
  1137. <p>
  1138. The <tt>Caller</tt> class can demonstrate the <tt>UIntMethod</tt> method being called from unmanaged code using the following C# code:
  1139. </p>
  1140. <div class="targetlang">
  1141. <pre>
  1142. public class runme
  1143. {
  1144. static void Main()
  1145. {
  1146. Caller myCaller = new Caller();
  1147. // Test pure C++ class
  1148. using (Base myBase = new Base())
  1149. {
  1150. makeCalls(myCaller, myBase);
  1151. }
  1152. // Test director / C# derived class
  1153. using (Base myBase = new CSharpDerived())
  1154. {
  1155. makeCalls(myCaller, myBase);
  1156. }
  1157. }
  1158. static void makeCalls(Caller myCaller, Base myBase)
  1159. {
  1160. myCaller.set(myBase);
  1161. myCaller.UIntMethodCall(123);
  1162. myCaller.reset();
  1163. }
  1164. }
  1165. </pre>
  1166. </div>
  1167. <p>
  1168. If the above is run, the output is then:
  1169. </p>
  1170. <div class="shell">
  1171. <pre>
  1172. Base - UIntMethod(123)
  1173. CSharpDerived - UIntMethod(123)
  1174. </pre>
  1175. </div>
  1176. <H3><a name="CSharp_directors_implementation"></a>19.6.2 Directors implementation</H3>
  1177. <p>
  1178. The previous section demonstrated a simple example where the virtual <tt>UIntMethod</tt> method was called from
  1179. C++ code, even when the overridden method is implemented in C#.
  1180. The intention of this section is to gain an insight into how the director feature works.
  1181. It shows the generated code for the two virtual methods, <tt>UIntMethod</tt> and <tt>BaseBoolMethod</tt>,
  1182. when the director feature is enabled for the <tt>Base</tt> class.
  1183. </p>
  1184. <p>
  1185. Below is the generated C# <tt>Base</tt> director class.
  1186. </p>
  1187. <div class="code">
  1188. <pre>
  1189. using System;
  1190. using System.Runtime.InteropServices;
  1191. public class Base : IDisposable {
  1192. private HandleRef swigCPtr;
  1193. protected bool swigCMemOwn;
  1194. internal Base(IntPtr cPtr, bool cMemoryOwn) {
  1195. swigCMemOwn = cMemoryOwn;
  1196. swigCPtr = new HandleRef(this, cPtr);
  1197. }
  1198. internal static HandleRef getCPtr(Base obj) {
  1199. return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
  1200. }
  1201. ~Base() {
  1202. Dispose();
  1203. }
  1204. public virtual void Dispose() {
  1205. lock(this) {
  1206. if(swigCPtr.Handle != IntPtr.Zero &amp;&amp; swigCMemOwn) {
  1207. swigCMemOwn = false;
  1208. examplePINVOKE.delete_Base(swigCPtr);
  1209. }
  1210. swigCPtr = new HandleRef(null, IntPtr.Zero);
  1211. GC.SuppressFinalize(this);
  1212. }
  1213. }
  1214. public virtual uint UIntMethod(uint x) {
  1215. uint ret = examplePINVOKE.Base_UIntMethod(swigCPtr, x);
  1216. return ret;
  1217. }
  1218. public virtual void BaseBoolMethod(Base b, bool flag) {
  1219. examplePINVOKE.Base_BaseBoolMethod(swigCPtr, Base.getCPtr(b), flag);
  1220. if (examplePINVOKE.SWIGPendingException.Pending)
  1221. throw examplePINVOKE.SWIGPendingException.Retrieve();
  1222. }
  1223. public Base() : this(examplePINVOKE.new_Base(), true) {
  1224. SwigDirectorConnect();
  1225. }
  1226. private void SwigDirectorConnect() {
  1227. if (SwigDerivedClassHasMethod("UIntMethod", swigMethodTypes0))
  1228. swigDelegate0 = new SwigDelegateBase_0(SwigDirectorUIntMethod);
  1229. if (SwigDerivedClassHasMethod("BaseBoolMethod", swigMethodTypes1))
  1230. swigDelegate1 = new SwigDelegateBase_1(SwigDirectorBaseBoolMethod);
  1231. examplePINVOKE.Base_director_connect(swigCPtr, swigDelegate0, swigDelegate1);
  1232. }
  1233. private bool SwigDerivedClassHasMethod(string methodName, Type[] methodTypes) {
  1234. System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, methodTypes);
  1235. bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(Base));
  1236. return hasDerivedMethod;
  1237. }
  1238. private uint SwigDirectorUIntMethod(uint x) {
  1239. return UIntMethod(x);
  1240. }
  1241. private void SwigDirectorBaseBoolMethod(IntPtr b, bool flag) {
  1242. BaseBoolMethod(new Base(b, false), flag);
  1243. }
  1244. internal delegate uint SwigDelegateBase_0(uint x);
  1245. internal delegate void SwigDelegateBase_1(IntPtr b, bool flag);
  1246. private SwigDelegateBase_0 swigDelegate0;
  1247. private SwigDelegateBase_1 swigDelegate1;
  1248. private static Type[] swigMethodTypes0 = new Type[] { typeof(uint) };
  1249. private static Type[] swigMethodTypes1 = new Type[] { typeof(Base), typeof(bool) };
  1250. }
  1251. </pre>
  1252. </div>
  1253. <p>
  1254. Everything from the <tt>SwigDirectorConnect()</tt> method and below is code that is only generated when
  1255. directors are enabled.
  1256. The design comprises a C# delegate being initialised for each virtual method on construction of the class.
  1257. Let's examine the <tt>BaseBoolMethod</tt>.
  1258. </p>
  1259. <p>
  1260. In the <tt>Base</tt> constructor a call is made to <tt>SwigDirectorConnect()</tt> which contains the initialisation code for all the virtual methods.
  1261. It uses a support method, <tt>SwigDerivedClassHasMethod()</tt>, which simply uses reflection to determine if the named method,
  1262. BaseBoolMethod, with the list of required parameter types, exists in a subclass.
  1263. If it does not exist, the delegate is not initialised as there is no need for unmanaged code to call back into managed C# code.
  1264. However, if there is an overridden method in any subclass, the delegate is required.
  1265. It is then initialised to the <tt>SwigDirectorBaseBoolMethod</tt> which in turn will call <tt>BaseBoolMethod</tt> if invoked.
  1266. The delegate is not initialised to the <tt>BaseBoolMethod</tt> directly as quite often types will need marshalling from the unmanaged type
  1267. to the managed type in which case an intermediary method (<tt>SwigDirectorBaseBoolMethod</tt>) is required for the marshalling.
  1268. In this case, the C# <tt>Base</tt> class needs to be created from the unmanaged <tt>IntPtr</tt> type.
  1269. </p>
  1270. <p>
  1271. The last thing that <tt>SwigDirectorConnect()</tt> does is to pass the delegates to the unmanaged code.
  1272. It calls the intermediary method <tt>Base_director_connect()</tt> which is really a call to the C function <tt>CSharp_Base_director_connect()</tt>.
  1273. This method simply maps each C# delegate onto a C function pointer.
  1274. </p>
  1275. <div class="code">
  1276. <pre>
  1277. SWIGEXPORT void SWIGSTDCALL CSharp_Base_director_connect(void *objarg,
  1278. SwigDirector_Base::SWIG_Callback0_t callback0,
  1279. SwigDirector_Base::SWIG_Callback1_t callback1) {
  1280. Base *obj = (Base *)objarg;
  1281. SwigDirector_Base *director = dynamic_cast&lt;SwigDirector_Base *&gt;(obj);
  1282. if (director) {
  1283. director-&gt;swig_connect_director(callback0, callback1);
  1284. }
  1285. }
  1286. class SwigDirector_Base : public Base, public Swig::Director {
  1287. public:
  1288. SwigDirector_Base();
  1289. virtual unsigned int UIntMethod(unsigned int x);
  1290. virtual ~SwigDirector_Base();
  1291. virtual void BaseBoolMethod(Base const &amp;b, bool flag);
  1292. typedef unsigned int (SWIGSTDCALL* SWIG_Callback0_t)(unsigned int);
  1293. typedef void (SWIGSTDCALL* SWIG_Callback1_t)(void *, unsigned int);
  1294. void swig_connect_director(SWIG_Callback0_t callbackUIntMethod,
  1295. SWIG_Callback1_t callbackBaseBoolMethod);
  1296. private:
  1297. SWIG_Callback0_t swig_callbackUIntMethod;
  1298. SWIG_Callback1_t swig_callbackBaseBoolMethod;
  1299. void swig_init_callbacks();
  1300. };
  1301. void SwigDirector_Base::swig_connect_director(SWIG_Callback0_t callbackUIntMethod,
  1302. SWIG_Callback1_t callbackBaseBoolMethod) {
  1303. swig_callbackUIntMethod = callbackUIntMethod;
  1304. swig_callbackBaseBoolMethod = callbackBaseBoolMethod;
  1305. }
  1306. </pre>
  1307. </div>
  1308. <p>
  1309. Note that for each director class SWIG creates an unmanaged director class for making the callbacks. For example <tt>Base</tt> has <tt>SwigDirector_Base</tt> and <tt>SwigDirector_Base</tt>
  1310. is derived from <tt>Base</tt>.
  1311. Should a C# class be derived from <tt>Base</tt>, the underlying C++ <tt>SwigDirector_Base</tt> is created rather than <tt>Base</tt>.
  1312. The <tt>SwigDirector_Base</tt> class then implements all the virtual methods, redirecting calls up to managed code if the callback/delegate is non-zero.
  1313. The implementation of <tt>SwigDirector_Base::BaseBoolMethod</tt> shows this - the callback is made by invoking the <tt>swig_callbackBaseBoolMethod</tt> function pointer:
  1314. </p>
  1315. <div class="code">
  1316. <pre>
  1317. void SwigDirector_Base::BaseBoolMethod(Base const &amp;b, bool flag) {
  1318. void * jb = 0 ;
  1319. unsigned int jflag ;
  1320. if (!swig_callbackBaseBoolMethod) {
  1321. Base::BaseBoolMethod(b,flag);
  1322. return;
  1323. } else {
  1324. jb = (Base *) &amp;b;
  1325. jflag = flag;
  1326. swig_callbackBaseBoolMethod(jb, jflag);
  1327. }
  1328. }
  1329. </pre>
  1330. </div>
  1331. <H3><a name="CSharp_director_caveats"></a>19.6.3 Director caveats</H3>
  1332. <p>
  1333. There is a subtle gotcha with directors.
  1334. If default parameters are used, it is recommended to follow a pattern of always calling a single method in any C# derived class.
  1335. An example will clarify this and the reasoning behind the recommendation. Consider the following C++ class wrapped as a director class:
  1336. </p>
  1337. <div class="code">
  1338. <pre>
  1339. class Defaults {
  1340. public:
  1341. virtual ~Defaults();
  1342. virtual void DefaultMethod(int a=-100);
  1343. };
  1344. </pre>
  1345. </div>
  1346. <p>
  1347. Recall that C++ methods with default parameters generate overloaded methods for each defaulted parameter, so a C# derived class can be created
  1348. with two <tt>DefaultMethod</tt> override methods:
  1349. </p>
  1350. <div class="code">
  1351. <pre>
  1352. public class CSharpDefaults : Defaults
  1353. {
  1354. public override void DefaultMethod()
  1355. {
  1356. DefaultMethod(-100); // note C++ default value used
  1357. }
  1358. public override void DefaultMethod(int x)
  1359. {
  1360. }
  1361. }
  1362. </pre>
  1363. </div>
  1364. <p>
  1365. It may not be clear at first, but should a user intend to call <tt>CSharpDefaults.DefaultMethod()</tt> from C++, a call is actually made to <tt>CSharpDefaults.DefaultMethod(int)</tt>.
  1366. This is because the initial call is made in C++ and therefore the <tt>DefaultMethod(int)</tt> method will be called as is expected with C++ calls to methods with defaults,
  1367. with the default being set to -100.
  1368. The callback/delegate matching this method is of course the overloaded method <tt>DefaultMethod(int)</tt>.
  1369. However, a call from C# to <tt>CSharpDefaults.DefaultMethod()</tt> will of course call this exact method and in order for behaviour to be consistent with calls from C++, the implementation
  1370. should pass the call on to <tt>CSharpDefaults.DefaultMethod(int)</tt>using the C++ default value, as shown above.
  1371. </p>
  1372. <H2><a name="CSharp_multiple_modules"></a>19.7 Multiples modules</H2>
  1373. <p>
  1374. When using <a href="Modules.html">multiple modules</a> it is is possible to compile each SWIG generated wrapper
  1375. into a different assembly.
  1376. However, by default the generated code may not compile if
  1377. generated classes in one assembly use generated classes in another assembly.
  1378. The visibility of the
  1379. <tt>getCPtr()</tt> and pointer constructor generated from the <tt>csbody</tt> typemaps needs changing.
  1380. The default visibility is <tt>internal</tt> but it needs to be <tt>public</tt> for access from a different assembly.
  1381. Just changing 'internal' to 'public' in the typemap achieves this.
  1382. Two macros are available in <tt>csharp.swg</tt> to make this easier and using them is the preferred approach
  1383. over simply copying the typemaps and modifying as this is forward compatible with any changes in
  1384. the <tt>csbody</tt> typemap in future versions of SWIG.
  1385. The macros are for the proxy and typewrapper classes and can respectively be used to
  1386. to make the method and constructor public:
  1387. </p>
  1388. <div class="code">
  1389. <pre>
  1390. SWIG_CSBODY_PROXY(public, public, SWIGTYPE)
  1391. SWIG_CSBODY_TYPEWRAPPER(public, public, public, SWIGTYPE)
  1392. </pre>
  1393. </div>
  1394. <p>
  1395. Alternatively, instead of exposing these as public, consider
  1396. using the <tt>[assembly:InternalsVisibleTo("Name")]</tt> attribute available in the .NET framework when you
  1397. know which assemblies these can be exposed to.
  1398. Another approach would be to make these public, but also to hide them from intellisense by using
  1399. the <tt>[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]</tt> attribute
  1400. if you don't want users to easily stumble upon these so called 'internal workings' of the wrappers.
  1401. </p>
  1402. <H2><a name="CSharp_typemap_examples"></a>19.8 C# Typemap examples</H2>
  1403. This section includes a few examples of typemaps. For more examples, you
  1404. might look at the files "<tt>csharp.swg</tt>" and "<tt>typemaps.i</tt>" in
  1405. the SWIG library.
  1406. <H3><a name="CSharp_memory_management_member_variables"></a>19.8.1 Memory management when returning references to member variables</H3>
  1407. <p>
  1408. This example shows how to prevent premature garbage collection of objects when the underlying C++ class returns a pointer or reference to a member variable.
  1409. The example is a direct equivalent to this <a href="Java.html#Java_memory_management_objects">Java equivalent</a>.
  1410. </p>
  1411. <p>
  1412. Consider the following C++ code:
  1413. </p>
  1414. <div class="code">
  1415. <pre>
  1416. struct Wheel {
  1417. int size;
  1418. Wheel(int sz) : size(sz) {}
  1419. };
  1420. class Bike {
  1421. Wheel wheel;
  1422. public:
  1423. Bike(int val) : wheel(val) {}
  1424. Wheel&amp; getWheel() { return wheel; }
  1425. };
  1426. </pre>
  1427. </div>
  1428. <p>
  1429. and the following usage from C# after running the code through SWIG:
  1430. </p>
  1431. <div class="code">
  1432. <pre>
  1433. Wheel wheel = new Bike(10).getWheel();
  1434. Console.WriteLine("wheel size: " + wheel.size);
  1435. // Simulate a garbage collection
  1436. System.GC.Collect();
  1437. System.GC.WaitForPendingFinalizers();
  1438. Console.WriteLine("wheel size: " + wheel.size);
  1439. </pre>
  1440. </div>
  1441. <p>
  1442. Don't be surprised that if the resulting output gives strange results such as...
  1443. </p>
  1444. <div class="shell">
  1445. <pre>
  1446. wheel size: 10
  1447. wheel size: 135019664
  1448. </pre>
  1449. </div>
  1450. <p>
  1451. What has happened here is the garbage collector has collected the <tt>Bike</tt> instance as it doesn't think it is needed any more.
  1452. The proxy instance, <tt>wheel</tt>, contains a reference to memory that was deleted when the <tt>Bike</tt> instance was collected.
  1453. In order to prevent the garbage collector from collecting the <tt>Bike</tt> instance a reference to the <tt>Bike</tt> must
  1454. be added to the <tt>wheel</tt> instance. You can do this by adding the reference when the <tt>getWheel()</tt> method
  1455. is called using the following typemaps.
  1456. </p>
  1457. <div class="code">
  1458. <pre>
  1459. %typemap(cscode) Wheel %{
  1460. // Ensure that the GC doesn't collect any Bike instance set from C#
  1461. private Bike bikeReference;
  1462. internal void addReference(Bike bike) {
  1463. bikeReference = bike;
  1464. }
  1465. %}
  1466. // Add a C# reference to prevent premature garbage collection and resulting use
  1467. // of dangling C++ pointer. Intended for methods that return pointers or
  1468. // references to a member variable.
  1469. %typemap(csout, excode=SWIGEXCODE) Wheel&amp; getWheel {
  1470. IntPtr cPtr = $imcall;$excode
  1471. $csclassname ret = null;
  1472. if (cPtr != IntPtr.Zero) {
  1473. ret = new $csclassname(cPtr, $owner);
  1474. ret.addReference(this);
  1475. }
  1476. return ret;
  1477. }
  1478. </pre>
  1479. </div>
  1480. <p>
  1481. The code in the first typemap gets added to the <tt>Wheel</tt> proxy class.
  1482. The code in the second typemap constitutes the bulk of the code in the generated <tt>getWheel()</tt> function:
  1483. </p>
  1484. <div class="code">
  1485. <pre>
  1486. public class Wheel : IDisposable {
  1487. ...
  1488. // Ensure that the GC doesn't collect any Bike instance set from C#
  1489. private Bike bikeReference;
  1490. internal void addReference(Bike bike) {
  1491. bikeReference = bike;
  1492. }
  1493. }
  1494. public class Bike : IDisposable {
  1495. ...
  1496. public Wheel getWheel() {
  1497. IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr);
  1498. Wheel ret = null;
  1499. if (cPtr != IntPtr.Zero) {
  1500. ret = new Wheel(cPtr, false);
  1501. ret.addReference(this);
  1502. }
  1503. return ret;
  1504. }
  1505. }
  1506. </pre>
  1507. </div>
  1508. <p>
  1509. Note the <tt>addReference</tt> call.
  1510. </p>
  1511. <H3><a name="CSharp_memory_management_objects"></a>19.8.2 Memory management for objects passed to the C++ layer</H3>
  1512. <p>
  1513. The example is a direct equivalent to this <a href="Java.html#Java_memory_management_objects">Java equivalent</a>.
  1514. Managing memory can be tricky when using C++ and C# proxy classes.
  1515. The previous example shows one such case and this example looks at memory management for a class passed to a C++ method which expects the object to remain in scope
  1516. after the function has returned. Consider the following two C++ classes:
  1517. </p>
  1518. <div class="code">
  1519. <pre>
  1520. struct Element {
  1521. int value;
  1522. Element(int val) : value(val) {}
  1523. };
  1524. class Container {
  1525. Element* element;
  1526. public:
  1527. Container() : element(0) {}
  1528. void setElement(Element* e) { element = e; }
  1529. Element* getElement() { return element; }
  1530. };
  1531. </pre>
  1532. </div>
  1533. <p>
  1534. and usage from C++
  1535. </p>
  1536. <div class="code">
  1537. <pre>
  1538. Container container;
  1539. Element element(20);
  1540. container.setElement(&amp;element);
  1541. cout &lt;&lt; "element.value: " &lt;&lt; container.getElement()-&gt;value &lt;&lt; endl;
  1542. </pre>
  1543. </div>
  1544. <p>
  1545. and more or less equivalent usage from C#
  1546. </p>
  1547. <div class="code">
  1548. <pre>
  1549. Container container = new Container();
  1550. Element element = new Element(20);
  1551. container.setElement(element);
  1552. </pre>
  1553. </div>
  1554. <p>
  1555. The C++ code will always print out 20, but the value printed out may not be this in the C# equivalent code.
  1556. In order to understand why, consider a garbage collection occuring...
  1557. </p>
  1558. <div class="code">
  1559. <pre>
  1560. Container container = new Container();
  1561. Element element = new Element(20);
  1562. container.setElement(element);
  1563. Console.WriteLine("element.value: " + container.getElement().value);
  1564. // Simulate a garbage collection
  1565. System.GC.Collect();
  1566. System.GC.WaitForPendingFinalizers();
  1567. Console.WriteLine("element.value: " + container.getElement().value);
  1568. </pre>
  1569. </div>
  1570. <p>
  1571. The temporary element created with <tt>new Element(20)</tt> could get garbage collected
  1572. which ultimately means the <tt>container</tt> variable is holding a dangling pointer, thereby printing out any old random value instead of the expected value of 20.
  1573. One solution is to add in the appropriate references in the C# layer...
  1574. </p>
  1575. <div class="code">
  1576. <pre>
  1577. public class Container : IDisposable {
  1578. ...
  1579. // Ensure