- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtinycc.py
More file actions
Latest commit
700 lines (616 loc) · 24.3 KB
/
Copy pathtinycc.py
File metadata and controls
700 lines (616 loc) · 24.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
# The MIT License (MIT)
#
# Copyright (c) 2016 Joerg Breitbart
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
__author__='Joerg Breitbart'
__copyright__='Copyright (C) 2016 Joerg Breitbart'
__license__='MIT'
__version__='0.1.0'
importos
importsys
importctypes
importtypes
PY3=False
ifsys.version_info>= (3, 0):
PY3=True
unicode=str
# basic type mapping (array types are not supported)
TYPE_MAPPER= {
# stdint.h
ctypes.c_int8: 'int8_t',
ctypes.c_int16: 'int16_t',
ctypes.c_int32: 'int32_t',
ctypes.c_int64: 'int64_t',
ctypes.c_uint8: 'unsigned int8_t',
ctypes.c_uint16: 'unsigned int16_t',
ctypes.c_uint32: 'unsigned int32_t',
ctypes.c_uint64: 'unsigned int64_t',
# stddef.h
ctypes.c_size_t: 'size_t',
ctypes.c_ssize_t: 'ssize_t',
# basic types
ctypes.c_int: 'int',
ctypes.c_uint: 'unsigned int',
ctypes.c_long: 'long',
ctypes.c_longlong: 'long long',
ctypes.c_short: 'short',
ctypes.c_ulong: 'unsigned long',
ctypes.c_ulonglong: 'unsigned long long',
ctypes.c_ushort: 'unsigned short',
ctypes.c_double: 'double',
ctypes.c_float: 'float',
#ctypes.c_longdouble: 'long double', # long double not working in PyPy
ctypes.c_bool: '_Bool',
ctypes.c_byte: 'char',
ctypes.c_ubyte: 'unsigned char',
ctypes.c_char: 'char',
ctypes.c_wchar: 'wchar_t'
}
# add basic pointer types
TYPE_MAPPER.update({ctypes.POINTER(k): v+' *'fork, vinTYPE_MAPPER.items()})
# add basic special types
TYPE_MAPPER.update({
None: 'void',
ctypes.c_char_p: 'char *',
ctypes.c_wchar_p: 'wchar_t *',
ctypes.c_void_p: 'void *'
})
MODULEDIR=os.path.dirname(__file__)
TCCPATH=os.path.join(MODULEDIR, './linux/lib/tcc')
TCCLIB=os.path.join(MODULEDIR, './linux/lib/libtcc.so')
OUTPUT_TYPES= {
'memory': 1,
'exe' : 2,
'dll' : 3,
'obj' : 4
}
WINDOWS=False
ifsys.platform=='win32':
WINDOWS=True
TCCPATH=os.path.join(MODULEDIR, 'win32')
TCCLIB=os.path.join(MODULEDIR, 'win32\\libtcc.dll')
# tcc error function type
ERROR_FUNC=ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_char_p)
classDeclaration(object):
def__init__(self, code, decl=''):
self._c_decl=decl
self._c_code=code
classInlineGeneratorException(Exception):
pass
classTccException(Exception):
pass
class_ScopedStructureBase(type(ctypes.Structure)):
"""
Metaclass for a ScopedStructure class.
It creates the C declarations for the struct and their
c_method and callable_method decorated methods.
Naming:
A Python class name `Test` translates to `struct Test`
in C (no typedef declaration is added).
A decorated instance method `Test.method(self, ...) is
declared as `Test_method(struct Test * self, ...)` in C.
"""
_state_=None
_sname_=''
_fields_= []
def__init__(cls, name, bases, dct):
dct['_c_decl'] =_ScopedStructureBase._c_decl
dct['_c_code'] =_ScopedStructureBase._c_code
super(_ScopedStructureBase, cls).__init__(name, bases, dct)
ifcls.__name__notin ('CStructure', 'ScopedStructure'):
ifnotcls._sname_:
cls._sname_=cls.__name__
TYPE_MAPPER[cls] ='struct %s'%cls._sname_
TYPE_MAPPER[ctypes.POINTER(cls)] ='struct %s *'%cls._sname_
cls._state_.parts.append(cls)
fork, vindct.items():
if (isinstance(v, types.FunctionType) and
getattr(v, '_cmethod', False)):
v._proto(ctypes.POINTER(cls), cls._sname_)
@property
def_c_decl(cls):
return'struct %s;'%cls._sname_
@property
def_c_code(cls):
defmembers(fields):
forname, ctypeinfields:
ifissubclass(ctype, ctypes.Array):
yield' %s %s[%s];'% (
TYPE_MAPPER[ctype._type_], name, ctype._length_)
else:
yield' %s %s;'% (TYPE_MAPPER[ctype], name)
return'struct %s\n{\n%s\n};'% (
cls._sname_, '\n'.join(members(cls._fields_)))
classInlineGenerator(object):
"""
Class to handle inline C definitions and
prepare symbol import and export to C.
Code generation:
The code is generated by collecting all
defined parts and writing them into 3 sections:
top section
The section gets not autofilled by the generator.
Use it with `add_topdeclaration` for any early stuff
like including header files and such.
forward section
Used by the generator to do forward declarations
of the inline definitions.
definition section
Used by the generator to place the inline
definitions. With `add_definition` you can add
any code to this section.
Symbols:
For the provided decorators `c_function`, `c_method`,
`callable_function` and `callable_method` symbols are
automatically resolved between Python and C.
Make sure to bind the generator object to a relocated
memory state before using those functions.
NOTE: Due to the awkward handling of arrays in C
the decorators don't support C arrays as arguments or restype.
You would have to fall back to a pointer and
length argument anyways.
Example:
>>> from tinycc import TinyCC, InlineGenerator
>>> from ctypes import c_int
>>>
>>> gen = InlineGenerator()
>>>
>>> # C function to be used from Python
... @gen.c_function(c_int, c_int, c_int, c_int)
... def add_mul(a, b, c):
... "return mul(a + b, c);" # calls the Python function mul
...
>>> # Python function to be used from C
... @gen.callable_function(c_int, c_int, c_int)
... def mul(a, b):
... return a * b
...
>>> # compile the code
... state = TinyCC().create_state()
>>> state.compile(gen.code)
>>> state.relocate()
>>>
>>> # bind to state for symbol resolution
... gen.bind_state(state)
>>>
>>> # use it
... add_mul(23, 42, 7)
"""
def__init__(self):
self.parts= []
self.headerparts= []
self.state=None
self.symbols= []
defbind_state(self, state):
"""
Bind to the compiler state `state`.
Enables the symbol resolution between C and Python.
`state` must be of the memory type.
"""
ifnotisinstance(state, TccStateMemory):
raiseInlineGeneratorException('state must be a memory type')
ifnotstate._relocated:
raiseInlineGeneratorException('state is not relocated')
self.state=state
# reset code parts (reimport symbols to Python lazy)
forpartinself.parts:
part._c_func=None
# add callable symbols to state (export to C)
forsymbolinself.symbols:
self.state.set_symbol(*symbol)
defadd_topdeclaration(self, declaration):
"""
Add `declaration` to the top section.
"""
self.headerparts.append(Declaration(declaration))
defadd_definition(self, code, forward=''):
"""
Add `code` to the definition section. Optional
write `forward` to the forward section.
"""
self.parts.append(Declaration(code, forward))
@property
defcode(self):
"""
Property for the generated C code.
"""
pre='/* inline generated code */'
end='/*\n * inline generated code end\n */'
top='/*\n * top section\n */\n\n'
top+='\n'.join(part._c_codeforpartinself.headerparts)
forward='/*\n * forward section\n */\n\n'
forward+='\n'.join(part._c_declforpartinself.parts)
definition='/*\n * definitions\n */\n\n'
definition+='\n\n'.join(part._c_codeforpartinself.parts)
return'\n\n\n'.join(filter(bool, [pre, top, forward, definition, end]))
@property
defScopedStructure(self):
"""
Structure with decorators for c_method and callable_method.
Use this as parent class to define a struct which is usable
in C and Python.
"""
return_ScopedStructureBase(
'ScopedStructure', (ctypes.Structure,), {'_state_': self})
def_create_func(self, fname, restype, cargs, code):
"""
Construct C function source.
"""
PROTO='%s %s(%s)'
restype_c=TYPE_MAPPER[restype]
cargs_c=', '.join('%s %s'% (TYPE_MAPPER[ctype], name)
forname, ctypeincargs)
proto=PROTO% (restype_c, fname, cargs_cor'void')
returnproto+';', proto+'\n{%s\n}'%code
defc_function(self, restype, *argtypes):
"""
Decorator for defining a C function.
`restype` denotes the ctype of the return value,
`argtypes` the ctypes of the arguments.
Use the docstring for the actual code.
"""
defwrap(f):
definner(*args, **kwargs):
# TODO: apply args and kwargs appropriate to Python
ifnotf._c_func:
f._c_func=f._c_func_proto()
returnf._c_func(*args)
ifPY3:
name=f.__name__
varnames=f.__code__.co_varnames
else:
name=f.func_name
varnames=f.func_code.co_varnames
cargs=zip(varnames, argtypes)
f._c_decl, f._c_code=self._create_func(name, restype, cargs, f.__doc__)
f._c_func_proto=lambda: self.state.get_symbol(name,
ctypes.CFUNCTYPE(restype, *argtypes))
f._c_func=None
self.parts.append(f)
returninner
returnwrap
defc_method(self, restype, *argtypes, **ckwargs):
"""
Decorator for declaring a C function with the first
argument as pointer to the current ScopedStructure object.
It is used to mimic method like behavior in C.
The function is named as Classname_methodname, e.g.
an instance method `Test.do_something(self, ...)` in Python
translates to `Test_do_something(struct Test *self, ...)` in C.
"""
defwrap(f):
definner(self, *args, **kwargs):
# TODO: apply args and kwargs appropriate to Python
ifnotf._c_func:
f._c_func=f._c_func_proto()
returnf._c_func(self, *args)
defproto(pointer, clsname):
ifPY3:
name=f.__name__
varnames=f.__code__.co_varnames
else:
name=f.func_name
varnames=f.func_code.co_varnames
args= [pointer] +list(argtypes)
cargs=zip(varnames, args)
fname=clsname+'_'+name
decl, code=self._create_func(fname, restype, cargs, f.__doc__)
f._c_decl=decl
f._c_code=code
self.parts.append(f)
f._c_func_proto=lambda: self.state.get_symbol(fname,
ctypes.CFUNCTYPE(restype, *args))
f._c_func=None
inner._cmethod=True
inner._proto=proto
returninner
returnwrap
defcallable_function(self, restype, *argtypes):
"""
Decorator to make a Python function callable from C.
"""
defwrap(f):
f._c_code=''
name=f.__name__ifPY3elsef.func_name
cargs_c=', '.join('%s'%TYPE_MAPPER[ctype] forctypeinargtypes)
f._c_decl='%s (*%s)(%s);'% (TYPE_MAPPER[restype], name, cargs_cor'void')
self.symbols.append((name, ctypes.CFUNCTYPE(restype, *argtypes)(f)))
self.parts.append(f)
returnf
returnwrap
defcallable_method(self, restype, *argtypes, **ckwargs):
"""
Decorator to make a ScopedStruture method callable from C.
Follows the naming convention of the c_method decorator in C.
"""
defwrap(f):
definner(self, *args, **kwargs):
returnf(self.contents, *args, **kwargs)
defproto(pointer, clsname):
name=f.__name__ifPY3elsef.func_name
args=tuple([pointer] +list(argtypes))
fname=clsname+'_'+name
f._c_code=''
cargs_c=', '.join('%s'%TYPE_MAPPER[ctype] forctypeinargs)
f._c_decl='%s (*%s)(%s);'% (TYPE_MAPPER[restype], fname, cargs_cor'void')
self.symbols.append((fname, ctypes.CFUNCTYPE(restype, *args)(inner)))
self.parts.append(f)
f._cmethod=True
f._proto=proto
returnf
returnwrap
classTccState(object):
"""
Base class for compile states.
Handles the low level stuff to work with tcc.
"""
def__init__(self, tcc, libpath, encoding):
self.tcc=tcc
self.encoding=encoding
self.ctx=self.tcc.lib.tcc_new()
self.tcc.states.append(self.ctx)
self._set_tcc_path(libpath)
self.tcc.lib.tcc_set_error_func(self.ctx, 0, self._error())
self.output=0
self.tcc_path=libpath
self.options= []
self.defines= {}
self.include_paths= []
self.libraries= []
self.link_paths= []
self.files= []
self._compiled=False
def_encode(self, value):
ifisinstance(value, unicode):
returnvalue.encode(self.encoding)
returnvalue
def_set_output(self, output):
self.tcc.lib.tcc_set_output_type(self.ctx, output)
self.output=output
def_error(self):
defcb(_, msg):
# TODO: better error msg handling
print(msg)
self._error_function=ERROR_FUNC(cb)
returnself._error_function
def_set_tcc_path(self, path):
self.tcc_path=path
self.tcc.lib.tcc_set_lib_path(self.ctx, self._encode(self.tcc_path))
defadd_option(self, option):
"""
Add a commandline option to the state.
"""
self.options.append(option)
self.tcc.lib.tcc_set_options(self.ctx, self._encode(option))
defdefine(self, symbol, value=None):
"""
Define preprocessor `symbol` with optional `value`.
"""
self.defines[symbol] =None
self.tcc.lib.tcc_define_symbol(self.ctx, symbol, self._encode(value))
defundefine(self, symbol):
"""
Undefine preprocessor `symbol`.
"""
try:
delself.defines[symbol]
exceptKeyError:
raiseTccException(b'define'+symbol+b'not set')
self.tcc.lib.tcc_undefine_symbol(self.ctx, self._encode(symbol))
defadd_include_path(self, path):
"""
Add an include path (equivalent to -Ipath).
"""
self.include_paths.append(path)
self.tcc.lib.tcc_add_include_path(self.ctx, self._encode(path))
defadd_library(self, name):
"""
Add a library. `name` is the same as the argument of the '-l' option.
"""
self.libraries.append(name)
self.tcc.lib.tcc_add_library(self.ctx, self._encode(name))
defadd_link_path(self, path):
"""
Add a linker path (equivalent to -Lpath).
"""
self.link_paths.append(path)
self.tcc.lib.tcc_add_library_path(self.ctx, self._encode(path))
defadd_file(self, path):
"""
Add a file ressource to the compile state.
"""
ifself.tcc.lib.tcc_add_file(self.ctx, self._encode(path)) ==-1:
raiseTccException('error adding file')
def_add_symbol(self, symbol, value):
"""
Add a `symbol` with `value` to the compiler state.
`value` must be a pointer type to the actual value.
Use this with caution as it is likely to fail on some
architectures (ARM at least).
To avoid problems during compilation with imported
Python symbols better use the `set_symbol` method.
"""
ifself.tcc.lib.tcc_add_symbol(self.ctx, self._encode(symbol), value) ==-1:
raiseTccException('error while adding symbol')
defcompile(self, source):
"""
Compile the sourcecode in `source`.
"""
print(self._encode(source).decode('utf-8'))
ifself.tcc.lib.tcc_compile_string(self.ctx, self._encode(source)) ==-1:
raiseTccException('compile error')
self._compiled=True
classTccStateFile(TccState):
"""
Compile state for file output. Used for 'exe', 'dll' and 'obj' states.
"""
def__init__(self, tcc, libpath, output, encoding='UTF-8'):
TccState.__init__(self, tcc, libpath, encoding)
self._set_output(OUTPUT_TYPES[output])
defwrite_file(self, filename):
"""
Link and write to `filename`.
"""
ifself.tcc.lib.tcc_output_file(self.ctx, self._encode(filename)) ==-1:
raiseTccException('error while linking/writing file')
classTccStateMemory(TccState):
"""
Compile state for in memory builds.
Use this state to compile and load c code into the current process.
After compilation the symbols are accessible via `get_symbol`.
"""
def__init__(self, tcc, libpath, encoding='UTF-8'):
TccState.__init__(self, tcc, libpath, encoding)
self._set_output(OUTPUT_TYPES['memory'])
self._relocated=False
defrelocate(self):
"""
Relocate symbols for further usage. Must be done after
compiling the source before accessing the symbols with `get_symbol`.
"""
# NOTE: only TCC_RELOCATE_AUTO is supported
ifnotself._compiled:
raiseTccException('need to compile first')
ifself._relocated:
raiseTccException('already relocated')
ifself.tcc.lib.tcc_relocate(self.ctx, 1) ==-1:
raiseTccException('relocate error')
self._relocated=True
def_get_address(self, symbol):
ifnotself._compiled:
raiseTccException('need to compile/relocate first')
ifnotself._relocated:
raiseTccException('need to relocate first')
address=self.tcc.lib.tcc_get_symbol(self.ctx, self._encode(symbol))
ifnotaddress:
raiseTccException('symbol not found')
returnaddress
defget_symbol(self, symbol, ctype):
"""
Resolve a symbol at runtime and attach to type `ctype`.
"""
ifissubclass(ctype, ctypes._CFuncPtr):
returnctype(self._get_address(symbol))
ifissubclass(ctype, (ctypes._SimpleCData, ctypes.Structure,
ctypes.Union, ctypes._Pointer, ctypes.Array)):
returnctype.from_address(self._get_address(symbol))
raiseTccException('cannot handle type information')
defset_symbol(self, symbol, value):
"""
Set a symbol to `value` at runtime.
This is more reliable on different architectures than
injecting symbols directly by the `_add_symbol` method.
Unlike `_add_symbol` this method injects a value
after compilation. Therefore the symbol must be declared in C.
Example for importing a Python function to C:
- create a Python function
def test(a, b):
return a + b
- declare the function in C as a function pointer, eg.
`int (*test)(int, int);`
- compile and relocate
- create a C function type of the Python function
cfunc = CFUNCTYPE(c_int, c_int, c_int)(test)
- set the function pointer
set_function('test', cfunc)
"""
ctypes.pointer(
type(value).from_address(self._get_address(symbol))
)[0] =value
classTccStateRun(TccState):
"""
Compile state for direct running of the code.
Calling `run` will enter the main function of the code.
"""
def__init__(self, tcc, libpath, encoding='UTF-8'):
TccState.__init__(self, tcc, libpath, encoding)
self._set_output(OUTPUT_TYPES['memory'])
self._relocated=False
self._run=False
defrun(self, arguments):
"""
Call the main function of the compiled code with `arguments`.
"""
ifnotself._compiled:
raiseTccException('not compiled')
ifself._run:
raiseTccException('can only run once')
argc=len(arguments)
argv= (ctypes.POINTER(ctypes.c_char) *argc)()
argv[:] = [ctypes.create_string_buffer(self._encode(s)) forsinarguments]
returnself.tcc.lib.tcc_run(self.ctx, argc, argv)
classTinyCC(object):
"""
Class for the TCC environment initialization.
With the optional arguments `shared_library` and `tccpath` the used
tcc can be customized. By default they point to the libtcc and tcc folder
in the tinycc package.
Call `create_state` for a compile state to work with.
example for run state:
>>> state = TinyCC().create_state('run')
>>> c_code = '''#include <stdio.h>\nvoid main(void){printf("Hello World!");}'''
>>> state.compile(c_code)
>>> state.run([])
example for memory state:
>>> state = TinyCC().create_state() # defaults to 'memory'
>>> c_code = '''#include <stdio.h>\nvoid main(void){printf("Hello World!");}'''
>>> state.compile(c_code)
>>> state.relocate()
>>> main = state.get_symbol('main', ctypes.CFUNCTYPE(None))
>>> main()
>>> main() # unlike in run state main can be called multiple times
example to write an executable:
>>> state = TinyCC().create_state('exe')
>>> c_code = '''#include <stdio.h>\nvoid main(void){printf("Hello World!");}'''
>>> state.compile(c_code)
>>> state.write_file('./hello')
"""
instance=None
def__new__(cls, *args, **kwargs):
ifnotcls.instance:
cls.instance=object.__new__(cls)
returncls.instance
def__init__(self, shared_library=TCCLIB, tccpath=TCCPATH, encoding='UTF-8'):
self.lib=ctypes.CDLL(shared_library)
self.libpath=tccpath
self.lib.tcc_get_symbol.restype=ctypes.c_int
self.states= []
self.encoding=encoding
defcreate_state(self, output_type='memory', encoding=None):
"""
Convenient method to create a compile state.
`output_type` supports the following values:
'memory' - default, memory build for loading into the current process
with support for inspecting exported symbols
'run' - memory build for direct calling of the main function
(no further symbol inspection possible)
'obj' - state for writing an object file
'exe' - state for writing an executable
'dll' - state for writing a shared library
"""
ifnotencoding:
encoding=self.encoding
ifoutput_type=='memory':
state=TccStateMemory(self, self.libpath, encoding=encoding)
elifoutput_type=='run':
state=TccStateRun(self, self.libpath, encoding=encoding)
else:
state=TccStateFile(self, self.libpath, output_type, encoding=encoding)
returnstate