linusu / swift-napi-bindings Goto Github PK
View Code? Open in Web Editor NEWLicense: MIT License
License: MIT License
Hey @LinusU! This package looks awesome, but beyond the simple examples it gets to be quite the exercise of seeing how you structured things. I'd love to use this package more but more advanced cases have me lost at present.
I've got a Swift class I'm defining that needs to event back to JS, through a EventEmitter.emit(...)
. EventEmitter
's prototype is added to the NAPI class through utils.inherit(...)
on the JS side before instantiation. I'm having a hard time seeing how this is possible without the object's receiver one would use with napi_call_function
?
Here's the TypeScript...
import * as utils from 'utils'
import { BindingClass } from ('.build/release/binding')
util.inherits(BindingClass, events.EventEmitter)
export { BindingClass }
You see, I need to access the emit
function added to the BindingClass
prototype.
class BindingClass: NSObject {
init(_ env: OpaquePointer) { ... }
func fireEvent(name: String) {
let emit = /* ... get JS emit function from self */
// Emit event
emit.call(env, name)
}
}
Any chance of more docs or examples with classes?
What license is this under?
Using this on older versions of Mac OS (High Sierra for example), causes this error:
dyld: Library not loaded: @rpath/libswiftCore.dylib
Anyway to indicate that the build should embed that?
I'm new to swift, c, c++, and napi. So forgive the noobyness. I need to pass an object containing a Data (https://developer.apple.com/documentation/foundation/data) object from swift to nodejs (passing image data).
End goal would be Data on nodejs side as a byte array/buffer.
import NAPI
import NAPIC
import Foundation
import Cocoa
open class ScreenWithScreenshot : NAPI.ValueConvertible {
public let screenshotData : Data
public let screenIndex : Int
public let screenRect : NSRect
public let scale : CGFloat
public required init(_ screenIndex : Int, _ screen : NSScreen, _ screenshotData : Data) {
self.screenIndex = screenIndex
self.screenshotData = screenshotData
self.screenRect = CoordinateHelper.GetQuartzCoordinates(screen)
self.scale = screen.backingScaleFactor
}
public required convenience init(_ env: napi_env, from: napi_value) throws {
fatalError("Not implemented")
}
public func napiValue(_ env: napi_env) throws -> napi_value {
var result: napi_value!
var status: napi_status!
status = napi_create_object(env, &result)
guard status == napi_ok else { throw NAPI.Error(status) }
var screenIndex: napi_value!
status = napi_create_int32(env, Int32(self.screenIndex), &screenIndex)
guard status == napi_ok else { throw NAPI.Error(status) }
status = napi_set_named_property(env, result, "screenIndex", screenIndex)
guard status == napi_ok else { throw NAPI.Error(status) }
status = napi_set_named_property(env, result, "screenRect", try self.screenRect.napiValue(env))
guard status == napi_ok else { throw NAPI.Error(status) }
var scale: napi_value!
status = napi_create_double(env, Double(self.scale), &scale)
guard status == napi_ok else { throw NAPI.Error(status) }
status = napi_set_named_property(env, result, "scale", scale)
guard status == napi_ok else { throw NAPI.Error(status) }
// //struggling here
// var data: napi_value!
// status = napi_set_named_property(env, result, "data", self.screenshotData.bytes
// guard status == napi_ok else { throw NAPI.Error(status) }
return result
}
}
Extensions:
import NAPI
import NAPIC
import Foundation
import Cocoa
extension NSRect: NAPI.ValueConvertible {
public init(_ env: napi_env, from: napi_value) throws {
fatalError("Not implemented")
}
public func napiValue(_ env: napi_env) throws -> napi_value {
var status: napi_status!
var result: napi_value!
status = napi_create_object(env, &result)
guard status == napi_ok else { throw NAPI.Error(status) }
var x: napi_value!
status = napi_create_double(env, Double(self.minX), &x)
guard status == napi_ok else { throw NAPI.Error(status) }
var y: napi_value!
status = napi_create_double(env, Double(self.minY), &y)
guard status == napi_ok else { throw NAPI.Error(status) }
var width: napi_value!
status = napi_create_double(env, Double(self.width), &width)
guard status == napi_ok else { throw NAPI.Error(status) }
var height: napi_value!
status = napi_create_double(env, Double(self.height), &height)
guard status == napi_ok else { throw NAPI.Error(status) }
status = napi_set_named_property(env, result, "x", x)
guard status == napi_ok else { throw NAPI.Error(status) }
status = napi_set_named_property(env, result, "y", y)
guard status == napi_ok else { throw NAPI.Error(status) }
status = napi_set_named_property(env, result, "width", width)
guard status == napi_ok else { throw NAPI.Error(status) }
status = napi_set_named_property(env, result, "height", height)
guard status == napi_ok else { throw NAPI.Error(status) }
return result
}
}
extension Data {
var bytes : [UInt8] {
return [UInt8](self)
}
}
Hey @LinusU,
I want to use this library to expose Swift written code to electron, when it came with sync callback, it works perfectly, but when it came with async callback, there is one use case I haven’t figure out, that is how to write async code in Swift side and call the js code back.
Example code shows below(I know there is no Runloop in the native side, so I use NAPI.RunLoop
.),
func callbackWithAsync(env: OpaquePointer, callback: Function) throws -> Void {
try NAPI.RunLoop.ref(env)
var context: napi_async_context!
try napi_async_init(env, callback.napiValue(env), nil, &context)
URLSession.shared.dataTask(with: URL(string: "https://jsonplaceholder.typicode.com/posts")!) { (data, response, error) in
let res = String(data: data!, encoding: .utf8)!
DispatchQueue.main.async {
try! callback.call(env, res)
NAPI.RunLoop.unref()
}
}.resume()
}
On the js side,
addon = require('addon.node')
describe("callback", () => {
it("async", done => {
mbox.callbackWithAsync(str => {
console.log(str);
done()
});
})
);
When I try to call the function above, it raised an error,
Fatal error: 'try!' expression unexpectedly raised an error: NAPI.Error.invalidArg: file file.swift, line xx
[1] 33377 illegal hardware instruction mocha index.js
I guess there is something wrong with the env
because the thread and the call stack changes. But I don't know how to handle it.
I know there are some methods like napi_create_async_work
, napi_queue_async_work
in N-API for the native addon to expose async code to node.js. But in this case, I'm a little bit confused with the relationship between node's eventloop and native addon's thread thing, and wonder if it is possible to make the example code above work?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.