Proper use of swift_allocObject()? #36
Answered
by
Azoy
NSExceptional
asked this question in
Q&A
-
Given the following extension: extension ClassMetadata {
func createInstance<T: AnyObject>(props: [String: Any] = [:]) -> T {
var obj = swift_allocObject(
for: self,
size: self.classSize,
alignment: self.instanceAlignmentMask
)
for (key, value) in props {
self.set(value: value, forKey: key, on: &obj)
}
return unsafeBitCast(obj, to: T.self)
}
} And class definition: class JustDeallocateMe {
var expectation: XCTestExpectation
init(_ expectation: XCTestExpectation) {
self.expectation = expectation
}
deinit {
self.expectation.fulfill()
}
} I would expect the following test to pass, but it does not: func testAllocObject() {
let expect = XCTestExpectation(description: "deinit")
let cls = reflectClass(JustDeallocateMe.self)!
DispatchQueue.global().async {
var obj: JustDeallocateMe? = cls.createInstance(props: ["expectation": expect])
obj = nil
}
self.wait(for: [expect], timeout: 2)
} The |
Beta Was this translation helpful? Give feedback.
Answered by
Azoy
Apr 21, 2021
Replies: 1 comment 9 replies
-
So the correct way to call let object = swift_allocObject(
for: someMetadata,
size: someMetadata.instanceSize,
alignment: someMetadata.instanceAlignmentMask
) Where it will return a pointer to a heap object and the fields can be placed in the respective field offset from that pointer. |
Beta Was this translation helpful? Give feedback.
9 replies
Answer selected by
NSExceptional
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So the correct way to call
swift_allocObject
is:Where it will return a pointer to a heap object and the fields can be placed in the respective field offset from that pointer.