1"""
2Generic setup.py file for PyObjC framework wrappers.
3
4This file should only be changed in pyobjc-core and then copied
5to all framework wrappers.
6"""
7
8__all__ = ('setup', 'Extension', 'Command')
9
10import sys
11from pkg_resources import Distribution
12
13try:
14    import setuptools
15
16except ImportError:
17    import distribute_setup
18    distribute_setup.use_setuptools()
19
20from setuptools.command import test
21from setuptools.command import build_py
22
23from distutils import log
24
25extra_args=dict(
26    use_2to3 = True,
27)
28
29
30class oc_build_py (build_py.build_py):
31    def build_packages(self):
32        log.info("overriding build_packages to copy PyObjCTest")
33        p = self.packages
34        self.packages = list(self.packages) + ['PyObjCTest']
35        try:
36            build_py.build_py.build_packages(self)
37        finally:
38            self.packages = p
39
40
41
42class oc_test (test.test):
43    def run_tests(self):
44        import sys, os
45
46        rootdir =  os.path.dirname(os.path.abspath(__file__))
47        if rootdir in sys.path:
48            sys.path.remove(rootdir)
49
50        # Ensure that any installed versions of this package aren't on sys.path
51        ei_cmd = self.get_finalized_command('egg_info')
52        egg_name = ei_cmd.egg_name.replace('-', '_')
53
54        to_remove = []
55        for dirname in sys.path:
56            bn = os.path.basename(dirname)
57            if bn.startswith(egg_name + "-"):
58                to_remove.append(dirname)
59
60        for dirname in to_remove:
61            log.info("removing installed %r from sys.path before testing"%(dirname,))
62            sys.path.remove(dirname)
63
64        # Actually run the tests
65        if sys.version_info[0] == 2:
66            sys.path.insert(0, rootdir)
67
68        import PyObjCTest
69        import unittest
70        from pkg_resources import EntryPoint
71        loader_ep = EntryPoint.parse("x="+self.test_loader)
72        loader_class = loader_ep.load(require=False)
73
74        unittest.main(None, None, [unittest.__file__]+self.test_args, testLoader=loader_class())
75
76
77
78from setuptools import setup as _setup, Extension as _Extension, Command
79from distutils.errors import DistutilsPlatformError
80from distutils.command import build, install
81from setuptools.command import develop, test, build_ext, install_lib
82import pkg_resources
83import shutil
84import os
85import plistlib
86import sys
87import __main__
88
89CLASSIFIERS = filter(None,
90"""
91Development Status :: 5 - Production/Stable
92Environment :: Console
93Environment :: MacOS X :: Cocoa
94Intended Audience :: Developers
95License :: OSI Approved :: MIT License
96Natural Language :: English
97Operating System :: MacOS :: MacOS X
98Programming Language :: Python
99Programming Language :: Python :: 2
100Programming Language :: Python :: 2.6
101Programming Language :: Python :: 2.7
102Programming Language :: Python :: 3
103Programming Language :: Python :: 3.1
104Programming Language :: Python :: 3.2
105Programming Language :: Objective C
106Topic :: Software Development :: Libraries :: Python Modules
107Topic :: Software Development :: User Interfaces
108""".splitlines())
109
110
111def get_os_level():
112    pl = plistlib.readPlist('/System/Library/CoreServices/SystemVersion.plist')
113    v = pl['ProductVersion']
114    return tuple(map(int, v.split('.')[:2]))
115
116class pyobjc_install_lib (install_lib.install_lib):
117    def get_exclusions(self):
118        result = install_lib.install_lib.get_exclusions(self)
119        for fn in install_lib._install_lib.get_outputs(self):
120            if 'PyObjCTest' in fn:
121                result[fn] = 1
122
123        result['PyObjCTest'] = 1
124        result[os.path.join(self.install_dir, 'PyObjCTest')] = 1
125        for fn in os.listdir('PyObjCTest'):
126            result[os.path.join('PyObjCTest', fn)] = 1
127            result[os.path.join(self.install_dir, 'PyObjCTest', fn)] = 1
128
129        return result
130
131
132
133class pyobjc_build_ext (build_ext.build_ext):
134    def run(self):
135
136        # Ensure that the PyObjC header files are available
137        # in 2.3 and later the headers are in the egg,
138        # before that we ship a copy.
139        dist, = pkg_resources.require('pyobjc-core')
140
141        include_root = os.path.join(self.build_temp, 'pyobjc-include')
142        if os.path.exists(include_root):
143            shutil.rmtree(include_root)
144
145        os.makedirs(include_root)
146        if dist.has_metadata('include'):
147            for fn in dist.metadata_listdir('include'):
148                data = dist.get_metadata('include/%s'%(fn,))
149                open(os.path.join(include_root, fn), 'w').write(data)
150
151        else:
152            data = gPyObjCAPI_H
153            open(os.path.join(include_root, 'pyobjc-api.h'), 'w').write(data)
154
155        for e in self.extensions:
156            if include_root not in e.include_dirs:
157                e.include_dirs.append(include_root)
158
159        # Run the actual build
160        build_ext.build_ext.run(self)
161
162        # Then tweak the copy_extensions bit to ensure PyObjCTest gets
163        # copied to the right place.
164        extensions = self.extensions
165        self.extensions = [
166            e for e in extensions if e.name.startswith('PyObjCTest') ]
167        self.copy_extensions_to_source()
168        self.extensions = extensions
169
170
171
172def Extension(*args, **kwds):
173    """
174    Simple wrapper about distutils.core.Extension that adds additional PyObjC
175    specific flags.
176    """
177    os_level = get_os_level()
178    cflags =  ["-DPyObjC_BUILD_RELEASE=%02d%02d"%os_level]
179    ldflags = []
180    if os_level != (10, 4):
181        pass
182        pass
183    else:
184        cflags.append('-DNO_OBJC2_RUNTIME')
185
186    if 'extra_compile_args' in kwds:
187        kwds['extra_compile_args'] = kwds['extra_compile_args'] + cflags
188    else:
189        kwds['extra_compile_args'] = cflags
190
191    if 'extra_link_args' in kwds:
192        kwds['extra_link_args'] = kwds['extra_link_args'] + ldflags
193    else:
194        kwds['extra_link_args'] = ldflags
195
196    return _Extension(*args, **kwds)
197
198
199def setup(
200        min_os_level=None,
201        max_os_level=None,
202        cmdclass=None,
203        **kwds):
204
205
206    k = kwds.copy()
207    k.update(extra_args)
208
209    os_level = get_os_level()
210    os_compatible = True
211    if sys.platform != 'darwin':
212        os_compatible = False
213
214    else:
215        if min_os_level is not None:
216            if os_level < tuple(map(int, min_os_level.split('.'))):
217                os_compatible = False
218        if max_os_level is not None:
219            if os_level > tuple(map(int, max_os_level.split('.'))):
220                os_compatible = False
221
222    if cmdclass is None:
223        cmdclass = {}
224    else:
225        cmdclass = cmdclass.copy()
226
227    if not os_compatible:
228        def create_command_subclass(base_class):
229            if min_os_level != None:
230                if max_os_level != None:
231                    msg = "This distribution is only supported on MacOSX versions %s upto and including %s"%(
232                            min_os_level, max_os_level)
233                else:
234                    msg = "This distribution is only support on MacOSX >= %s"%(min_os_level,)
235            elif max_os_level != None:
236                    msg = "This distribution is only support on MacOSX <= %s"%(max_os_level,)
237            else:
238                    msg = "This distribution is only support on MacOSX"
239
240            class subcommand (base_class):
241                def run(self):
242                    raise DistutilsPlatformError(msg)
243
244            return subcommand
245
246        cmdclass['build'] = create_command_subclass(build.build)
247        cmdclass['test'] = create_command_subclass(oc_test)
248        cmdclass['install'] = create_command_subclass(pyobjc_install_lib)
249        cmdclass['develop'] = create_command_subclass(develop.develop)
250        cmdclass['build_py'] = create_command_subclass(oc_build_py)
251    else:
252        cmdclass['build_ext'] = pyobjc_build_ext
253        cmdclass['install_lib'] = pyobjc_install_lib
254        cmdclass['test'] = oc_test
255        cmdclass['build_py'] = oc_build_py
256
257
258
259    _setup(
260        cmdclass=cmdclass,
261        long_description=__main__.__doc__,
262        author='Ronald Oussoren',
263        author_email='pyobjc-dev@lists.sourceforge.net',
264        url='http://pyobjc.sourceforge.net',
265        platforms = [ "MacOS X" ],
266        package_dir = { '': 'Lib', 'PyObjCTest': 'PyObjCTest' },
267        dependency_links = [],
268        package_data = { '': ['*.bridgesupport'] },
269        test_suite='PyObjCTest',
270        zip_safe = False,
271        **k
272    )
273
274
275gPyObjCAPI_H="""\
276#ifndef PyObjC_API_H
277#define PyObjC_API_H
278
279/*
280 * Use this in helper modules for the objc package, and in wrappers
281 * for functions that deal with objective-C objects/classes
282 *
283 * This header defines some utility wrappers for importing and using
284 * the core bridge.
285 *
286 * This is the *only* header file that should be used to access
287 * functionality in the core bridge.
288 *
289 * WARNING: this file is not part of the public interface of PyObjC and
290 * might change or be removed without warning or regard for backward
291 * compatibility.
292 */
293
294#include "Python.h"
295#include <objc/objc.h>
296
297#import <Foundation/Foundation.h>
298
299
300
301
302
303#ifndef PyObjC_COMPAT_H
304#if (PY_VERSION_HEX < 0x02050000)
305typedef int Py_ssize_t;
306#define PY_FORMAT_SIZE_T ""
307#define Py_ARG_SIZE_T "n"
308#define PY_SSIZE_T_MAX INT_MAX
309
310#else
311
312#define Py_ARG_SIZE_T "i"
313#endif
314#endif
315
316#import <Foundation/NSException.h>
317
318struct PyObjC_WeakLink {
319	const char* name;
320	void (*func)(void);
321};
322
323
324/* threading support */
325#ifdef NO_OBJC2_RUNTIME
326#define PyObjC_DURING \
327		Py_BEGIN_ALLOW_THREADS \
328		NS_DURING
329
330#define PyObjC_HANDLER NS_HANDLER
331
332#define PyObjC_ENDHANDLER \
333		NS_ENDHANDLER \
334		Py_END_ALLOW_THREADS
335#else
336
337#define	PyObjC_DURING \
338		Py_BEGIN_ALLOW_THREADS \
339		@try {
340
341#define PyObjC_HANDLER } @catch(volatile NSObject* _localException) { \
342		NSException* localException __attribute__((__unused__))= (NSException*)_localException;
343
344#define PyObjC_ENDHANDLER \
345		} \
346		Py_END_ALLOW_THREADS
347
348#endif
349
350#define PyObjC_BEGIN_WITH_GIL \
351	{ \
352		PyGILState_STATE _GILState; \
353		_GILState = PyGILState_Ensure();
354
355#define PyObjC_GIL_FORWARD_EXC() \
356		do { \
357            PyObjCErr_ToObjCWithGILState(&_GILState); \
358		} while (0)
359
360
361#define PyObjC_GIL_RETURN(val) \
362		do { \
363			PyGILState_Release(_GILState); \
364			return (val); \
365		} while (0)
366
367#define PyObjC_GIL_RETURNVOID \
368		do { \
369			PyGILState_Release(_GILState); \
370			return; \
371		} while (0)
372
373
374#define PyObjC_END_WITH_GIL \
375		PyGILState_Release(_GILState); \
376	}
377
378
379
380#include <objc/objc-runtime.h>
381
382/* On 10.1 there are no defines for the OS version. */
383#ifndef MAC_OS_X_VERSION_10_1
384#define MAC_OS_X_VERSION_10_1 1010
385#define MAC_OS_X_VERSION_MAX_ALLOWED MAC_OS_X_VERSION_10_1
386
387#error "MAC_OS_X_VERSION_10_1 not defined. You aren't running 10.1 are you?"
388
389#endif
390
391#ifndef MAC_OS_X_VERSION_10_2
392#define MAC_OS_X_VERSION_10_2 1020
393#endif
394
395#ifndef MAC_OS_X_VERSION_10_3
396#define MAC_OS_X_VERSION_10_3 1030
397#endif
398
399#ifndef MAC_OS_X_VERSION_10_4
400#define MAC_OS_X_VERSION_10_4 1040
401#endif
402
403#ifndef MAC_OS_X_VERSION_10_5
404#define MAC_OS_X_VERSION_10_5 1050
405#endif
406
407/* Current API version, increase whenever:
408 * - Semantics of current functions change
409 * - Functions are removed
410 * Do not increase when adding a new function, the struct_len field
411 * can be used for detecting if a function has been added.
412 *
413 * HISTORY:
414 * - Version 2.2 adds PyObjCUnsupportedMethod_IMP
415 *       and PyObjCUnsupportedMethod_Caller
416 * - Version 2.1 adds PyObjCPointerWrapper_Register
417 * - Version 2 adds an argument to PyObjC_InitSuper
418 * - Version 3 adds another argument to PyObjC_CallPython
419 * - Version 4 adds PyObjCErr_ToObjCGILState
420 * - Version 4.1 adds PyObjCRT_AlignOfType and PyObjCRT_SizeOfType
421 *         (PyObjC_SizeOfType is now deprecated)
422 * - Version 4.2 adds PyObjCRT_SELName
423 * - Version 4.3 adds PyObjCRT_SimplifySignature
424 * - Version 4.4 adds PyObjC_FreeCArray, PyObjC_PythonToCArray and
425 *   		PyObjC_CArrayToPython
426 * - Version 5 modifies the signature for PyObjC_RegisterMethodMapping,
427 *	PyObjC_RegisterSignatureMapping and PyObjCUnsupportedMethod_IMP,
428 *      adds PyObjC_RegisterStructType and removes PyObjC_CallPython
429 * - Version 6 adds PyObjCIMP_Type, PyObjCIMP_GetIMP and PyObjCIMP_GetSelector
430 * - Version 7 adds PyObjCErr_AsExc, PyGILState_Ensure
431 * - Version 8 adds PyObjCObject_IsUninitialized,
432        removes PyObjCSelector_IsInitializer
433 * - Version 9 (???)
434 * - Version 10 changes the signature of PyObjCRT_SimplifySignature
435 * - Version 11 adds PyObjCObject_Convert, PyObjCSelector_Convert,
436     PyObjCClass_Convert, PyObjC_ConvertBOOL, and PyObjC_ConvertChar
437 * - Version 12 adds PyObjCObject_New
438 * - Version 13 adds PyObjCCreateOpaquePointerType
439 * - Version 14 adds PyObjCObject_NewTransient, PyObjCObject_ReleaseTransient
440 * - Version 15 changes the interface of PyObjCObject_New
441 * - Version 16 adds PyObjC_PerformWeaklinking
442 * - Version 17 introduces Py_ssize_t support
443 * - Version 18 introduces several API incompatibilities
444 */
445#define PYOBJC_API_VERSION 18
446
447#define PYOBJC_API_NAME "__C_API__"
448
449/*
450 * Only add items to the end of this list!
451 */
452typedef int (RegisterMethodMappingFunctionType)(
453			Class,
454			SEL,
455			PyObject *(*)(PyObject*, PyObject*, PyObject*),
456			void (*)(void*, void*, void**, void*));
457
458struct pyobjc_api {
459	int	      api_version;	/* API version */
460	size_t	      struct_len;	/* Length of this struct */
461	PyTypeObject* class_type;	/* PyObjCClass_Type    */
462	PyTypeObject* object_type;	/* PyObjCObject_Type   */
463	PyTypeObject* select_type;	/* PyObjCSelector_Type */
464
465	/* PyObjC_RegisterMethodMapping */
466	RegisterMethodMappingFunctionType *register_method_mapping;
467
468	/* PyObjC_RegisterSignatureMapping */
469	int (*register_signature_mapping)(
470			char*,
471			PyObject *(*)(PyObject*, PyObject*, PyObject*),
472			void (*)(void*, void*, void**, void*));
473
474	/* PyObjCObject_GetObject */
475	id (*obj_get_object)(PyObject*);
476
477	/* PyObjCObject_ClearObject */
478	void (*obj_clear_object)(PyObject*);
479
480	/* PyObjCClass_GetClass */
481	Class (*cls_get_class)(PyObject*);
482
483	/* PyObjCClass_New */
484	PyObject* (*cls_to_python)(Class cls);
485
486	/* PyObjC_PythonToId */
487	id (*python_to_id)(PyObject*);
488
489	/* PyObjC_IdToPython */
490	PyObject* (*id_to_python)(id);
491
492	/* PyObjCErr_FromObjC */
493	void (*err_objc_to_python)(NSException*);
494
495	/* PyObjCErr_ToObjC */
496	void (*err_python_to_objc)(void);
497
498	/* PyObjC_PythonToObjC */
499	int (*py_to_objc)(const char*, PyObject*, void*);
500
501	/* PyObjC_ObjCToPython */
502	PyObject* (*objc_to_py)(const char*, void*);
503
504	/* PyObjC_SizeOfType */
505	Py_ssize_t   (*sizeof_type)(const char*);
506
507	/* PyObjCSelector_GetClass */
508	Class	   (*sel_get_class)(PyObject* sel);
509
510	/* PyObjCSelector_GetSelector */
511	SEL	   (*sel_get_sel)(PyObject* sel);
512
513	/* PyObjC_InitSuper */
514	void	(*fill_super)(struct objc_super*, Class, id);
515
516	/* PyObjC_InitSuperCls */
517	void	(*fill_super_cls)(struct objc_super*, Class, Class);
518
519	/* PyObjCPointerWrapper_Register */
520	int  (*register_pointer_wrapper)(
521		        const char*, PyObject* (*pythonify)(void*),
522			int (*depythonify)(PyObject*, void*)
523		);
524
525	void (*unsupported_method_imp)(void*, void*, void**, void*);
526	PyObject* (*unsupported_method_caller)(PyObject*, PyObject*, PyObject*);
527
528	/* PyObjCErr_ToObjCWithGILState */
529	void (*err_python_to_objc_gil)(PyGILState_STATE* state);
530
531	/* PyObjCRT_AlignOfType */
532	Py_ssize_t (*alignof_type)(const char* typestr);
533
534	/* PyObjCRT_SELName */
535	const char* (*selname)(SEL sel);
536
537	/* PyObjCRT_SimplifySignature */
538	int (*simplify_sig)(char* signature, char* buf, size_t buflen);
539
540	/* PyObjC_FreeCArray */
541	void    (*free_c_array)(int,void*);
542
543	/* PyObjC_PythonToCArray */
544	int     (*py_to_c_array)(BOOL, BOOL, const char*, PyObject*, void**, Py_ssize_t*, PyObject**);
545
546	/* PyObjC_CArrayToPython */
547	PyObject* (*c_array_to_py)(const char*, void*, Py_ssize_t);
548
549	/* PyObjC_RegisterStructType */
550	PyObject* (*register_struct)(const char*, const char*, const char*, initproc, Py_ssize_t, const char**);
551
552	/* PyObjCIMP_Type */
553	PyTypeObject* imp_type;
554
555	/* PyObjCIMP_GetIMP */
556	IMP  (*imp_get_imp)(PyObject*);
557
558	/* PyObjCIMP_GetSelector */
559	SEL  (*imp_get_sel)(PyObject*);
560
561	/* PyObjCErr_AsExc */
562	NSException* (*err_python_to_nsexception)(void);
563
564	/* PyGILState_Ensure */
565	PyGILState_STATE (*gilstate_ensure)(void);
566
567	/* PyObjCObject_IsUninitialized */
568	int (*obj_is_uninitialized)(PyObject*);
569
570	/* PyObjCObject_Convert */
571	int (*pyobjcobject_convert)(PyObject*,void*);
572
573	/* PyObjCSelector_Convert */
574	int (*pyobjcselector_convert)(PyObject*,void*);
575
576	/* PyObjCClass_Convert */
577	int (*pyobjcclass_convert)(PyObject*,void*);
578
579	/* PyObjC_ConvertBOOL */
580	int (*pyobjc_convertbool)(PyObject*,void*);
581
582	/* PyObjC_ConvertChar */
583	int (*pyobjc_convertchar)(PyObject*,void*);
584
585	/* PyObjCObject_New */
586	PyObject* (*pyobjc_object_new)(id, int , int);
587
588	/* PyObjCCreateOpaquePointerType */
589	PyObject* (*pointer_type_new)(const char*, const char*, const char*);
590
591	/* PyObject* PyObjCObject_NewTransient(id objc_object, int* cookie); */
592	PyObject* (*newtransient)(id objc_object, int* cookie);
593
594	/* void PyObjCObject_ReleaseTransient(PyObject* proxy, int cookie); */
595	void (*releasetransient)(PyObject* proxy, int cookie);
596
597	void (*doweaklink)(PyObject*, struct PyObjC_WeakLink*);
598
599	const char* (*removefields)(char*, const char*);
600
601	PyObject** pyobjc_null;
602
603	int (*dep_c_array_count)(const char* type, Py_ssize_t count, BOOL strict, PyObject* value, void* datum);
604
605	PyObject* (*varlistnew)(const char* tp, void* array);
606};
607
608#ifndef PYOBJC_BUILD
609
610#ifndef PYOBJC_METHOD_STUB_IMPL
611static struct pyobjc_api*	PyObjC_API;
612#endif /* PYOBJC_METHOD_STUB_IMPL */
613
614#define PyObjCObject_Check(obj) PyObject_TypeCheck(obj, PyObjC_API->object_type)
615#define PyObjCClass_Check(obj)  PyObject_TypeCheck(obj, PyObjC_API->class_type)
616#define PyObjCSelector_Check(obj)  PyObject_TypeCheck(obj, PyObjC_API->select_type)
617#define PyObjCIMP_Check(obj)  PyObject_TypeCheck(obj, PyObjC_API->imp_type)
618#define PyObjCObject_GetObject (PyObjC_API->obj_get_object)
619#define PyObjCObject_ClearObject (PyObjC_API->obj_clear_object)
620#define PyObjCClass_GetClass   (PyObjC_API->cls_get_class)
621#define PyObjCClass_New 	     (PyObjC_API->cls_to_python)
622#define PyObjCSelector_GetClass (PyObjC_API->sel_get_class)
623#define PyObjCSelector_GetSelector (PyObjC_API->sel_get_sel)
624#define PyObjC_PythonToId      (PyObjC_API->python_to_id)
625#define PyObjC_IdToPython      (PyObjC_API->id_to_python)
626#define PyObjCErr_FromObjC     (PyObjC_API->err_objc_to_python)
627#define PyObjCErr_ToObjC       (PyObjC_API->err_python_to_objc)
628#define PyObjCErr_ToObjCWithGILState       (PyObjC_API->err_python_to_objc_gil)
629#define PyObjCErr_AsExc        (PyObjC_API->err_python_to_nsexception)
630#define PyObjC_PythonToObjC    (PyObjC_API->py_to_objc)
631#define PyObjC_ObjCToPython    (PyObjC_API->objc_to_py)
632#define PyObjC_RegisterMethodMapping (PyObjC_API->register_method_mapping)
633#define PyObjC_RegisterSignatureMapping (PyObjC_API->register_signature_mapping)
634#define PyObjC_SizeOfType      (PyObjC_API->sizeof_type)
635#define PyObjC_PythonToObjC   (PyObjC_API->py_to_objc)
636#define PyObjC_ObjCToPython   (PyObjC_API->objc_to_py)
637#define PyObjC_InitSuper	(PyObjC_API->fill_super)
638#define PyObjC_InitSuperCls	(PyObjC_API->fill_super_cls)
639#define PyObjCPointerWrapper_Register (PyObjC_API->register_pointer_wrapper)
640#define PyObjCUnsupportedMethod_IMP (PyObjC_API->unsupported_method_imp)
641#define PyObjCUnsupportedMethod_Caller (PyObjC_API->unsupported_method_caller)
642#define PyObjCRT_SizeOfType      (PyObjC_API->sizeof_type)
643#define PyObjCRT_AlignOfType	(PyObjC_API->alignof_type)
644#define PyObjCRT_SELName	(PyObjC_API->selname)
645#define PyObjCRT_SimplifySignature	(PyObjC_API->simplify_sig)
646#define PyObjC_FreeCArray	(PyObjC_API->free_c_array)
647#define PyObjC_PythonToCArray	(PyObjC_API->py_to_c_array)
648#define PyObjC_CArrayToPython	(PyObjC_API->c_array_to_py)
649#define PyObjC_RegisterStructType   (PyObjC_API->register_struct)
650#define PyObjCIMP_GetIMP   (PyObjC_API->imp_get_imp)
651#define PyObjCIMP_GetSelector   (PyObjC_API->imp_get_sel)
652#define PyObjCObject_IsUninitialized (PyObjC_API->obj_is_uninitialized)
653#define PyObjCObject_Convert (PyObjC_API->pyobjcobject_convert)
654#define PyObjCSelector_Convert (PyObjC_API->pyobjcselector_convert)
655#define PyObjCClass_Convert (PyObjC_API->pyobjcselector_convert)
656#define PyObjC_ConvertBOOL (PyObjC_API->pyobjc_convertbool)
657#define PyObjC_ConvertChar (PyObjC_API->pyobjc_convertchar)
658#define PyObjCObject_New (PyObjC_API->pyobjc_object_new)
659#define PyObjCCreateOpaquePointerType (PyObjC_API->pointer_type_new)
660#define PyObjCObject_NewTransient (PyObjC_API->newtransient)
661#define PyObjCObject_ReleaseTransient (PyObjC_API->releasetransient)
662#define PyObjC_PerformWeaklinking (PyObjC_API->doweaklink)
663#define PyObjCRT_RemoveFieldNames (PyObjC_API->removefields)
664#define PyObjC_NULL		  (*(PyObjC_API->pyobjc_null))
665#define PyObjC_DepythonifyCArray  (PyObjC_API->dep_c_array_count)
666#define PyObjC_VarList_New  (PyObjC_API->varlistnew)
667
668
669#ifndef PYOBJC_METHOD_STUB_IMPL
670
671static int
672PyObjC_ImportAPI(PyObject* calling_module)
673{
674	PyObject* m;
675	PyObject* d;
676	PyObject* api_obj;
677	PyObject* name = PyString_FromString("objc");
678
679	m = PyImport_Import(name);
680	Py_DECREF(name);
681	if (m == NULL) {
682		return -1;
683	}
684
685	d = PyModule_GetDict(m);
686	if (d == NULL) {
687		PyErr_SetString(PyExc_RuntimeError,
688			"No dict in objc module");
689		return -1;
690	}
691
692	api_obj = PyDict_GetItemString(d, PYOBJC_API_NAME);
693	if (api_obj == NULL) {
694		PyErr_SetString(PyExc_RuntimeError,
695			"No C_API in objc module");
696		return -1;
697	}
698	PyObjC_API = PyCObject_AsVoidPtr(api_obj);
699	if (PyObjC_API == NULL) {
700		return 0;
701	}
702	if (PyObjC_API->api_version != PYOBJC_API_VERSION) {
703		PyErr_SetString(PyExc_RuntimeError,
704			"Wrong version of PyObjC C API");
705		return -1;
706	}
707
708	if (PyObjC_API->struct_len < sizeof(struct pyobjc_api)) {
709		PyErr_SetString(PyExc_RuntimeError,
710			"Wrong struct-size of PyObjC C API");
711		return -1;
712	}
713
714	Py_INCREF(api_obj);
715
716	/* Current pyobjc implementation doesn't allow deregistering
717	 * information, avoid unloading of users of the C-API.
718	 * (Yes this is ugle, patches to fix this situation are apriciated)
719	 */
720	Py_INCREF(calling_module);
721
722	return 0;
723}
724#endif /* PYOBJC_METHOD_STUB_IMPL */
725
726#else /* PyObjC_BUILD */
727
728extern struct pyobjc_api	objc_api;
729
730#endif /* !PYOBJC_BUILD */
731
732#endif /*  PyObjC_API_H */
733"""
734