-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathGenericModule.swift
More file actions
55 lines (44 loc) · 1.99 KB
/
Copy pathGenericModule.swift
File metadata and controls
55 lines (44 loc) · 1.99 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
import PythonWrapper
fileprivate let modname = "swift_module".cString(using:.utf8)
fileprivate var myextension_methods : [PyMethodDef] = [
PyMethodDef(ml_name: nil, ml_meth: nil, ml_flags: 0, ml_doc: nil)
]
fileprivate var moduleDef : PyModuleDef!
fileprivate var slots = [
PyModuleDef_Slot.init(slot: Py_mod_exec, value: mm),
PyModuleDef_Slot.init(slot: 0, value: nil)
]
fileprivate let mm = unsafeBitCast(callbackWrapper, to: Optional<UnsafeMutableRawPointer>.self)
fileprivate let callbackWrapper : @convention(c) (PyObjectRef, UnsafeMutablePointer<PyModuleDef>?) -> PyObjectRef? = swift_module_install
fileprivate func initModuleFn() -> PyObjectRef? {
withUnsafeMutablePointer(to: &myextension_methods[0]) { mxm in
withUnsafeMutablePointer(to: &slots[0]) { sls in
withUnsafeBytes(of: modname!) { modnamex in
moduleDef = PyModuleDef.init(m_base: PyModuleDef_Base(), m_name: modnamex.baseAddress?.bindMemory(to: CChar.self, capacity: modname!.count+1),
m_doc: nil, m_size: 0,
m_methods: mxm, // &myextension_methods,
m_slots: sls, // &slots,
m_traverse: nil,
m_clear: nil,
m_free: nil)
}
}
}
return PyModuleDef_Init(&moduleDef)
}
fileprivate func swift_module_install(spec : PyObjectRef, def: UnsafeMutablePointer<PyModuleDef>!) -> PyObjectRef? {
return nil
}
open class SwiftModule {
public init() {
let _ = PyImport_AppendInittab(modname, initModuleFn );
}
public func addMethod( _ nm : String, _ mf : @escaping PyCFunction ) {
let j = nm.cString(using:.utf8)!
let p = UnsafeMutablePointer<CChar>.allocate(capacity: j.count)
for i in 0..<j.count { p[i] = j[i] }
let ii = PyMethodDef(ml_name: p, ml_meth: mf, ml_flags: METH_VARARGS, ml_doc: nil)
// try! throwErrorIfPresent()
myextension_methods.insert(ii, at: 0)
}
}