SWIG entry 3: C/C ++ Basic Features

Source: Internet
Author: User

The reason for the establishment of the SWIG project is to provide simple and natural scripting language interfaces for everyone. What is concise and natural? It means that C/C ++ functions are directly encapsulated into python functions, and classes are encapsulated into python classes. In this way, it will not change. The following describes some basic C/C ++ features supported by SWIG.

1 Function

Function is the source of code reuse. SWIG encapsulates functions in Ultimate simplicity. After encapsulation, it is directly called as a module method in python.

1% module example

2 int fact (int n );


1 >>> import example

2 >>> print example. fact (4)

3 24

4 >>>

2. Global Variables

Various types of variables in C language can be used in python. Global variables are placed in the cvar variable of the module.

01 // file: foo. c

02 # include <stdio. h>

03 int bar = 2;

04 float barfloat = 3.14;

05 double bardouble = 3.1415926;

06 short barshort = 10000;

07 long barriers = 200;

08 long barlonglong = 20001000000000ll;

09 unsigned barunsigned = 200;

10

11

12 int barFunc ()

13 {

14 printf ("this is bar % d. \ n"

15 "barfloat % f \ n"

16 "bardouble % f \ n"

17 "barshort % hd \ n"

18 "barlong % ld \ n"

19 "barlonglong % lld \ n"

20 "barunsigned % u \ n"

21, bar, barfloat,

22 bardouble, barshort,

23 barlong, barlonglong,

24 barunsigned );

25 return 0;

26}


01 // file: foo. I

02% module foo

03% {

04 extern int bar;

05 extern float barfloat;

06 extern double bardouble;

07 extern short barshort;

08 extern long barlong;

09 extern long barlonglong;

10 extern unsigned barunsigned;

11%}

12

13 int bar;

14 float barfloat;

15 double bardouble;

16 short barshort;

17 long barlong;

18 long barlonglong;

19 unsigned barunsigned;

20 int barFunc ();


Note that global variables must be extern in the. I file. Otherwise, an error is returned when foo_wrap.c is compiled.

Use foo. var. xxx directly. For example

1 [GCC 4.4.5] on linux2

2 Type "help", "copyright", "credits" or "license" for more information.

3 >>> import foo

4 >>> foo. bar

5 Traceback (most recent call last ):

6 File "<stdin>", line 1, in <module>

7 AttributeError: 'module' object has no attribute 'bar'

8 >>> print foo. cvar. bar

9 2

It is particularly worth noting that the range check is also performed for each type of number in python. If the value assignment exceeds the range of this type, python will throw overflowerror.

1 >>> foo. cvar. barunsigned =-1

2 Traceback (most recent call last ):

3 File "<stdin>", line 1, in <module>

4 OverflowError: in variable 'barunsigne' of type 'unsigned int'

In addition, if you modify a const global variable, a segment fault is triggered. Therefore, the best way to handle const global variables is to use % immutable and % mutable. These two keywords represent read-only and writable variables respectively.

1% immutable;

2 int barconst;


1 [GCC 4.4.5] on linux2

2 Type "help", "copyright", "credits" or "license" for more information.

3 >>> import foo

4 >>> foo. cvar. barconst = 2

5 Traceback (most recent call last ):

6 File "<stdin>", line 1, in <module>

7 AttributeError: Variable barconst is read-only.

8 >>>

This will only cause exceptions, but will not cause more fatal segment errors. The % immutable Command remains valid until the % mutable command is displayed.

If you think that cvar is not a cool name, you can change it to another name. You only need to use the-globals varname parameter when running swig.

View sourceprint? 1 swig-python-globals variable foo. I

3. SWIG const and enumeration Variables

In addition to directly using the variables defined in the C language module, you can also define the const and enumeration variables for the python script in the SWIG script. You can use # define, enum, and % constant. The enum enumerated variable must also be written into your xxx_wrap.c code.

1% {

2 enum People {Man, Woman };

3%}

4 # define PI 3.1415

5 # define VERSION "1.0"

6

7 enum People {Man, Woman };

8% constant int barconstant = 100;

You do not need to use cvar to use this variable. This is the variable defined by the Python script and has nothing to do with your C code.

01 Type "help", "copyright", "credits" or "license" for more information.

02 >>> import foo

03 >>> foo. VERSION

04 '1. 0'

05 >>> foo. PI

06 3.1415000000000002

07 >>> foo. Woman

08 1

09 >>> foo. Man

10 0

11 >>> foo. barconstant

12 100


4 pointer

Because PYTHON does not contain pointers, SWIG only processes pointers as an object.

1% module foo

2 FILE * fopen (const char * fname, const char * mode );

3 int fputs (const char *, FILE *);

4 int fclose (FILE *);

We can directly encapsulate library functions for use.

01 [GCC 4.4.5] on linux2

02 Type "help", "copyright", "credits" or "license" for more information.

03 >>> import foo

04 >>> foo. fopen ("test", "w ")

05 <Swig Object of type 'file * 'at 0xb741c620>

06 >>> f = foo. fopen ("test", "w ")

07 >>> foo. fputs ("1234 \ n", f)

08 1

09 >>> foo. fclose (f)

10 0

5 arrays

PYTHON does not contain arrays. Therefore, SWIG can encapsulate the first address of an array only once as a pointer. That is to say, in PYTHON, you can only use this array as a pointer. It can be passed to a function with the pointer as a parameter. It can also be assigned a value by another array. In fact, the assignment is performed on the memory copy without changing the pointer address. See the following example.
01 // file: ary. c

02 # include <stdio. h>

03 int a [5] = {1, 2, 3, 4, 5 };

04 int B [6] = {10, 20, 30, 40, 50, 60 };

05

06 void PrintArray (int * a, size_t n)

07 {

08 size_t I = 0;

09 printf ("{");

10 for (I = 0; I <n; I ++)

11 {

12 printf ("% d,", * a ++ );

13}

14 printf ("} \ n ");

15}

16

17 void pa ()

18 {

19 PrintArray (a, sizeof (a)/sizeof (int ));

20}

21

22 void pb ()

23 {

24 PrintArray (B, sizeof (B)/sizeof (int ));

25}
01 // file: ary. I

02% module ary

03% {

04

05 extern int a [5];

06 extern int B [6];

07

08 extern void pa ();

09 extern void pb ();

10%}

11

12 int a [5];

13 int B [6];

14 void pa ();

15 void pb ();


01 # file: testary. py

02 import ary

03 print "a is :"

04 ary. pa ()

05 print str (ary. cvar.)

06 print "B is :"

07 print str (ary. cvar. B)

08 ary. pb ()

09

10 print "\ n"

11 ary. cvar. a = ary. cvar. B

12

13 print "After a = B"

14 print "a is :"

15 ary. pa ()

16 print str (ary. cvar.)

17 print "B is :"

18 print str (ary. cvar. B)

19 ary. pb ()

Running result:

View sourceprint? 01 a is:

02 {1, 2, 3, 4, 5 ,}

03 _ 306720b7_p_int

04 B is:

05 _ 446720b7_p_int

06 {10, 20, 30, 40, 50, 60 ,}

07

08

09 After a = B

10 a is: www.2cto.com

11 {10, 20, 30, 40, 50 ,}

12 _ 306720b7_p_int

13 B is:

14 _ 446720b7_p_int

15 {10, 20, 30, 40, 50, 60 ,}

As you can see, running a = B does not change the position pointed to by pointer a, but just copies the first five elements of array B to the position pointed to by pointer.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.