Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / src / nas,5.n2.os.2 / lib / python / html / swig / CSharp.html
CommitLineData
86530b38
AT
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>16 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_exceptions">C# Exceptions</a>
15<ul>
16<li><a href="#csharp_exception_example_check_typemap">C# exception example using "check" typemap</a>
17<li><a href="#csharp_exception_example_percent_exception">C# exception example using %exception</a>
18<li><a href="#csharp_exception_example_exception_specifications">C# exception example using exception specifications</a>
19<li><a href="#csharp_custom_application_exception">Custom C# ApplicationException example</a>
20</ul>
21</ul>
22</div>
23<!-- INDEX -->
24
25
26
27<H2><a name="csharp_introduction"></a>16.1 Introduction</H2>
28
29
30<p>
31The purpose of the C# module is to offer an automated way of accessing existing C/C++ code from .NET languages.
32The wrapper code implementation uses C# and the Platform Invoke (PInvoke) interface to access natively compiled C/C++ code.
33The PInvoke interface has been chosen over Microsoft's Managed C++ interface as it is portable to both Microsoft Windows and non-Microsoft platforms.
34PInvoke is part of the ECMA/ISO C# specification.
35It is also better suited for robust production environments due to the Managed C++ flaw called the
36<a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vcconMixedDLLLoadingProblem.asp">Mixed DLL Loading Problem</a>.
37Swig C# works equally well on non-Microsoft operating systems such as Linux, Solaris and Apple Mac using
38<a href="http://www.mono-project.com/">Mono</a> and <a href="http://www.dotgnu.org/pnet.html">Portable.NET</a>.
39</p>
40
41<p>
42To get the most out of this chapter an understanding of interop is required.
43The <a href="http://msdn.microsoft.com">Microsoft Developer Network (MSDN)</a> has a good reference guide in a section titled "Interop Marshaling".
44Monodoc, 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>.
45</p>
46
47<H2><a name="csharp_differences_java"></a>16.2 Differences to the Java module</H2>
48
49
50<p>
51The C# module is very similar to the Java module, so until some more complete documentation has been written,
52please use the <a href="Java.html#Java">Java documentation</a> as a guide to using SWIG with C#.
53The rest of this section should be read in conjunction with the Java documentation as it lists the main differences.
54
55<p>
56Director support (virtual method callbacks into C#) has not yet been implemented and is the main missing feature compared to Java.
57Less of the STL is supported and there are also a few minor utility typemaps in the various.i library which are missing.
58
59<p>
60
61The most noteable differences to Java are the following:
62<ul>
63
64<li>
65When invoking SWIG use the <tt>-csharp</tt> command line option instead of <tt>-java</tt>.
66</li>
67
68<li>
69The <tt>-package</tt> command line option does not exist.
70</li>
71
72<li>
73The <tt>-namespace &lt;name&gt;</tt> commandline option will generate all code into the namespace specified by <tt>&lt;name&gt;</tt>.
74</li>
75
76<li>
77The <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.
78</li>
79
80<li>
81C/C++ variables are wrapped with C# properties and not JavaBean style getters and setters.
82</li>
83
84<li>
85Global constants are generated into the module class. There is no constants interface.
86</li>
87
88<li>
89There is no implementation for type unsafe enums - not deemed necessary.
90</li>
91
92<li>
93The default enum wrapping approach is proper C# enums, not typesafe enums.
94<br>
95Note that %csconst(0) will be ignored when wrapping C/C++ enums with proper C# enums.
96This is because C# enum items must be initialised from a compile time constant.
97If an enum item has an initialiser and the initialiser doesn't compile as C# code,
98then the %csconstvalue directive must be used as %csconst(0) will have no effect.
99If it was used, it would generate an illegal runtime initialisation via a PInvoke call.
100</li>
101
102<li>
103C# doesn't support the notion of throws clauses.
104Therefore there is no 'throws' typemap attribute support for adding exception classes to a throws clause.
105Likewise there is no need for an equivalent to <tt>%javaexception</tt>.
106In fact, throwing C# exceptions works quite differently, see <a href="CSharp.html#csharp_exceptions">C# Exceptions></a> below.
107</li>
108
109<li>
110<p>Typemap equivalent names:</p>
111
112<div class="code"><pre>
113jni -&gt; ctype
114jtype -&gt; imtype
115jstype -&gt; cstype
116javain -&gt; csin
117javaout -&gt; csout
118javainterfaces -&gt; csinterfaces and csinterfaces_derived
119javabase -&gt; csbase
120javaclassmodifiers -&gt; csclassmodifiers
121javacode -&gt; cscode
122javaimports -&gt; csimports
123javabody -&gt; csbody
124javafinalize -&gt; csfinalize
125javadestruct -&gt; csdestruct
126javadestruct_derived -&gt; csdestruct_derived
127</pre></div>
128
129</li>
130
131<li>
132<p>Additional typemaps:</p>
133
134<div class="code"><pre>
135csvarin C# code property set typemap
136csvarout C# code property get typemap
137csattributes C# attributes for attaching to proxy classes/enums
138</pre></div>
139
140</li>
141
142<li>
143<p>Feature equivalent names:</p>
144<div class="code"><pre>
145%javaconst -&gt; %csconst
146%javaconstvalue -&gt; %csconstvalue
147%javamethodmodifiers -&gt; %csmethodmodifiers
148</pre></div>
149</li>
150
151<li>
152<p>Pragma equivalent names:</p>
153<div class="code"><pre>
154%pragma(java) -&gt; %pragma(csharp)
155jniclassbase -&gt; imclassbase
156jniclassclassmodifiers -&gt; imclassclassmodifiers
157jniclasscode -&gt; imclasscode
158jniclassimports -&gt; imclassimports
159jniclassinterfaces -&gt; imclassinterfaces
160</pre></div>
161</li>
162
163<li>
164<p>Special variable equivalent names:</p>
165<div class="code"><pre>
166$javaclassname -&gt; $csclassname
167$javainput -&gt; $csinput
168$jnicall -&gt; $imcall
169</pre></div>
170</li>
171
172<li>
173<p>
174The intermediary classname has <tt>PINVOKE</tt> appended after the module name instead of <tt>JNI</tt>, for example <tt>modulenamePINVOKE</tt>.
175</p>
176</li>
177
178<li>
179<p>
180Support for asymmetric type marshalling. The 'ctype', 'imtype' and 'cstype' typemaps support an optional <tt>out</tt> attribute which is used for output types.
181If this typemap attribute is specified, then the type specified in the attribute is used for output types and
182the type specified in the typemap itself is used for the input type.
183If this typemap attribute is not specified, then the type used for both input and output is the type specified in the typemap.
184An example shows that <tt>char *</tt> could be marshalled in different ways,
185</p>
186
187<div class="code">
188<pre>
189%typemap(imtype, out="IntPtr") char * "string"
190char * function(char *);
191</pre>
192</div>
193
194<p>
195The output type is thus IntPtr and the input type is string. The resulting intermediary C# code is:
196</p>
197
198<div class="code">
199<pre>
200public static extern IntPtr function(string jarg1);
201</pre>
202</div>
203
204</li>
205
206<li>
207<p>
208Support for type attributes.
209The 'imtype' and 'cstype' typemaps can have an optional <tt>inattributes</tt> and <tt>outattributes</tt> typemap attribute.
210There are C# attributes and typemap attributes, don't get confused!!
211The C# attributes specified in these typemap attributes are generated wherever the type is used in the C# wrappers.
212These 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.
213For example:
214</p>
215
216<div class="code">
217<pre>
218%typemap(imtype,
219 inattributes="[MarshalAs(UnmanagedType.LPStr)]",
220 outattributes="[return: MarshalAs(UnmanagedType.LPStr)]") const char * "String"
221
222const char * GetMsg() {}
223void SetMsg(const char *msg) {}
224</pre>
225</div>
226
227<p>
228The intermediary class will then have the marshalling as specified by everything in the 'imtype' typemap:
229</p>
230
231<div class="code">
232<pre>
233class examplePINVOKE {
234 ...
235 [DllImport("example", EntryPoint="CSharp_GetMsg")]
236 [return: MarshalAs(UnmanagedType.LPStr)]
237 public static extern String GetMsg();
238
239 [DllImport("example", EntryPoint="CSharp_SetMsg")]
240 public static extern void SetMsg([MarshalAs(UnmanagedType.LPStr)]String jarg1);
241}
242</pre>
243</div>
244
245<p>
246Note that the <tt>DllImport</tt> attribute is always generated, irrespective of any additional attributes specified.
247</p>
248
249<p>
250These attributes are associated with the C/C++ parameter type or return type, which is subtely different to
251the attribute features and typemaps covered next.
252Note that all these different C# attributes can be combined so that a method has more than one attribute.
253</p>
254</li>
255
256<li>
257<p>
258Support for attaching C# attributes to wrapped methods and variables.
259This is done using the <tt>%csattributes</tt> feature, see <a href="Customization.html#features">%feature directives</a>.
260Note that C# attributes are attached to proxy classes and enums using the <tt>csattributes</tt> typemap.
261For example, imagine we have a custom attribute class, <tt>ThreadSafeAttribute</tt>, for labelling thread safety.
262The following SWIG code shows how to attach this C# attribute to some methods and the class declaration itself:
263</p>
264
265<div class="code">
266<pre>
267%typemap(csattributes) AClass "[ThreadSafe]"
268%csattributes AClass::AClass(double d) "[ThreadSafe(false)]"
269%csattributes AClass::AMethod() "[ThreadSafe(true)]"
270
271%inline %{
272class AClass {
273public:
274 AClass(double a) {}
275 void AMethod() {}
276};
277%}
278</pre>
279</div>
280
281<p>
282will generate a C# proxy class:
283</p>
284
285<div class="code">
286<pre>
287[ThreadSafe]
288public class AClass : IDisposable {
289 ...
290 [ThreadSafe(false)]
291 public AClass(double a) ...
292
293 [ThreadSafe(true)]
294 public void AMethod() ...
295}
296</pre>
297</div>
298
299<p>
300If C# attributes need adding to the <tt>set</tt> or <tt>get</tt> part of C# properties, when wrapping C/C++ variables,
301they can be added using the 'csvarin' and 'csvarout' typemaps respectively.
302</p>
303</li>
304
305<li>
306<p>
307The <tt>%csmethodmodifiers</tt> feature can also be applied to variables as well as methods.
308In addition to the default <tt>public</tt> modifier that SWIG generates when <tt>%csmethodmodifiers</tt> is not
309specified, the feature will also replace the <tt>virtual</tt>/<tt>new</tt>/<tt>override</tt> modifiers that SWIG thinks is appropriate.
310This 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.
311</p>
312</li>
313
314</ul>
315
316<p>
317<b><tt>$dllimport</tt></b><br>
318This is a C# only special variable that can be used in typemaps, pragmas, features etc.
319The special variable will get translated into the value specified by the <tt>-dllimport</tt> commandline option
320if specified, otherwise it is equivalent to the <b>$module</b> special variable.
321</p>
322
323<p>
324The directory <tt>Examples/csharp</tt> has a number of simple examples.
325Visual Studio .NET 2003 solution and project files are available for compiling with the Microsoft .NET C# compiler on Windows.
326If 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,
327then <tt>ilrun runme.exe</tt> (Portable.NET C# compiler) or <tt>mono runme.exe</tt> (Mono C# compiler) to run the examples.
328Windows users can also get the examples working using a
329<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.
330Any 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.
331
332<H2><a name="csharp_exceptions"></a>16.3 C# Exceptions</H2>
333
334
335<p>
336It is possible to throw a C# Exception from C/C++ code.
337SWIG already provides the framework for throwing C# exceptions if it is able to detect that a C++ exception could be thrown.
338Automatically detecting that a C++ exception could be thrown is only possible when a C++ exception specification is used,
339see <a href="SWIGPlus.html#SWIGPlus_exception_specifications">Exception specifications</a>.
340The <a href="Customization.html#exception">Exception handling with %exception</a> section details the <tt>%exception</tt> feature.
341Customised code for handling exceptions with or without a C++ exception specification is possible and the details follow.
342However anyone wishing to do this should be familiar with the contents of the sections referred to above.
343</p>
344
345<p>
346Unfortunately a C# exception cannot simply be thrown from unmanaged code for a variety of reasons.
347Most noteably being that throwing a C# exception results in exceptions being thrown across the C PInvoke interface and C does not understand exceptions.
348The design revolves around a C# exception being constructed and stored as a pending exception, to be thrown only when the unmanaged code has completed.
349Implementing this is a tad involved and there are thus some unusual typemap constructs.
350Some practical examples follow and they should be read in conjunction with the rest of this section.
351</p>
352
353<p>
354First some details about the design that must be followed.
355Each typemap or feature that generates <b>unmanaged code</b> supports an attribute called <tt>canthrow</tt>.
356This 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.
357The code in the typemap/feature can then raise a C# exception by calling one of the C functions,
358<tt>SWIG_CSharpSetPendingException()</tt> or <tt>SWIG_CSharpSetPendingExceptionArgument()</tt>.
359When called, the function makes a callback into the managed world via a delegate.
360The callback creates and stores an exception ready for throwing when the unmanaged code has finished.
361The typemap/feature unmanaged code is then expected to force an immediate return from the unmanaged wrapper function,
362so that the pending managed exception can then be thrown.
363The support code has been carefully designed to be efficient as well as thread-safe.
364However to achieve the goal of efficiency requires some optional code generation in the <b>managed code</b> typemaps.
365Code to check for pending exceptions is generated if and only if the unmanaged code has code to set a pending exception,
366that is if the <tt>canthrow</tt> attribute is set.
367The optional managed code is generated using the <tt>excode</tt> typemap attribute and <tt>$excode</tt> special variable in the relevant managed code typemaps.
368Simply, if any relevant unmanaged code has the <tt>canthrow</tt> attribute set, then any occurrences of <tt>$excode</tt>
369is replaced with the code in the <tt>excode</tt> attribute.
370If the <tt>canthrow</tt> attribute is not set, then any occurrences of <tt>$excode</tt> are replaced with nothing.
371</p>
372
373<p>
374The prototypes for the <tt>SWIG_CSharpSetPendingException()</tt> and <tt>SWIG_CSharpSetPendingExceptionArgument()</tt> functions are
375</p>
376
377<div class="code">
378<pre>
379static void SWIG_CSharpSetPendingException(SWIG_CSharpExceptionCodes code,
380 const char *msg);
381
382static void SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpExceptionArgumentCodes code,
383 const char *msg,
384 const char *param_name);
385</pre>
386</div>
387
388<p>
389The first parameter defines which .NET exceptions can be thrown:
390</p>
391
392<div class="code">
393<pre>
394typedef enum {
395 SWIG_CSharpApplicationException,
396 SWIG_CSharpArithmeticException,
397 SWIG_CSharpDivideByZeroException,
398 SWIG_CSharpIndexOutOfRangeException,
399 SWIG_CSharpInvalidOperationException,
400 SWIG_CSharpIOException,
401 SWIG_CSharpNullReferenceException,
402 SWIG_CSharpOutOfMemoryException,
403 SWIG_CSharpOverflowException,
404 SWIG_CSharpSystemException
405} SWIG_CSharpExceptionCodes;
406
407typedef enum {
408 SWIG_CSharpArgumentException,
409 SWIG_CSharpArgumentNullException,
410 SWIG_CSharpArgumentOutOfRangeException,
411} SWIG_CSharpExceptionArgumentCodes;
412</pre>
413</div>
414
415<p>
416where, for example, <tt>SWIG_CSharpApplicationException</tt> corresponds to the .NET exception, <tt>ApplicationException</tt>.
417The <tt>msg</tt> and <tt>param_name</tt> parameters contain the C# exception message and parameter name associated with the exception.
418</p>
419
420
421<p>
422The <tt>%exception</tt> feature in C# has the <tt>canthrow</tt> attribute set.
423The <tt>%csnothrowexception</tt> feature is like <tt>%exception</tt>, but it does not have the <tt>canthrow</tt> attribute
424set so should only be used when a C# exception is not created.
425</p>
426
427
428<H3><a name="csharp_exception_example_check_typemap"></a>16.3.1 C# exception example using "check" typemap</H3>
429
430
431<p>
432Lets say we have the following simple C++ method:
433</p>
434
435
436<div class="code">
437<pre>
438void positivesonly(int number);
439</pre>
440</div>
441
442<p>
443and we want to check that the input <tt>number</tt> is always positive and if not throw a C# <tt>ArgumentOutOfRangeException</tt>.
444The "check" typemap is designed for checking input parameters. Below you will see the <tt>canthrow</tt> attribute is set because
445the code contains a call to <tt>SWIG_CSharpSetPendingExceptionArgument()</tt>. The full example follows:
446</p>
447
448<div class="code">
449<pre>
450%module example
451
452%typemap(check, canthrow=1) int number %{
453if ($1 &lt; 0) {
454 SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
455 "only positive numbers accepted", "number");
456 return $null;
457}
458// SWIGEXCODE is a macro used by many other csout typemaps
459%define SWIGEXCODE
460 "\n if ($modulePINVOKE.SWIGPendingException.Pending)"
461 "\n throw $modulePINVOKE.SWIGPendingException.Retrieve();"
462%enddef
463%typemap(csout, excode=SWIGEXCODE) void {
464 $imcall;$excode
465 }
466%}
467
468%inline %{
469
470void positivesonly(int number) {
471}
472
473%}
474</pre>
475</div>
476
477<p>
478When the following C# code is executed:
479</p>
480
481<div class="code">
482<pre>
483public class runme {
484 static void Main() {
485 example.positivesonly(-1);
486 }
487}
488</pre>
489</div>
490
491<p>
492The exception is thrown:
493</p>
494
495<div class="code">
496<pre>
497Unhandled Exception: System.ArgumentOutOfRangeException: only positive numbers accepted
498Parameter name: number
499in &lt;0x00034&gt; example:positivesonly (int)
500in &lt;0x0000c&gt; runme:Main ()
501</pre>
502</div>
503
504<p>
505Now let's analyse the generated code to gain a fuller understanding of the typemaps. The generated unmanaged C++ code is:
506</p>
507
508
509<div class="code">
510<pre>
511SWIGEXPORT void SWIGSTDCALL CSharp_positivesonly(int jarg1) {
512 int arg1 ;
513
514 arg1 = (int)jarg1;
515
516 if (arg1 &lt; 0) {
517 SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
518 "only positive numbers accepted", "number");
519 return ;
520 }
521
522 positivesonly(arg1);
523
524}
525</pre>
526</div>
527
528<p>
529This largely comes from the "check" typemap. The managed code in the module class is:
530</p>
531
532<div class="code">
533<pre>
534public class example {
535 public static void positivesonly(int number) {
536 examplePINVOKE.positivesonly(number);
537 if (examplePINVOKE.SWIGPendingException.Pending)
538 throw examplePINVOKE.SWIGPendingException.Retrieve();
539 }
540
541}
542</pre>
543</div>
544
545<p>
546This comes largely from the "csout" typemap.
547</p>
548
549<p>
550The "csout" typemap is the same as the default void "csout" typemap so is not strictly necessary for the example.
551However, it is shown to demonstrate what managed output code typemaps should contain,
552that is, a <tt>$excode</tt> special variable and an <tt>excode</tt> attribute.
553Also note that <tt>$excode</tt> is expanded into the code held in the <tt>excode</tt> attribute.
554The <tt>$imcall</tt> as always expands into <tt>examplePINVOKE.positivesonly(number)</tt>.
555The exception support code in the intermediary class, <tt>examplePINVOKE</tt>, is not shown, but is contained within the inner classes,
556<tt>SWIGPendingException</tt> and <tt>SWIGExceptionHelper</tt> and is always generated.
557These classes can be seen in any of the generated wrappers.
558However, all that is required of a user is as demonstrated in the "csin" typemap above.
559That is, is to check <tt>SWIGPendingException.Pending</tt> and to throw the exception returned by <tt>SWIGPendingException.Retrieve()</tt>.
560</p>
561
562<p>
563If the "check" typemap did not exist, then
564the following module class would instead be generated:
565</p>
566
567<div class="code">
568<pre>
569public class example {
570 public static void positivesonly(int number) {
571 examplePINVOKE.positivesonly(number);
572 }
573
574}
575</pre>
576</div>
577
578<p>
579Here we see the pending exception checking code is omitted.
580In fact, the code above would be generated if the <tt>canthrow</tt> attribute was not in the "check" typemap, such as:
581</p>
582
583<div class="code">
584<pre>
585%typemap(check) int number %{
586if ($1 &lt; 0) {
587 SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
588 "only positive numbers accepted", "number");
589 return $null;
590}
591%}
592</pre>
593</div>
594
595<p>
596Note that if SWIG detects you have used <tt>SWIG_CSharpSetPendingException()</tt> or <tt>SWIG_CSharpSetPendingExceptionArgument()</tt>
597without setting the <tt>canthrow</tt> attribute you will get a warning message similar to
598</p>
599
600<div class="code">
601<pre>
602example.i:21: Warning(845): Unmanaged code contains a call to a SWIG_CSharpSetPendingException
603method and C# code does not handle pending exceptions via the canthrow attribute.
604</pre>
605</div>
606<p>
607Actually it will issue this warning for any function beginning with <tt>SWIG_CSharpSetPendingException</tt>.
608</P>
609
610<H3><a name="csharp_exception_example_percent_exception"></a>16.3.2 C# exception example using %exception</H3>
611
612
613<p>
614Let's consider a similar, but more common example that throws a C++ exception from within a wrapped function.
615We can use <tt>%exception</tt> as mentioned in <a href="Customization.html#exception">Exception handling with %exception</a>.
616</p>
617
618<div class="code">
619<pre>
620%exception negativesonly(int value) %{
621try {
622 $action
623} catch (std::out_of_range e) {
624 SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
625}
626%}
627
628%inline %{
629#include &lt;stdexcept&gt;
630void negativesonly(int value) {
631 if (value &gt;= 0)
632 throw std::out_of_range("number should be negative");
633}
634%}
635</pre>
636</div>
637
638<p>
639The generated unmanaged code this time catches the C++ exception and converts it into a C# <tt>ApplicationException</tt>.
640</p>
641
642<div class="code">
643<pre>
644SWIGEXPORT void SWIGSTDCALL CSharp_negativesonly(int jarg1) {
645 int arg1 ;
646
647 arg1 = (int)jarg1;
648
649 try {
650 negativesonly(arg1);
651
652 } catch (std::out_of_range e) {
653 SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
654 return ;
655 }
656
657}
658</pre>
659</div>
660
661<p>
662The 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:
663</p>
664
665<div class="code">
666<pre>
667 public static void negativesonly(int value) {
668 examplePINVOKE.negativesonly(value);
669 if (examplePINVOKE.SWIGPendingException.Pending)
670 throw examplePINVOKE.SWIGPendingException.Retrieve();
671 }
672</pre>
673</div>
674
675<H3><a name="csharp_exception_example_exception_specifications"></a>16.3.3 C# exception example using exception specifications</H3>
676
677
678<p>
679When C++ exception specifications are used, SWIG is able to detect that the method might throw an exception.
680By default SWIG will automatically generate code to catch the exception and convert it into a managed <tt>ApplicationException</tt>,
681as defined by the default "throws" typemaps.
682The following example has a user supplied "throws" typemap which is used whenever an exception specification contains a <tt>std::out_of_range</tt>,
683such as the <tt>evensonly</tt> method below.
684</p>
685
686<div class="code">
687<pre>
688%typemap(throws, canthrow=1) std::out_of_range {
689 SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, $1.what(), NULL);
690 return $null;
691}
692
693%inline %{
694#include &lt;stdexcept&gt;
695void evensonly(int input) throw (std::out_of_range) {
696 if (input%2 != 0)
697 throw std::out_of_range("number is not even");
698}
699%}
700</pre>
701</div>
702
703<p>
704Note that the type for the throws typemap is the type in the exception specification.
705SWIG generates a try catch block with the throws typemap code in the catch handler.
706</p>
707
708<div class="code">
709<pre>
710SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) {
711 int arg1 ;
712
713 arg1 = (int)jarg1;
714 try {
715 evensonly(arg1);
716 }
717 catch(std::out_of_range &amp;_e) {
718 {
719 SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, (&amp;_e)-&gt;what(), NULL);
720 return ;
721 }
722 }
723
724}
725</pre>
726</div>
727
728<p>
729Multiple catch handlers are generated should there be more than one exception specifications declared.
730</p>
731
732<H3><a name="csharp_custom_application_exception"></a>16.3.4 Custom C# ApplicationException example</H3>
733
734
735<p>
736This example involves a user defined exception.
737The conventional .NET exception handling approach is to create a custom <tt>ApplicationException</tt> and throw it in your application.
738The goal in this example is to convert the STL <tt>std::out_of_range</tt> exception into one of these custom .NET exceptions.
739</p>
740
741
742<p>
743The default exception handling is quite easy to use as the <tt>SWIG_CSharpSetPendingException()</tt> and <tt>SWIG_CSharpSetPendingExceptionArgument()</tt>
744methods are provided by SWIG.
745However, for a custom C# exception, the boiler plate code that supports these functions needs replicating.
746In essence this consists of some C/C++ code and C# code.
747The C/C++ code can be generated into the wrapper file using the <tt>%insert(runtime)</tt> directive and
748the C# code can be generated into the intermediary class using the <tt>imclasscode</tt> pragma as follows:
749
750</p>
751
752<div class="code">
753<pre>
754%insert(runtime) %{
755 // Code to handle throwing of C# CustomApplicationException from C/C++ code.
756 // The equivalent delegate to the callback, CSharpExceptionCallback_t, is CustomExceptionDelegate
757 // and the equivalent customExceptionCallback instance is customDelegate
758 typedef void (SWIGSTDCALL* CSharpExceptionCallback_t)(const char *);
759 CSharpExceptionCallback_t customExceptionCallback = NULL;
760
761 extern "C" SWIGEXPORT
762 void SWIGSTDCALL CustomExceptionRegisterCallback(CSharpExceptionCallback_t customCallback) {
763 customExceptionCallback = customCallback;
764 }
765
766 // Note that SWIG detects any method calls named starting with
767 // SWIG_CSharpSetPendingException for warning 845
768 static void SWIG_CSharpSetPendingExceptionCustom(const char *msg) {
769 customExceptionCallback(msg);
770 }
771%}
772
773%pragma(csharp) imclasscode=%{
774 class CustomExceptionHelper {
775 // C# delegate for the C/C++ customExceptionCallback
776 public delegate void CustomExceptionDelegate(string message);
777 static CustomExceptionDelegate customDelegate =
778 new CustomExceptionDelegate(SetPendingCustomException);
779
780 [DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")]
781 public static extern
782 void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback);
783
784 static void SetPendingCustomException(string message) {
785 SWIGPendingException.Set(new CustomApplicationException(message));
786 }
787
788 static CustomExceptionHelper() {
789 CustomExceptionRegisterCallback(customDelegate);
790 }
791 }
792 static CustomExceptionHelper exceptionHelper = new CustomExceptionHelper();
793%}
794</pre>
795</div>
796
797<p>
798The method stored in the C# delegate instance, <tt>customDelegate</tt> is what gets called by the C/C++ callback.
799However, the equivalent to the C# delegate, that is the C/C++ callback, needs to be assigned before any unmanaged code is executed.
800This is achieved by putting the initialisation code in the intermediary class.
801Recall that the intermediary class contains all the PInvoke methods, so the static variables in the intermediary class will be initialised
802before any of the PInvoke methods in this class are called.
803The <tt>exceptionHelper</tt> static variable ensures the C/C++ callback is initialised with the value in <tt>customDelegate</tt> by calling
804the <tt>CustomExceptionRegisterCallback</tt> method in the <tt>CustomExceptionHelper</tt> static constructor.
805Once 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.
806Any calls to <tt>SWIG_CSharpSetPendingExceptionCustom()</tt> will make the callback to create the pending exception in the same way that
807<tt>SWIG_CSharpSetPendingException()</tt> and <tt>SWIG_CSharpSetPendingExceptionArgument()</tt> does.
808In fact the method has been similarly named so that SWIG can issue the warning about missing <tt>canthrow</tt> attributes as discussed earlier.
809It is an invaluable warning as it is easy to forget the <tt>canthrow</tt> attribute when writing typemaps/features.
810</p>
811
812<p>
813The <tt>SWIGPendingException</tt> helper class is not shown, but is generated as an inner class into the intermediary class.
814It stores the pending exception in Thread Local Storage so that the exception handling mechanism is thread safe.
815</p>
816
817<p>
818The boiler plate code above must be used in addition to a handcrafted <tt>CustomApplicationException</tt>:
819</p>
820
821<div class="code">
822<pre>
823// Custom C# Exception
824class CustomApplicationException : System.ApplicationException {
825 public CustomApplicationException(string message)
826 : base(message) {
827 }
828}
829</pre>
830</div>
831
832<p>
833and the SWIG interface code:
834</p>
835
836<div class="code">
837<pre>
838%typemap(throws, canthrow=1) std::out_of_range {
839 SWIG_CSharpSetPendingExceptionCustom($1.what());
840 return $null;
841}
842
843%inline %{
844void oddsonly(int input) throw (std::out_of_range) {
845 if (input%2 != 1)
846 throw std::out_of_range("number is not odd");
847}
848%}
849</pre>
850</div>
851
852<p>
853The "throws" typemap now simply calls our new <tt>SWIG_CSharpSetPendingExceptionCustom()</tt> function so that the exception can be caught, as such:
854</p>
855
856<div class="code">
857<pre>
858try {
859 example.oddsonly(2);
860} catch (CustomApplicationException e) {
861 ...
862}
863</pre>
864</div>
865
866</body>
867</html>
868