File: genCtypesStructs.py

package info (click to toggle)
macromoleculebuilder 4.0.0%2Bdfsg-3.1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 122,532 kB
  • sloc: cpp: 23,631; python: 5,047; ansic: 2,101; awk: 145; perl: 144; makefile: 40; sh: 21
file content (220 lines) | stat: -rw-r--r-- 7,006 bytes parent folder | download | duplicates (5)
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
#!/usr/bin/env python

import sys
from collections import OrderedDict

def join(iterable, delimeter):
    s = ""
    for i in iterable[:-1]:
        s = s + i + delimeter
    s = s + iterable[-1]
    return s

cToPy = {"int": "c_int",
          "float": "c_float",
          "double": "c_double",
          "char": "c_char",
          "const char *": "c_char_p",
          "char *": "c_char_p",
          "bool": "c_bool"
          }

cToCppPrefixes = { "string": "string(",
                    "String": "String(",
                    "char *": "strdup(",
                    "const char *": "strdup(",
                    "ResidueID": "ResidueID("
                    }
cToCppSuffixes = { "string": ")",
                    "String": ")",
                    "char *": ")",
                    "const char *": ")",
                    "ResidueID": ", ' ')"
                    }

cppToC = {"string": "const char *",
          "String": "const char *",
          "char *": "char *",
          "const char *": "const char *",
          "ResidueID": "int"
          }

wrapPrefixes = {  "string": "strdup(",
                "String": "strdup(",
                "char *": "strdup(",
                "const char *": "strdup(",
                'ResidueID':""
             }

wrapSuffixes = {   "string": ".c_str())",
                "String": ".c_str())",
                "char *": ")",
                "const char *": ")",
                "ResidueID": ".getResidueNumber()"
            }

cFileName = sys.argv[1]

structures = OrderedDict()

name = None
comment = False
for line in open(cFileName, "r"):
    line = line.strip()
    if len(line) <= 0:
        continue
    # print line
    l = line.split()
    if line.startswith("private:"):
        comment = True
        continue
    if line.startswith("public:"):
        comment = False
        continue
    if name and comment and (line[-1] == "}" or ")" in line):
        line = "// "+line
        structures[name][line] = ""
        comment = False
        continue
    if name and (line[-1] == "{" or "(" in line):
        comment = True
        if ")" in line:
            line = "// "+line
            structures[name][line] = ""
            comment = False
    if line.startswith("}"):
        name = None
    if line.startswith("struct") or line.startswith("class"):
        name = l[1].split("{")[0]
        if name =="MMB_EXPORT":
            name = l[2].split("{")[0]
        structures[name] = OrderedDict()
        # print "class %s(Structure):" % name
        continue
    if name:
        if comment:
            line = "// "+line
            structures[name][line] = ""
            continue
        # Check if constructor/destructor
        field = line.split(";")[0]
        if len(field.split()) < 2:
            structures[name][field.split()[-1]] = "//"
            continue
        # Get type
        t = join(field.split()[:-1], " ")
        if t not in cToPy.keys()+cppToC.keys():
            print "Unknown type: " + t + " in " + name
            t = "//"+t
        # Get field name
        fieldName = field.split()[-1]
        structures[name][fieldName] = t

# C wrapper
fileOut = open(sys.argv[2], "w")      
for s in structures.keys():
    fileOut.write("typedef struct %s_wrapper{\n" % s)
    struct = structures[s]
    
    # C structure
    buff = "\tint mmbID;\n"
    for field in struct.keys():
        if field.startswith("//"):
            buff += "\t%s\n" % field
        else:
            t = struct[field]
            if t in cppToC.keys(): 
                t = cppToC[t]
            buff += "\t%s %s;\n" %(t, field)
    fileOut.write(buff + "}%s_wrapper;\n\n" % s)

    # Wrapping functions
    # void updateX_wrapper(X & _struct_, X_wrapper * _wrap_) // copy _struct_ to _wrap_
    buff = ""
    buff += "void update%s_wrapper(%s & _struct_, %s_wrapper * _wrap_){\n" % (s,s,s)
    for field in struct.keys():
        if field.startswith("//"):
            buff += "\t%s\n" % field
        else:
            t = struct[field]
            if t.startswith("//"): 
                buff += "//"
            wrapPrefix = ""
            wrapSuffix = ""
            if t in cppToC: 
                wrapPrefix = wrapPrefixes.get(t,"")
                wrapSuffix = wrapSuffixes.get(t,"")
            buff += "\t_wrap_->%s = %s_struct_.%s; //%s\n" %(field, wrapPrefix, field+wrapSuffix, t)
    fileOut.write(buff + "\n}\n")

    # void updateX(X_wrapper * _wrap_, X & _struct_) // copy _wrap_ to _struct_
    buff = ""
    buff += "void update%s(%s_wrapper * _wrap_, %s & _struct_){\n" % (s,s,s)
    for field in struct.keys():
        if field.startswith("//"):
            buff += "\t%s\n" % field
        else:
            t = struct[field]
            if t.startswith("//"): buff += "//"
            wrapPrefix = ""
            wrapSuffix = ""
            if t in cppToC: 
                wrapPrefix = cToCppPrefixes.get(t,"")
                wrapSuffix = cToCppSuffixes.get(t,"")
            buff += "\t_struct_.%s = %s_wrap_->%s; //%s\n" %(field, wrapPrefix, field+wrapSuffix, t)
    fileOut.write(buff + "\n}\n")
fileOut.close()


# Python wrapper
fileOut = open(sys.argv[3], "w")
fileOut.write("from ctypes import *\nfrom pyMMB import *\n\n")      
for s in structures.keys():
    fileOut.write("class %s_wrapper(Structure):\n" % s)
    fileOut.write("\t_fields_ = [ \n")
    struct = structures[s]
    buff = "\t\t\t('mmbID', c_int),\n"
    for field in struct.keys():
        try:
            t = struct[field]
            if t in cppToC.keys(): t = cppToC[t]
            buff += "\t\t\t('%s', %s),\n" %(field, cToPy[t])
        except KeyError:
            buff += "\t\t\t#('%s', %s),\n" %(field, struct[field]+ ": unknown ctype")
    buff = buff[:-2] + "\n"
    fileOut.write(buff + "\t\t\t]\n")
    
    functionsCode = """
    def __init__(self):
        Structure.__init__(self)
        # print "Init"
        call('updateParameterReader_wrapper', byref(self))
        Structure.__setattr__(self,"nonDefaultParameters",set())

    def __setattr__(self, name, value):
        # print __file__, "Set", name
        #cmd(name + " " + str(value))
        # We synchronize the wrapper with MMB to avoid changing other attributes
        call('updateParameterReader_wrapper', byref(self))
        Structure.__setattr__(self,name, value)
        Structure.__getattribute__(self, "nonDefaultParameters").update(set([name]))
        call('updateParameterReader', byref(self))

    def __getattribute__(self, name):
        # print __file__,  "Get", name
        call('updateParameterReader_wrapper', byref(self))
        return Structure.__getattribute__(self, name)
    """
    functionsCode = functionsCode.replace("    ", "\t")
    fileOut.write("%s\n" % functionsCode )

    fileOut.write("%s_ptr = POINTER(%s_wrapper)\n" % (s, s))

    buff = "MMB.update%s_wrapper.argtypes = [c_void_p, c_char_p]\n" % s
    buff += "MMB.update%s.argtypes = [c_void_p, c_char_p]\n" % s


    fileOut.write(buff)

fileOut.close()