-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathSWIG_generator.py
More file actions
1312 lines (1257 loc) · 61.3 KB
/
SWIG_generator.py
File metadata and controls
1312 lines (1257 loc) · 61.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: iso-8859-1 -*-
#! /usr/bin/python
##Copyright 2008-2011 Thomas Paviot (tpaviot@gmail.com)
##
##This file is part of pythonOCC.
##
##pythonOCC is free software: you can redistribute it and/or modify
##it under the terms of the GNU Lesser General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##pythonOCC is distributed in the hope that it will be useful,
##but WITHOUT ANY WARRANTY; without even the implied warranty of
##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
##GNU Lesser General Public License for more details.
##
##You should have received a copy of the GNU Lesser General Public License
##along with pythonOCC. If not, see <http://www.gnu.org/licenses/>.
##
## $Revision$
## $Date$
## $Author$
## $HeadURL$
##
import os, os.path
import sys
sys.path.append("../..")
import glob
import datetime
try:
from pygccxml import declarations
from pyplusplus import module_builder
HAVE_PYGCCXML = True
except ImportError:
HAVE_PYGCCXML = False
import environment
import Modules
def CaseSensitiveGlob(wildcard):
"""
Case sensitive glob for Windows.
Designed for handling of GEOM and Geom modules
This function makes the difference between GEOM_* and Geom_* under Windows
"""
flist = glob.glob(wildcard)
pattern = wildcard.split('*')[0]
f = []
for file in flist:
if pattern in file:
f.append(file)
return f
def WriteLicenseHeader(fp):
header = """/*
Copyright 2008-2011 Thomas Paviot (tpaviot@gmail.com)
This file is part of pythonOCC.
pythonOCC is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pythonOCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with pythonOCC. If not, see <http://www.gnu.org/licenses/>.
$Revision$
$Date$
$Author$
$HeaderURL$
*/
"""
fp.write(header)
nb_exported_classes = 0
def write_windows_pragma(fp):
"""
Remove warnings that raise compiler errors, like for instance C4716
"""
str= """
%{
#ifdef WNT
#pragma warning(disable : 4716)
#endif
%}
"""
fp.write(str)
class ModularBuilder(object):
"""
This class generates a set of .i files integrated in one OCC.i script. The result is
a simple _OCC.pyd and OCC.py script that enable better handliing of different OCC classes.
"""
#def __init__( self , module, generate_doc = False, INC_PATH = environment.OCC_INC):
def __init__( self , module, INC_PATH = environment.OCC_INC):
self.MODULES = module
self.MODULE_NAME = module[0]
self.INC_PATH = INC_PATH #the path where are the headers to parse can be OCC_INC or SALOME_GEOM_INC
#self = generate_doc
#if self._generate_doc:
# self.WriteLicenseHeader = WriteDisclaimerHeader
#else:
# self.WriteLicenseHeader = WriteLicenseHeader
self._mb = None
self.fp = None
self.occ_fp = None
self.dependencies_fp = None
self.module_dependencies = []
self.dependencies_headers_to_write = []
self._available_occ_packages = []
# The name of the header file to be parsed by gccxml/pygccxml
self._wrapper_filename = os.path.join(os.getcwd(),'%s'%environment.SWIG_FILES_PATH_MODULAR,'%s_Wrapper.hxx'%self.MODULE_NAME)
# A dict contains all parent classes of a given class
self.DERIVED = {}
# Two lists containing typedefs and enums
self._typedef_list = []
self._enum_list = []
# A list containing all necessary headers to achieve compilation
self.ADDITIONAL_HEADERS = module[1]
self.ADDITIONAL_HXX = []
self.NEEDED_HXX = []
self.IMPORTED_MODULES = []
self.MODULES_TO_IMPORT = ['GarbageCollector']
self.MEMBER_FUNCTIONS_TO_EXCLUDE = {}
self.STATIC_METHODS = []
self.ClassDocstring = ""
self.CLASS_WRAP_EQ = False
self.CLASS_WRAP_NE = False
self.MemberfunctionDocStrings = {}
self.ALREADY_EXPOSED = []
self.CLASSES_TO_EXCLUDE = []
self.InitBaseSwigFile()
self.FindClasseToExclude()
self.FindMemberFunctionsToExclude()
self.Init()
self.GenerateSWIGSourceFile()
self.WriteDepencyFile()
self.WriteHeaderFile()
def BuildClassHierarchy(self):
"""
Directory of class hierarchy
Ex: DERIVED = {"104":[Voiture],"106":[Voiture]}
"""
try:
all_classes = self._mb.classes()
except: #no class defined in the set of headers
print "No class defined in the set of headers"
return True
classes_declarations = all_classes.declarations
for class_declaration in classes_declarations:
class_name = class_declaration.name
derived = class_declaration.derived
if len(derived)>0:
for der in derived:
self.DERIVED[der.related_class.name]=class_name
def BuildTypedefList(self):
"""
Fill in the typedef_list with all typedef defined in this module
"""
try:
typedefs = self._mb.global_ns.typedefs()
except:
return False #no typedefs defined in this package
for typedef in typedefs:
typedef_name = typedef.name
self._typedef_list.append(typedef_name)
def BuildEnumList(self):
"""
Fill in the enum_list with all enums defined in this module
"""
try:#eeror with BRepBndLib on Linux
for enum in self._mb.enumerations():
enum_name = enum.name
self._enum_list.append(enum_name)
except:
pass
def GenerateSWIGSourceFile(self):
"""
.i file creation
"""
self.GenerateWrapper()
self.BuildModule()
self.BuildTypedefList()
self.BuildEnumList()
self.BuildClassHierarchy()
# File creation
self.fp = self.occ_fp
self.WriteModuleTypedefs()
self.WriteModuleEnums()
# Classes processing (if any class defined in the module)
try:
handle_classes_to_expose = self._mb.classes(lambda decl: (decl.name.lower().startswith(("Handle_%s_"%self.MODULE_NAME).lower())))
for class_declaration in handle_classes_to_expose:
if not class_declaration.name in self.CLASSES_TO_EXCLUDE:
self.process_class(class_declaration)
except RuntimeError:
print "No handles defined."
try:
classes_to_expose = self._mb.classes(lambda decl: (decl.name.lower().startswith(("%s_"%self.MODULE_NAME).lower())) or decl.name==self.MODULE_NAME)
for class_declaration in classes_to_expose:
if not class_declaration.name in self.CLASSES_TO_EXCLUDE:
self.process_class(class_declaration)
except RuntimeError:
print "No class defined."
self.write_modules_to_import_files()
self.write_renames_file()
self.fp.close()
def AddDependency(self, module_name):
"""
Add a dependency with other module.
"""
# Exclude a number of extra dependencies for the SMESH module:
if module_name in ['TSideVector','TError','Z','TParam2ColumnMap',\
'basic','exception','MeshDimension','TSetOfInt',\
'NLinkNodeMap','pair<SMDS','NLink','TIDSortedElemSet',\
'TElemOfElemListMap','TNodeNodeMap','EventListener',\
'EventListenerData','TLinkNodeMap','MapShapeNbElems',\
'size']:
return True
if module_name=='GEOM':
module_name='SGEOM'
if 'XW' in module_name: #TODO: better handling of XW.i dependency with Xw module under Linux
return True
if module_name == 'Selector': #SalomeGEOM
return True
if module_name=='TVariablesList': #SGEOM module
return True
if sys.platform=='win32' and module_name=='WNT':
return True
if sys.platform=='win32' and module_name=='Xw':
return True
if not module_name in self.module_dependencies:
self.module_dependencies.append(module_name)
if module_name=='TCollection':
self.dependencies_headers_to_write += CaseSensitiveGlob(os.path.join(self.INC_PATH,'Handle_%s_*.hxx'%module_name))
if self.INC_PATH == environment.SALOME_GEOM_INC:
self.dependencies_headers_to_write += CaseSensitiveGlob(os.path.join(environment.OCC_INC,'Handle_%s_*.hxx'%module_name))
else:
self.dependencies_headers_to_write += CaseSensitiveGlob(os.path.join(self.INC_PATH,'%s_*.hxx'%module_name))+\
CaseSensitiveGlob(os.path.join(self.INC_PATH,'Handle_%s_*.hxx'%module_name))
if self.INC_PATH == environment.SALOME_GEOM_INC:
self.dependencies_headers_to_write += CaseSensitiveGlob(os.path.join(environment.OCC_INC,'%s_*.hxx'%module_name))+\
CaseSensitiveGlob(os.path.join(environment.OCC_INC,'Handle_%s_*.hxx'%module_name))
self.dependencies_headers_to_write = self.OSFilterHeaders(self.dependencies_headers_to_write)
def WriteDepencyFile(self):
"""
Generate the file for dependencies.
"""
if self.MODULE_NAME=='GEOM':
self.MODULE_NAME='SGEOM'#back to the good name
dependencies_fp = open(os.path.join(os.getcwd(),'%s'%environment.SWIG_FILES_PATH_MODULAR,'%s_dependencies.i'%self.MODULE_NAME),"w")
WriteLicenseHeader(dependencies_fp)
self.dependencies_headers_to_write.sort()
if len(self.module_dependencies)==0:
return True
dependencies_fp.write("%{\n")
for header_to_write in self.dependencies_headers_to_write:
dependencies_fp.write("#include <%s>\n"%os.path.basename(header_to_write))
dependencies_fp.write("%};\n\n")
# Adding imports
for module_name in self.module_dependencies:
dependencies_fp.write("%%import %s.i\n"%module_name)
dependencies_fp.close()
def WriteHeaderFile(self):
"""
Write the SWIG file that contains all required headers for compilation.
"""
print self.MODULE_NAME
if self.MODULE_NAME=='GEOM':
self.MODULE_NAME='SGEOM'#back to the good name
already_written = []
headers_fp = open(os.path.join(os.getcwd(),'%s'%environment.SWIG_FILES_PATH_MODULAR,'%s_headers.i'%self.MODULE_NAME),"w")
WriteLicenseHeader(headers_fp)
# Write includes
headers_fp.write("%{\n")
headers_fp.write("\n// Headers necessary to define wrapped classes.\n\n")
for hxx_file in self.HXX_FILES:
if not hxx_file in already_written:
headers_fp.write("#include<%s>\n"%os.path.basename(hxx_file))
already_written.append(hxx_file)
headers_fp.write("\n// Additional headers necessary for compilation.\n\n")
self.ADDITIONAL_HXX = self.OSFilterHeaders(self.ADDITIONAL_HXX)
for hxx_file in self.ADDITIONAL_HXX:
if not hxx_file in already_written:
headers_fp.write("#include<%s>\n"%os.path.basename(hxx_file))
already_written.append(hxx_file)
# NEEDED_HXX:
headers_fp.write("\n// Needed headers necessary for compilation.\n\n")
self.NEEDED_HXX = self.OSFilterHeaders(self.NEEDED_HXX)
for hxx_file in self.NEEDED_HXX:
if os.path.isfile(os.path.join(self.INC_PATH,hxx_file)):
if not hxx_file in already_written:
headers_fp.write("#include<%s>\n"%os.path.basename(hxx_file))
already_written.append(hxx_file)
headers_fp.write("%}\n")
headers_fp.close()
def write_renames_file(self):
''' some methods needs to be renamed. For instance, the Vertex() method of the TopoDS class,
which is a static method, will be accessed under python with the name TopoDS_Vertex(). It conflicts
with the TopoDS_Vertex class and then one of the class/method is shadowed by SWIG.
As a consequence, all the static methods are renamed with the lowercase convention.
'''
renamed_file_fp = open(os.path.join(os.getcwd(),'%s'%environment.SWIG_FILES_PATH_MODULAR,'%s_renames.i'%self.MODULE_NAME),"w")
WriteLicenseHeader(renamed_file_fp)
#
# Process static methods
#
if self.MODULE_NAME == 'GccEnt':
#do nothing
renamed_file_fp.close()
return True
for static_method in self.STATIC_METHODS:
class_name = static_method[0]
method_name = static_method[1]
#protect_methods = ['TypeName','Static','Template','DownCast']
if class_name == 'TopoDS':
#if method_name not in ['TypeName','Static','Template','DownCast']: # lowercase typename will raise issues
new_method_name = method_name.lower()
renamed_file_fp.write("%%rename(%s) %s::%s;\n"%(new_method_name,class_name,method_name))
else:
renamed_file_fp.write("%%rename(%s) %s::%s;\n"%(method_name,class_name,method_name))
renamed_file_fp.close()
def write_modules_to_import_files(self):
#if len(self.MODULES_TO_IMPORT) == 0:
# return True
if self.MODULE_NAME=='GEOM':
self.MODULE_NAME='SGEOM'
required_modules_fp = open(os.path.join(os.getcwd(),'%s'%environment.SWIG_FILES_PATH_MODULAR,'%s_required_python_modules.i'%self.MODULE_NAME),"w")
WriteLicenseHeader(required_modules_fp)
if not len(self.MODULES_TO_IMPORT)==0:
required_modules_fp.write("\n%pythoncode {\n")
required_modules_fp.write("#importing required modules\n")
for module in self.MODULES_TO_IMPORT:
required_modules_fp.write('import %s\n'%module)
required_modules_fp.write("};\n")
required_modules_fp.close()
def process_by_ref_argument(self,argument_list):
''' process arguments passed by ref. Try to remove the by ref and pass by value.
This will be achieved only if the argument passed by ref has defined a copy constructor
'''
if not '&' in argument_list:
return argument_list
module = argument_list[0].split('_')[0]
if not module.startswith('Handle'):
if module in ['gp','TopoDS']:
argument_list.remove('&')
return argument_list
def write_function_arguments(self,mem_fun):
"""
Write the function arguments, comma separated
"""
to_write = ''
return_list = []
param_list = []
param_names = [] # a list with all the names of parameters
default_value = {}
FUNCTION_MODIFIED = False #is the function modified by any byref stuff?
arguments = mem_fun.arguments
is_first = True
for i in range(len(arguments)):
argument = arguments[i]
if i<len(arguments)-1:
next_argument = arguments[i+1]
next_argument_default_value = "%s"%next_argument.default_value
else:
next_argument_default_value = "PP"
if not is_first:
to_write += ", "
argument_name = "%s"%argument.name
param_names.append(argument_name)
argument_type = "%s"%argument.type
argument_types=argument_type.split(" ")
#
# Check if the parameter is a typedef defined in another OCC package
#
argument_type_name = argument_types[0]
#
# The argument type_name may be Standard_Real, gp_Pnt etc.
# The associated header must be added to the swig .if file in order to
# properly compile. This is then the strategy:
# Example: V3d package is parsed
# - if the argument_type_name startswith V3d_, it's defined in this module. Pass.
# - if the argument_type_name does'nt start with V3d, (for ex gp_), then add the header
# to the list of additionnal headers.
#
#
t = self.CheckParameterIsTypedef(argument_type_name)
if t:
if (t!=self.MODULE_NAME):
self.AddDependency(t)
else:#it's not a type def
if (not argument_type_name.startswith('%s_'%self.MODULE_NAME)) and \
(not argument_type_name.startswith('Handle_%s_'%self.MODULE_NAME)) and\
(not '::' in argument_type_name) and \
(not argument_type in ['int']):#external dependency. Add header
header_to_add = '%s.hxx'%argument_type_name
if not (header_to_add in self.NEEDED_HXX):
self.NEEDED_HXX.append('%s.hxx'%argument_type_name)
#
# Find argument default value
#
argument_default_value = "%s"%argument.default_value
if len(argument_types)==1:
to_write += "%s "%argument_types[0]
elif argument_types[0].startswith('std::list'):
tmp = argument_types[0]
tmp = tmp.split('<')[1]
tmp = tmp.split(',')[0]
if tmp=='std::basic_string':
tmp='std::string'
#if tmp=='std::basic_string':
# tmp='std::basic_string<char>'
argument_types[0] = 'std::list'
argument_types[1] = tmp
to_write += "%s<%s>"%(argument_types[0],argument_types[1])
param_list.append(["String","aString"])
elif argument_types[0].startswith('std::vector<int') and len(argument_types)==4:
to_write += 'std::vector<int> %s'%argument_name
elif argument_types[0].startswith('std::vector<double') and len(argument_types)==4:
to_write += 'std::vector<double> %s'%argument_name
elif argument_types[1]=='*' and len(argument_types)==2:
#Case: GEOM_Engine* theEngine
to_write += "%s%s %s"%(argument_types[0],argument_types[1],argument_name)
param_list.append([argument_types[0],argument_name])
elif len(argument_types)==3:
#ex: Handle_WNT_GraphicDevice const &
#or const TopoDS_Shape &
#In that case, the & reference can be safely removed if the class has defined
# a copy constructor
argument_types = self.process_by_ref_argument(argument_types)
if len(argument_types)==2:#removed a '&'
to_write += "%s %s %s"%(argument_types[1],argument_types[0],argument_name)
else:
to_write += "%s %s %s%s"%(argument_types[1],argument_types[0],argument_types[2],argument_name)
param_list.append([argument_types[1],argument_name])
elif (len(argument_types)==2 and argument_types[1]!="&"):#ex: Aspect_Handle const
to_write += "%s %s %s"%(argument_types[1],argument_types[0],argument_name)
param_list.append([argument_types[0],argument_name])
elif len(argument_types)==4:
to_write += "%s %s%s"%(argument_types[0],argument_types[1],argument_name)
param_list.append([argument_types[1],argument_name])
else:
if ('Standard_Real &' in argument_type) or\
('Quantity_Parameter &' in argument_type) or\
('Quantity_Length &' in argument_type) or\
('V3d_Coordinate &' in argument_type): # byref Standard_Float parameter
to_write += 'Standard_Real &OutValue'
return_list.append(['Standard_Real',argument_name])
FUNCTION_MODIFIED = True
elif 'Standard_Integer &' in argument_type:# byref Standard_Integer parameter
to_write += 'Standard_Integer &OutValue'
return_list.append(['Standard_Integer',argument_name])
FUNCTION_MODIFIED = True
elif argument_type == 'int &': #appears in SMESH_Mesh grouping feature
to_write += 'Standard_Integer &OutValue'
elif argument_type == 'double &': #appears in SMESH_Mesh grouping feature
to_write += 'Standard_Real &OutValue'
elif 'FairCurve_AnalysisCode &' in argument_type:
to_write += 'FairCurve_AnalysisCode &OutValue'
return_list.append(['FairCurve_AnalysisCode',argument_name])
FUNCTION_MODIFIED = True
else:
to_write += "%s %s"%(argument_type,argument_name)
#if 'Standard_CString' in to_write:
# to_write = to_write.replace('Standard_CString','char *')
if argument_default_value!="None" and next_argument_default_value!="None":
# default value may be "1u"or "::AspectCentered" etc.
if argument_default_value=="1u":
argument_default_value = "1"
elif argument_default_value=="0u":
argument_default_value = "0"
elif argument_default_value.startswith('::'):
argument_default_value = argument_default_value[2:]
to_write += "=%s"%argument_default_value
default_value[argument_name]=argument_default_value
is_first = False
if mem_fun.decl_string.endswith(" const"):
END_WITH_CONST = True
else:
END_WITH_CONST = False
return to_write, return_list, param_list, arguments, default_value, END_WITH_CONST, param_names,FUNCTION_MODIFIED
def process_by_ref_return_type(self, return_type_string):
''' This method checks if the returned value is by ref:
for instance const gp_Pnt &.
In that case, try to remove the '&':
const gp_Pnt
so that the argument is returned by value. As a consequence, the object does not have to
be garbage collected since it remains in scope
'''
# if the argument is returned by value, do nothin
if not '&' in return_type_string:
return return_type_string
# First check in which module is defined the returned argument
elem = return_type_string.split(' ')[0].split('_')[0]
#don't process the handles since it's a bit special
if elem=='Handle':
#don't modify the string
return return_type_string
# if the module is in the list NOT_GARBAGED_MODULES, then remove the '&
# WARNING : the classes defined in such modules must have public copy ctors
if elem in ['gp','TopoDS']:
modified_string = return_type_string.replace('&','')
return modified_string
else:
return return_type_string
def write_function( self , mem_fun , parent_is_abstract):
"""
Write member functions declarations
"""
# Test if method already exposed
is_exportable = mem_fun.exportable
function_name = mem_fun.name
class_parent_name = mem_fun.parent.name
#FUNCTION_MODIFIED = False #is the function modified by any byref stuff?
param_list = [] # a dict that contain param names and their types (used for python docstring construction).
return_list = []
default_value={}
if (not is_exportable) and not(class_parent_name in function_name):#for constructors and destructor
print "\t\t %s method not exportable"%function_name
return True
if ("operator ::" in function_name): #Pb with SWIG
return True
if hasattr(mem_fun,"return_type"):
return_type = "%s"%mem_fun.return_type
else:
print "No return type found for this method!!!"
return False
#
# Check what headers to add for the return type
#
if return_type!='None' and not (' ' in return_type):
t = self.CheckParameterIsTypedef(return_type)
if t:
if (t!=self.MODULE_NAME):# and (t!='Standard'):
if t.startswith('Handle'):
t = t.split('_')[1]
self.AddDependency(t)
else:#it's not a type def
if (not return_type.startswith('%s_'%self.MODULE_NAME)) and \
(not return_type.startswith('Handle_%s_'%self.MODULE_NAME)) and \
(not return_type in ['void','int']) and (not '::' in return_type):#external dependency. Add header
header_to_add = '%s.hxx'%return_type
if not (header_to_add in self.NEEDED_HXX):
self.NEEDED_HXX.append('%s.hxx'%return_type)
# If the returned type is not in the scope, import the module
#
# First check the module name
if (not return_type in ['void','int']) and (not '::' in return_type):#
if return_type.startswith('Handle'):
module_name = return_type.split('_')[1]
print 'The module is :',module_name
else:
module_name = return_type.split('_')[0]
# then add this module to the list of modules to import
if module_name != self.MODULE_NAME and module_name in Modules.get_wrapped_modules_names():
if not (module_name in self.MODULES_TO_IMPORT) and module_name!='None':
self.MODULES_TO_IMPORT.append(module_name)
#
# Replace return type Standard_CString with char *
#
print "\t\t %s added."%function_name
to_write = ''#
# Handle 'Standard_Integer &' and 'Standard_Real &' return types
#
if (return_type in ['Standard_Integer &','Standard_Real &','Standard_Boolean &']) and not ('operator' in function_name):
# First get the string for arguments declaration
str_args,return_list,param_list,arguments, default_value,END_WITH_CONST,param_names,FUNCTION_MODIFIED = self.write_function_arguments(mem_fun)
# build param enum from params:
# ['a','b','c']->'a,b,c'
po = ''
k = len(param_names)
for i in range(k):
po+=param_names[i]
if i<k-1:
po+=','
typ = return_type.split(" ")[0] # -> Standard_Integer or Standard_Real
# Create Get function_name
to_write += '\t\t%feature("autodoc","1");\n'
to_write += '\t\t%extend {\n'
to_write += '\t\t\t\t%s Get%s(%s) {\n'%(typ,function_name,str_args)
to_write += '\t\t\t\treturn (%s) $self->%s(%s);\n'%(typ,function_name,po)
to_write += '\t\t\t\t}\n\t\t};\n'
# Create Set function_name
to_write += '\t\t%feature("autodoc","1");\n'
to_write += '\t\t%extend {\n'
if len(param_list)>0:
str_args2=","+str_args
else:
str_args2=str_args
to_write += '\t\t\t\tvoid Set%s(%s value %s) {\n'%(function_name,typ,str_args2)
to_write += '\t\t\t\t$self->%s(%s)=value;\n'%(function_name,po)
to_write += '\t\t\t\t}\n\t\t};\n'
self.fp.write(to_write)
return True
# FEATURE DOCSTRING
# First try to find the key (necessary for overloaded functions
# the key can be Coord, Coord_1 or Coord_2
if self.MemberfunctionDocStrings.has_key(function_name):
key = function_name
else:
key = None
# Detect virtuality
if (mem_fun.virtuality==declarations.VIRTUALITY_TYPES.PURE_VIRTUAL) or (mem_fun.virtuality==declarations.VIRTUALITY_TYPES.VIRTUAL):
to_write+="\t\tvirtual"
# Detect static method
if mem_fun.has_static:
to_write+="\t\tstatic"
if not [class_parent_name,function_name] in self.STATIC_METHODS:
self.STATIC_METHODS.append([class_parent_name,function_name])
# on teste le cas suivant pour return_type:gp_Pnt const &, qu'il faut transformer en const gp_Pnt &
# test if the value is returned by reference. For that, just check if the '&' character
# is in the return type
if '&' in return_type:
# send the return_type string to the process_by_ref_return_type method
# and get the modified string
return_type = self.process_by_ref_return_type(return_type)
parts = return_type.split(" ")
if len(parts)==3:
return_type="%s %s %s"%(parts[1],parts[0],parts[2])
if return_type=="None":
to_write += "\t\t%s("%(function_name)
else:
to_write +="\t\t%s %s("%(return_type,function_name)
#
# Write arguments of the method
#
str,return_list,param_list,arguments, default_value,END_WITH_CONST, param_names,FUNCTION_MODIFIED = self.write_function_arguments(mem_fun)
#
# Check if operator==
#
if ("operator==") in function_name:
to_write="\t\t%extend{\n"
to_write+="\t\t\tbool __eq_wrapper__(%s) {\n"%str
to_write+="\t\t\t\tif (*self==%s) return true;\n"%param_names[0]
to_write+="\t\t\t\telse return false;\n"
to_write+="\t\t\t}\n\t\t}\n"
self.fp.write(to_write)
self.CLASS_WRAP_EQ = True
self._CURRENT_CLASS_EXPOSED_METHODS.append(to_write)
return True
#
# Check if operator!=
#
if ("operator!=") in function_name:
to_write="\t\t%extend{\n"
to_write+="\t\t\tbool __ne_wrapper__(%s) {\n"%str
to_write+="\t\t\t\tif (*self!=%s) return true;\n"%param_names[0]
to_write+="\t\t\t\telse return false;\n"
to_write+="\t\t\t}\n\t\t}\n"
self.fp.write(to_write)
self.CLASS_WRAP_NE = True
self._CURRENT_CLASS_EXPOSED_METHODS.append(to_write)
return True
to_write += str
if END_WITH_CONST:
to_write += ") const;\n"
else:
to_write += ");\n"
if 'Standard_CString' in to_write:
to_write = to_write.replace('Standard_CString','char *')
if to_write in self._CURRENT_CLASS_EXPOSED_METHODS: #to avoid writing twice constructors
return True
if "&arg0);" in to_write: #constructor
return False
# dont't write constructors for abstract classes
if parent_is_abstract and ("%s();"%class_parent_name in to_write):
return False
#
# Finally, process Standard_OStream and Standard_ISteam selected methods
#
if len(arguments)==1: #Methods with only one Standard_Ostream/Standard_IStream & parameter
#if len(arguments)>0:
if 'Standard_OStream &' in '%s'%arguments[0].type:#argument_type:
to_write ='\t\t%feature("autodoc", "1");\n'
to_write+='\t\t%extend{\n\t\t\tstd::string '
to_write+='%sToString() {\n\t\t\tstd::stringstream s;\n'%function_name
to_write+='\t\t\tself->%s(s);\n'%function_name
to_write+='\t\t\treturn s.str();}\n\t\t};\n'
if 'std::istream &' in '%s'%arguments[0].type:#argument_type:
to_write = '\t\t%feature("autodoc", "1");\n'
to_write+='\t\t%extend{\n\t\t\tvoid '
to_write+='%sFromString(std::string src) {\n\t\t\tstd::stringstream s(src);\n'%function_name
to_write+='\t\t\tself->%s(s);}\n'%function_name
to_write+='\t\t};\n'
# Log
if FUNCTION_MODIFIED:
self.AddFunctionTransformation("%s::%s\n"%(class_parent_name,function_name))
# Write docstring to file
if FUNCTION_MODIFIED: # The docstring has to be changed
meth_doc = "%s("%function_name
index=1
for param in param_list:
meth_doc+=param[0]
meth_doc+=" "
meth_doc+=param[1]
if default_value.has_key(param[1]):
meth_doc+="=%s"%default_value[param[1]][:8]#eight digits maxi
if index<len(param_list):
meth_doc+=", "
index+=1
docstring = '\t\t%feature("autodoc",'
docstring+='"%s)'%meth_doc
# Add return
if len(return_list)<=1:#just one value
docstring+=' -> %s'%return_list[0][0]
else:
docstring+=' -> ['
index_2=1
for rt in return_list:
docstring+='%s'%rt[0]
if index_2<len(return_list):
docstring+=", "
index_2+=1
docstring+=']'
docstring+='");\n\n'
if function_name=='Edge':
print param_list
print docstring
# TODO : a problem with this docstring
else:
# automatically generated docstring by SWUG is perfect
docstring = '\t\t%feature("autodoc", "1");\n'
self.fp.write(docstring)
# Write method
self.fp.write(to_write)
self._CURRENT_CLASS_EXPOSED_METHODS.append(to_write)
def process_class(self,class_declaration):
"""
Process class
"""
self.CLASS_WRAP_EQ = False
self.CLASS_WRAP_NE = False
# list with exposed member functions decl_strings
CURRENT_CLASS_IS_ABSTRACT = False
self._CURRENT_CLASS_EXPOSED_METHODS = []
class_name = class_declaration.name
if class_name in self.ALREADY_EXPOSED:
return True#raise "Already imported"
# Check whether the class to process is outside this package
if class_name.startswith('Handle'):
from_package = class_name.split('_')[1]
else:
from_package = class_name.split('_')[0]
if from_package!=self.MODULE_NAME:
self.AddDependency(from_package)
return True
if class_declaration.is_abstract: #cannot instanciate abstract class
CURRENT_CLASS_IS_ABSTRACT = True
# That's ok, let's go for this class
print "####### class %s ##########"%class_name
# getting docstrings
#if self._generate_doc and not ('Handle' in class_name):
# self.ClassDocstring, self.MemberfunctionDocStrings = BuildDocstring.GetClassDocstrings(class_name)
# on traite d'abord la classe qui est derivee
if self.DERIVED.has_key(class_name):
inherits_from = self.DERIVED[class_name]
print "\t\tInherits from %s"%inherits_from
class_to_perform = self._mb.classes(inherits_from).declarations[0]
if not class_to_perform.name in self.CLASSES_TO_EXCLUDE:
self.process_class(class_to_perform)
# Check protected constructors
PROTECTED_CONSTRUCTOR = False
for protected_method in class_declaration.protected_members:
if class_name == protected_method.name:
PROTECTED_CONSTRUCTOR = True
print 'class %s has protected constructor'%class_name
# Check protected destructors
PROTECTED_DESTRUCTOR = False
for protected_method in class_declaration.protected_members:
if "~%s"%class_name == protected_method.name:
PROTECTED_DESTRUCTOR = True
print 'class %s has protected destructor'%class_name
#
# Affichage du nom de la classe
#
self.fp.write("\n\n%nodefaultctor ")
self.fp.write("%s;\n"%class_name)
if PROTECTED_DESTRUCTOR:
self.fp.write("\n\n%nodefaultdtor ")
self.fp.write("%s;\n"%class_name)
# Adding %docstring SWIG directive
#if self._generate_doc and not ('Handle' in class_name):
# self.fp.write('%feature("docstring") ')
# self.fp.write('%s '%class_name)
# self.fp.write('"%s";\n'%self.ClassDocstring)
# Check if this class inherits from antoher one
if not self.DERIVED.has_key(class_name):
self.fp.write("class %s {\n"%class_name)
else:
self.fp.write("class %s : public %s {\n"%(class_name,self.DERIVED[class_name]))
self.fp.write("\tpublic:\n")
if len(class_declaration.derived)>0:
for other_classes in class_declaration.derived:
print "\t\t%s"%other_classes.related_class.name
# Processing class internal enums, or enums that are defined inside a C++ class
#
# For instance, in the file SMESH_Hypothesis.hxx:
#
#class SMESH_EXPORT SMESH_Hypothesis: public SMESHDS_Hypothesis
#{
#public:
# enum Hypothesis_Status // in the order of severity
# {
# HYP_OK = 0,
# HYP_MISSING, // algo misses a hypothesis
# HYP_CONCURENT, // several applicable hypotheses
# HYP_BAD_PARAMETER,// hy
# Aim of the following lines is to handle the Hypothesis_Status enum defined
# in the SMESH_Hypothesis class and add the corresponding code to the SWIG file.
# protected_enums is a list of encountered protected defined enums.
# TODO: find a way to find automatically whether or not the enum is protected
protected_enums=['PointLocation','Comparison','Logical','HypothesisType','VValue','IValueIndex','VValueIndex','SValueIndex','ValueIndex',\
'ParameterType','' #AWfull Tweak to exclude a protected enum in SMESH_Block\
]
try:
class_declaration.enumerations() #if no internal enum, an exception is raised by pygccxml
HAVE_INTERNAL_ENUMS = True
except:
HAVE_INTERNAL_ENUMS = False
if HAVE_INTERNAL_ENUMS:
class_enums_tempdict = {} #a dict {} = [enum_name:enum_value]
for class_enum in class_declaration.enumerations():
if class_enum.name not in protected_enums:
# TODO: better handle of privade enums
class_enums_tempdict[class_enum.name]=class_enum.values
# Then add the lines to write
for class_enum_name in class_enums_tempdict.keys():
self.fp.write("\t\tenum %s {\n"%class_enum_name)
for class_enum_values in class_enums_tempdict[class_enum_name]:
self.fp.write("\t\t\t%s,\n"%class_enum_values[0])
self.fp.write("\t\t};\n")
# Processing methods for this class
# The implementation is a loop over the methods found by pygccxml
print "\t### Member functions for class %s ###"%class_declaration.name
HAVE_HASHCODE = False
# process all public methods
for mem_fun in class_declaration.public_members:#member_functions():
# Member functions to exclude
function_name = mem_fun.name
if function_name == 'HashCode': #function that have a special HashCode
nb_arguments = len(mem_fun.arguments)
if nb_arguments == 1:
HAVE_HASHCODE = True
if (function_name.startswith('~')):#ignore destructor
pass
elif not self.MEMBER_FUNCTIONS_TO_EXCLUDE.has_key(class_name):
self.write_function(mem_fun,CURRENT_CLASS_IS_ABSTRACT)
elif function_name not in self.MEMBER_FUNCTIONS_TO_EXCLUDE[class_name]:
self.write_function(mem_fun,CURRENT_CLASS_IS_ABSTRACT)
# Add __eq__ method is needed
if self.CLASS_WRAP_EQ:
to_write = "\t\t%"
to_write += "pythoncode {\n"
to_write += "\t\tdef __eq__(self,right):\n"
to_write += "\t\t\ttry:\n"
to_write += "\t\t\t\treturn self.__eq_wrapper__(right)\n"
to_write += "\t\t\texcept:\n"
to_write += "\t\t\t\treturn False\n"
to_write += "\t\t}\n"
self.fp.write(to_write)
# Add __eq__ method is needed
if self.CLASS_WRAP_NE:
to_write = "\t\t%"
to_write += "pythoncode {\n"
to_write += "\t\tdef __ne__(self,right):\n"
to_write += "\t\t\ttry:\n"
to_write += "\t\t\t\treturn self.__ne_wrapper__(right)\n"
to_write += "\t\t\texcept:\n"
to_write += "\t\t\t\treturn True\n"
to_write += "\t\t}\n"
self.fp.write(to_write)
self.fp.write("\n};")
#
# Adding a method GetObject() to Handle_* classes
#
if (class_name.startswith('Handle_')):
self.fp.write("\n%")
self.fp.write("extend %s {\n"%class_name)
pointed_class = class_name[7:]
self.fp.write("\t%s* GetObject() {\n"%pointed_class)
self.fp.write("\treturn (%s*)$self->Access();\n\t}\n};"%pointed_class)
#
# Adding a method GetHandle() to objects managed by handles
#
if ('Handle_%s'%class_name) in self.ALREADY_EXPOSED:
self.fp.write("\n%")
self.fp.write("extend %s {\n"%class_name)
handle_class_name = 'Handle_%s'%class_name
self.fp.write("\t%s GetHandle() {\n"%handle_class_name)
self.fp.write("\treturn *(%s*) &$self;\n\t}\n};"%handle_class_name)
if HAVE_HASHCODE:
self.fp.write("\n%")
self.fp.write("extend %s {\n"%class_name)
handle_class_name = 'Handle_%s'%class_name
self.fp.write("\tStandard_Integer __hash__() {\n")
self.fp.write("\treturn $self->HashCode(2147483647);\n\t}\n};")
#
# Overload __hash__() method for objects that inherits from Standard_Transient
#
elif ('Handle_%s'%class_name in self.ALREADY_EXPOSED):
self.fp.write("\n%")
self.fp.write("extend %s {\n"%class_name)
handle_class_name = 'Handle_%s'%class_name
self.fp.write("\tStandard_Integer __hash__() {\n")
self.fp.write("\treturn HashCode((Standard_Address)$self,2147483647);\n\t}\n};")
#
# Or for functions that have a special HashCode function (TopoDS, Standard_GUID etc.)
#
#if not (class_name.startswith('GEOMAlgo') and class_name.startswith('NCollection')):#issues with GEOMAlgo_Clsf destructor, protected
if not PROTECTED_DESTRUCTOR:
self.fp.write('\n%')
self.fp.write('feature("shadow") %s::~%s '%(class_name,class_name))
self.fp.write('%{\n')
self.fp.write('def __del__(self):\n')
#self.fp.write('\tglobal occ_gc\n')
self.fp.write('\ttry:\n')
self.fp.write('\t\tself.thisown = False\n')#detach python object/C++ object
self.fp.write('\t\tGarbageCollector.garbage.collect_object(self)\n')
self.fp.write('\texcept:\n\t\tpass\n')
#self.fp.write('\texcept:\n\t\tpass\n')
self.fp.write('%}\n')
# Customize destructor
#self.fp.write('\n%')
#self.fp.write('extend %s {\n'%class_name)
#self.fp.write('\t~%s() {\n\tchar *__env=getenv("PYTHONOCC_VERBOSE");\n\tif (__env){printf("## Call custom destructor for instance of %s\\n");}'%(class_name,class_name))
#if class_name == 'BRepAlgoAPI_BooleanOperation':
# self.fp.write('\n\t$self->Destroy();\n')
#self.fp.write('\n\t}\n};\n')
# Customize destructor
self.fp.write('\n%')
self.fp.write('extend %s {\n'%class_name)
self.fp.write('\tvoid _kill_pointed() {\n\t')
self.fp.write('\tdelete $self;')
self.fp.write('\n\t}\n};\n')
#
# Special method for XCAFApp_Application
#
if (class_name=='XCAFApp_Application'):
self.fp.write('%inline %{\n')
self.fp.write('Handle_XCAFApp_Application GetApplication()\n')
self.fp.write('{\n')
self.fp.write('return XCAFApp_Application::GetApplication();\n')
self.fp.write('}\n%}\n')
#
# Method ToString for Standard_GUID
#
if (class_name=='Standard_GUID'):
self.fp.write('%extend Standard_GUID {\n')
self.fp.write('\tStandard_PCharacter ToString() {\n')
self.fp.write('\tStandard_PCharacter tmpstr=NULL;\n')
self.fp.write('\ttmpstr = new char[37];\n')
self.fp.write('\tstrcpy(tmpstr,"00000000-0000-0000-0000-000000000000");\n')
self.fp.write('\t$self->ToCString(tmpstr);\n')
self.fp.write('\treturn tmpstr;\n\t}\n};\n')
#
# Pickling for TopoDS shapes
#
if (class_name=='TopoDS_Shape'):
self.fp.write('%extend TopoDS_Shape {\n%pythoncode {\n')
self.fp.write('\tdef __getstate__(self):\n')
self.fp.write('\t\tfrom BRepTools import BRepTools_ShapeSet\n')
self.fp.write('\t\tss = BRepTools_ShapeSet()\n')
self.fp.write('\t\tss.Add(self)\n')
self.fp.write('\t\tstr_shape = ss.WriteToString()\n')
self.fp.write('\t\tindx = ss.Locations().Index(self.Location())\n')
self.fp.write('\t\treturn str_shape, indx\n')
self.fp.write('\tdef __setstate__(self, state):\n')