DDeepin Developerfeat: Init commit
b83cb584创建于 2022年10月19日历史提交
<html>
<head>
<title>SWIG:Examples:python:class</title>
</head>

<body bgcolor="#ffffff">


<tt>SWIG/Examples/python/class/</tt>
<hr>

<H2>Wrapping a simple C++ class</H2>

<p>
This example illustrates wrapping a simple C++ class to give a Python class.

<h2>The C++ Code</h2>

Suppose you have some C++ classes described by the following (and admittedly lame) 
header file:

<blockquote>
<pre>
/* File : example.h */

class Shape {
public:
  Shape() {
    nshapes++;
  }
  virtual ~Shape() {
    nshapes--;
  }
  double  x, y;
  void    move(double dx, double dy);
  virtual double area() = 0;
  virtual double perimeter() = 0;
  static  int nshapes;
};

class Circle : public Shape {
private:
  double radius;
public:
  Circle(double r) : radius(r) { }
  virtual double area();
  virtual double perimeter();
};

class Square : public Shape {
private:
  double width;
public:
  Square(double w) : width(w) { }
  virtual double area();
  virtual double perimeter();
};
</pre>
</blockquote>

<h2>The SWIG interface</h2>

A simple SWIG interface for this can be built by simply grabbing the header file
like this:

<blockquote>
<pre>
/* File : example.i */
%module example

%{
#include "example.h"
%}

/* Let's just grab the original header file here */
%include "example.h"
</pre>
</blockquote>

Note: when creating a C++ extension, you must run SWIG with the <tt>-c++</tt> option like this:
<blockquote>
<pre>
% swig -c++ -python example.i
</pre>
</blockquote>

<h2>A sample Python script</h2>

Click <a href="runme.py">here</a> to see a script that calls the C++ functions from Python.

<h2>Key points</h2>

<ul>
<li>To create a new object, you call a constructor like this:

<blockquote>
<pre>
c = example.new_Circle(10.0)
</pre>
</blockquote>

<p>
<li>Member variables of the C++ class are wrapped as attributes of the Python class.
For example:

<blockquote>
<pre>
c.x = 15   # Set member data
x = c.x    # Get member data
</pre>
</blockquote>

<p>
<li>Member function are invoked as you would expect:

<blockquote>
<pre>
print "The area is ", c.area()
</pre>
</blockquote>

<p>
<li>To invoke a destructor, simply call <code>del</code> on the object:

<blockquote>
<pre>
del c    # Deletes a shape
</pre>
</blockquote>

<p>
<li>Static member variables are wrapped as C global variables.  For example:

<blockquote>
<pre>
n = example.cvar.Shape_nshapes     # Get a static data member
example.cvar.Shapes_nshapes = 13   # Set a static data member
</pre>
</blockquote>

</ul>

<h2>General Comments</h2>

<ul>
<li>SWIG <b>does</b> know how to properly perform upcasting of objects in
an inheritance hierarchy (including multiple inheritance).  Therefore
it is perfectly safe to pass an object of a derived class to any
function involving a base class.

<li>C++ Namespaces - %nspace isn't yet supported for Python.

</ul>

<hr>
</body>
</html>