Re: [swift-users] DispatchQueue.async within infinite loop

2017-10-04 Thread Jeremy W. Sherman via swift-users
Something has to drain blocks sent to the main queue.

You can run a Foundation run loop. That should drain the main queue. I believe 
it also ensures blocks sent to the main queue always run on the main thread.

Dispatch includes its own lower-level function to pump the main queue: 
dispatch_main. This does not return. It does not ensure main queue blocks run 
on the main thread. The main queue does remain the only default, global, serial 
queue.

Both the Foundation and Dispatch APIs support creating custom event sources. A 
custom event source lets your integrate processing your own events with the 
framework’s main run loop. You might investigate those event source APIs as a 
way to integrate your SDL rendering code with whichever run loop you select. 
(If you expect to use Foundation, you probably want to run its RunLoop.)

Don’t forget to drain the autorelease pool associated with your main run loop 
regularly.

Cheers,
--
Jeremy W. Sherman
http://jeremywsherman.com/

> On Oct 4, 2017, at 21:07, Rahul Ranjan via swift-users 
>  wrote:
> 
> Hi Geordie,
> 
> I am new here and so pardon me if I misunderstood anything.
> 
> When you run a program in Swift, it already runs on main thread by default 
> and then you can all Dispatch async. So for example,
> 
> while true { // This while loop will run for infinite on main thread
> 
> Dispatch.main.async {} // your rendering goes here.
> 
> }
> 
> Regards,
> Rahul
>> On Thu, 5 Oct 2017 at 2:45 AM, Geordie J via swift-users 
>>  wrote:
>> Hi!
>> 
>> I have a somewhat unusual use-case that I’m trying to figure out.
>> 
>> I have a command-line swift app whose main thread ends up in an infinite 
>> loop for graphics rendering purposes (running SDL).
>> 
>> What I’m hoping to do is to be able to run async code like this from within 
>> that infinite loop:
>> 
>> DispatchQueue.someQueue.async {
>>  // do something
>>  DispatchQueue.main.async {
>>  // return result
>>  }
>> }
>> 
>> The issue is that the DispatchQueue.main.async block never runs, which is 
>> pretty logical given that it’s called inside the infinite loop - so where 
>> would it possibly get to run?
>> 
>> 
>> The question is, how do we achieve this? Is there a better way to have an 
>> infinite loop on the main thread (e.g. Foundation’s RunLoop class etc)? On 
>> iOS (where I have the most experience with Swift), the rendering loop’s 
>> implementation is obviously hidden.
>> 
>> Theoretically we could probably do the entire rendering loop like this:
>> 
>> func renderStuff() {
>> 
>>  // actually render stuff
>> 
>>  if !shouldQuit {
>>  DispatchQueue.main.async(renderStuff) // loops here
>>  }
>> }
>> 
>> // Start render loop:
>> DispatchQueue.main.async(renderStuff)
>> 
>> But I am pretty sure the DispatchQueue API is not intended to be used like 
>> that :)
>> 
>> Any ideas? Maybe an API that basically says “dequeue and perform work from 
>> the DispatchQueue”?
>> 
>> Cheers,
>> Geordie
>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
> 
> -- 
> Rahul
> 
> Sent from iPhone
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Detect if a generic type is numeric

2017-10-04 Thread Kevin Lundberg via swift-users
Scratch that, that won't work for the runtime type:

isNumeric(0 as Any) == false // :(


On 10/4/2017 9:30 PM, Kevin Lundberg via swift-users wrote:
>
> Can you do something like this?
>
> func isNumber(_ value: T) -> Bool { return true }
>
> func isNumber(_ value: T) -> Bool { return false }
>
> I don't recall whether or not swift will pick the right version of the
> function here, or whether this can even compile (mac isnt open at the
> moment), but if you can overload functions in this way then it might
> be much nicer than checking for lots of concrete types.
>
>
> On 10/1/2017 6:27 PM, V T via swift-users wrote:
>>
>>
>>> On 1. Oct 2017, at 22:43, davel...@mac.com 
>>> wrote:
>>>
>>>
>>>
 On Oct 1, 2017, at 2:32 PM, Glenn L. Austin > wrote:

>
> On Oct 1, 2017, at 8:56 AM, Dave Reed via swift-users
> > wrote:
>
>
>> On Sep 21, 2017, at 3:58 PM, V T via swift-users
>> > wrote:
>>
>> Hi there!
>>
>> Is there a best way to check if a given type conforms to numeric
>> protocol (Integer or FP) at runtime?
>>
>> func checkNumeric(_ value: T) {
>> /* return true if vaiue is Integer or FP */
>> /* this will not compile: */
>> if value is Numeric {
>>
>> }
>> }
>>
>> Best regards!
>>
>> VT
>>
>
> I think the way to do it is to try casting as the type, but you
> can't use "as? Numeric" as you get:
>
> error: protocol 'Numeric' can only be used as a generic constraint
> because it has Self or associated type requirements
>
> but you could check for each specific numeric type such as:
>
> func checkNumeric(_ value: T) {
>   if (value as? Int != nil) || (value as? Float != nil) {
>   print("numeric")
>   } else {
>   print("not numeric")
>   }
> }
>
> checkNumeric(3)
> checkNumeric(3.0)
> checkNumeric("3")

 You can also use the 'is' operator, as in 'value is Int || value is
 Float || value is Double'

 -- 
 Glenn L. Austin, Computer Wizard, AustinSoft.com
 
>>>
>>>
>>> Ah, I had forgotten "is" works in Swift
>>>
>>> Just be careful as:
>>>
>>> func checkNumeric(_ value: T) {
>>>    if (value is Int) || (value is Float) {
>>>    print("numeric")
>>>    } else {
>>>    print("not numeric")
>>>    }
>>> }
>>>
>>
>> Thanks all! My current implementation looks like this. A bit
>> redundant, bat it works. My intention was to simplify that monster:
>>
>> func isNumber(_ value: T) -> Bool {
>>     let valueMirror = Mirror(reflecting: value)
>>     #ifarch(arm) || arch(arm64)
>>         if (valueMirror.subjectType == Int.self ||
>> valueMirror.subjectType == UInt.self || valueMirror.subjectType ==
>> Double.self || valueMirror.subjectType == Int8.self ||
>> valueMirror.subjectType == Int16.self || valueMirror.subjectType ==
>> Int32.self || valueMirror.subjectType == Int64.self ||
>> valueMirror.subjectType == UInt8.self || valueMirror.subjectType ==
>> UInt16.self || valueMirror.subjectType == UInt32.self ||
>> valueMirror.subjectType == UInt64.self || valueMirror.subjectType ==
>> Float.self || valueMirror.subjectType == Float32.self ||
>> valueMirror.subjectType == NSNumber.self || valueMirror.subjectType
>> == NSDecimalNumber.self ) {
>>             return true
>>         }
>>         else {
>>             return false
>>         }
>>     #else
>>         if (valueMirror.subjectType == Int.self ||
>> valueMirror.subjectType == UInt.self || valueMirror.subjectType ==
>> Double.self || valueMirror.subjectType == Int8.self ||
>> valueMirror.subjectType == Int16.self || valueMirror.subjectType ==
>> Int32.self || valueMirror.subjectType == Int64.self ||
>> valueMirror.subjectType == UInt8.self || valueMirror.subjectType ==
>> UInt16.self || valueMirror.subjectType == UInt32.self ||
>> valueMirror.subjectType == UInt64.self || valueMirror.subjectType ==
>> Float.self || valueMirror.subjectType == Float32.self ||
>> valueMirror.subjectType == Float80.self || valueMirror.subjectType ==
>> NSNumber.self || valueMirror.subjectType == NSDecimalNumber.self ) {
>>             return true
>>         }
>>         else {
>>             return false
>>         }
>>     #endif
>> }
>>
>>> checkNumeric(3)
>>> checkNumeric(3.0)
>>> checkNumeric("3")
>>>
>>> outputs:
>>>
>>> numeric
>>> not numeric
>>> not numeric
>>>
>>> Since the literal 3.0 is a Double so you'd have to catch every
>>> floating point type (including CGFloat, I suspect etc.) vs. just
>>> trying to cast to a Float (although I guess casting to a Float could
>>> have unexpected results also if someone made an extension that
>>> allows a type to be cast as a Float).
>>>
>>> Dave
>>>
>>>
>>
>>
>>
>> 

Re: [swift-users] Detect if a generic type is numeric

2017-10-04 Thread Kevin Lundberg via swift-users
Can you do something like this?

func isNumber(_ value: T) -> Bool { return true }

func isNumber(_ value: T) -> Bool { return false }

I don't recall whether or not swift will pick the right version of the
function here, or whether this can even compile (mac isnt open at the
moment), but if you can overload functions in this way then it might be
much nicer than checking for lots of concrete types.


On 10/1/2017 6:27 PM, V T via swift-users wrote:
>
>
>> On 1. Oct 2017, at 22:43, davel...@mac.com 
>> wrote:
>>
>>
>>
>>> On Oct 1, 2017, at 2:32 PM, Glenn L. Austin >> > wrote:
>>>

 On Oct 1, 2017, at 8:56 AM, Dave Reed via swift-users
 > wrote:


> On Sep 21, 2017, at 3:58 PM, V T via swift-users
> > wrote:
>
> Hi there!
>
> Is there a best way to check if a given type conforms to numeric
> protocol (Integer or FP) at runtime?
>
> func checkNumeric(_ value: T) {
> /* return true if vaiue is Integer or FP */
> /* this will not compile: */
> if value is Numeric {
>
> }
> }
>
> Best regards!
>
> VT
>

 I think the way to do it is to try casting as the type, but you
 can't use "as? Numeric" as you get:

 error: protocol 'Numeric' can only be used as a generic constraint
 because it has Self or associated type requirements

 but you could check for each specific numeric type such as:

 func checkNumeric(_ value: T) {
   if (value as? Int != nil) || (value as? Float != nil) {
   print("numeric")
   } else {
   print("not numeric")
   }
 }

 checkNumeric(3)
 checkNumeric(3.0)
 checkNumeric("3")
>>>
>>> You can also use the 'is' operator, as in 'value is Int || value is
>>> Float || value is Double'
>>>
>>> -- 
>>> Glenn L. Austin, Computer Wizard, AustinSoft.com 
>>
>>
>> Ah, I had forgotten "is" works in Swift
>>
>> Just be careful as:
>>
>> func checkNumeric(_ value: T) {
>>    if (value is Int) || (value is Float) {
>>    print("numeric")
>>    } else {
>>    print("not numeric")
>>    }
>> }
>>
>
> Thanks all! My current implementation looks like this. A bit
> redundant, bat it works. My intention was to simplify that monster:
>
> func isNumber(_ value: T) -> Bool {
>     let valueMirror = Mirror(reflecting: value)
>     #ifarch(arm) || arch(arm64)
>         if (valueMirror.subjectType == Int.self ||
> valueMirror.subjectType == UInt.self || valueMirror.subjectType ==
> Double.self || valueMirror.subjectType == Int8.self ||
> valueMirror.subjectType == Int16.self || valueMirror.subjectType ==
> Int32.self || valueMirror.subjectType == Int64.self ||
> valueMirror.subjectType == UInt8.self || valueMirror.subjectType ==
> UInt16.self || valueMirror.subjectType == UInt32.self ||
> valueMirror.subjectType == UInt64.self || valueMirror.subjectType ==
> Float.self || valueMirror.subjectType == Float32.self ||
> valueMirror.subjectType == NSNumber.self || valueMirror.subjectType ==
> NSDecimalNumber.self ) {
>             return true
>         }
>         else {
>             return false
>         }
>     #else
>         if (valueMirror.subjectType == Int.self ||
> valueMirror.subjectType == UInt.self || valueMirror.subjectType ==
> Double.self || valueMirror.subjectType == Int8.self ||
> valueMirror.subjectType == Int16.self || valueMirror.subjectType ==
> Int32.self || valueMirror.subjectType == Int64.self ||
> valueMirror.subjectType == UInt8.self || valueMirror.subjectType ==
> UInt16.self || valueMirror.subjectType == UInt32.self ||
> valueMirror.subjectType == UInt64.self || valueMirror.subjectType ==
> Float.self || valueMirror.subjectType == Float32.self ||
> valueMirror.subjectType == Float80.self || valueMirror.subjectType ==
> NSNumber.self || valueMirror.subjectType == NSDecimalNumber.self ) {
>             return true
>         }
>         else {
>             return false
>         }
>     #endif
> }
>
>> checkNumeric(3)
>> checkNumeric(3.0)
>> checkNumeric("3")
>>
>> outputs:
>>
>> numeric
>> not numeric
>> not numeric
>>
>> Since the literal 3.0 is a Double so you'd have to catch every
>> floating point type (including CGFloat, I suspect etc.) vs. just
>> trying to cast to a Float (although I guess casting to a Float could
>> have unexpected results also if someone made an extension that allows
>> a type to be cast as a Float).
>>
>> Dave
>>
>>
>
>
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] DispatchQueue.async within infinite loop

2017-10-04 Thread Rahul Ranjan via swift-users
Hi Geordie,

I am new here and so pardon me if I misunderstood anything.

When you run a program in Swift, it already runs on main thread by default
and then you can all Dispatch async. So for example,

while true { // This while loop will run for infinite on main thread

Dispatch.main.async {} // your rendering goes here.

}

Regards,
Rahul
On Thu, 5 Oct 2017 at 2:45 AM, Geordie J via swift-users <
swift-users@swift.org> wrote:

> Hi!
>
> I have a somewhat unusual use-case that I’m trying to figure out.
>
> I have a command-line swift app whose main thread ends up in an infinite
> loop for graphics rendering purposes (running SDL).
>
> What I’m hoping to do is to be able to run async code like this from
> within that infinite loop:
>
> *DispatchQueue.someQueue.async {*
> * // do something*
> * DispatchQueue.main.async {*
> * // return result*
> * }*
> *}*
>
> The issue is that the *DispatchQueue.main.async* block never runs, which
> is pretty logical given that it’s called *inside *the infinite loop - so
> where would it possibly get to run?
>
>
> The question is, how do we achieve this? Is there a better way to have an
> infinite loop on the main thread (e.g. Foundation’s RunLoop class etc)? On
> iOS (where I have the most experience with Swift), the rendering loop’s
> implementation is obviously hidden.
>
> Theoretically we could probably do the entire rendering loop like this:
>
> *func renderStuff() {*
>
> *// actually render stuff*
>
> * if !shouldQuit {*
> * DispatchQueue.main.async(renderStuff) // loops here*
> * }*
> *}*
>
> *// Start render loop:*
> *DispatchQueue.main.async(renderStuff)*
>
> But I am pretty sure the DispatchQueue API is not intended to be used like
> that :)
>
> Any ideas? Maybe an API that basically says “dequeue and perform work from
> the DispatchQueue”?
>
> Cheers,
> Geordie
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
-- 
Rahul

Sent from iPhone
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Where CodingKey protocol is implemented on swift source code

2017-10-04 Thread Solli Honorio via swift-users
Studying "Codable.swift" and "JSONEncoder.swift" to understand how decoding
works under the hood, I got confused about how CodingKey is implemented for
'enum'. Shouldn't have an extension of RawRepresentable to implement the
CodingKey protocol?

This is the answer I'm looking for, how the CodingKey protocol is
implemented on enum?

I appreciate any help, tks

Solli Honorio

-- 
"o animal satisfeito dorme". - Guimarães Rosa
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Communicating with dynamically loaded swift library

2017-10-04 Thread Joe Groff via swift-users


> On Oct 4, 2017, at 11:02 AM, Ján Kosa via swift-users  
> wrote:
> 
> Hello folks,
> 
> I have been toying with dynamic libraries, trying to implement plugin 
> functionality. I was able to get to the point where I can call simple 
> function in loaded library, but I am having troubles starting more 
> sophisticated communication channel.
> 
> There are 3 projects
> - PluginConsumer is an app that loads plugin libraries 
> - MyPlugin is a plugin implementation, output is dynamic library that 
> PluginConsumer loads
> - PluginInterface is common interface that both MyPlugin and PluginConsumer 
> use, so that they know how to communicate
> 
> My first idea was to have PluginInterface be a simple SPM project with single 
> file where the bare-bones PluginInterface class would be:
> 
> 
> open class PluginInterface {
> 
> open func sayHi()
> 
> }
> 
> 
> 
> Package.swift file:
> 
> 
> 
> // swift-tools-version:4.0
> 
> import PackageDescription
> 
> let package = Package(
> 
> name: "PluginInterface",
> 
> products: [ .library(name: "PluginInterface", type: .dynamic, targets: 
> ["PluginInterface"]) ],
> 
> targets: [ .target(name: "PluginInterface") ]
> 
> 
> )
> 
> 
> 
> 
> 
> UserPlugin is also very simple project containing only one file:
> 
> 
> 
> public func getPlugin() -> AnyObject {
> 
> return MyPlugin()
> 
> 
> }
> 
> 
> 
> class MyPlugin: PluginInterface {
> 
> override func sayHi() {
> 
> print("Hi from my plugin")
> 
> }
> 
> }
> 
> Package.swift:
> 
> 
> 
> // swift-tools-version:4.0
> 
> import PackageDescription
> 
> let package = Package(
> 
> name: "MyPlugin",
> 
> products: [ .library(name: "MyPlugin", type: .dynamic, targets: 
> ["MyPlugin"]) ],
> 
> dependencies: [ .package(url: "url_to_PluginInterface", from: "0.0.0"), ],
> 
> targets: [
> 
> .target(name: "PluginInterface", dependencies: ["PluginInterface"]),
> 
> .target(name: "MyPlugin", dependencies: ["PluginInterface"]),
> 
> ]
> 
> 
> )
> 
> 
> 
> The PluginConsumer is bit more complicated, but here is relevant part (lib 
> loading and function calling):
> 
> 
> 
> typealias InitFunction = @convention(c) () -> AnyObject
> 
> 
> 
> let openRes = dlopen(pathToLib, RTLD_NOW|RTLD_LOCAL)
> 
> if openRes != nil {
> 
> defer {
> 
> dlclose(openRes)
> 
> }
> 
> let symbolName = "mangled_symbol_name"
> 
> let sym = dlsym(openRes, symbolName)
> 
> 
> 
> if sym != nil {
> 
> let f: InitFunction = unsafeBitCast(sym, to: InitFunction.self)
> 
> let plugin = f() as? PluginInterface
> 
> }
> 
> 
> }
> 
> Package.swift file:
> 
> // swift-tools-version:4.0
> 
> import PackageDescription
> 
> let package = Package(
> 
> name: "PluginConsumer",
> 
> dependencies: [ .package(url: "path_to_plugin_interface", from: "0.0.0") 
> ],
> 
> targets: [ .target(name: "PluginConsumer", dependencies: 
> ["PluginConsumer"]) ]
> 
> 
> )
> 
> 
> 
> This all compiles nicely, MyPlugin project creates dylib file that executable 
> created by PluginConsumer can load, but the problem is with following line:
> 
> let plugin = f() as? PluginInterface
> 
> Type of the plugin is MyPlugin, but from the consumer's view, it doesn't 
> inherit from PluginInterface so I can't call sayHi() method. I assume this is 
> because there is no relation between PluginInterface class that compiler uses 
> for MyPlugin project one that it uses for PluginConsumer project. After 
> library is loaded, they are two completely different classes that happen to 
> share same name. Is my assumption correct and how do I go about fixing it?

It sounds like that may be the case. Class names are namespaced to their 
module. If you're literally including the same PluginInterface.swift file in 
both of your modules, then you're going to end up with a 
ModuleA.PluginInterface and ModuleB.PluginInterface class. If you built 
PluginInterface as its own module, and imported the same module from your 
plugin and host projects, then you should end up with one common class.

-Joe

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Communicating with dynamically loaded swift library

2017-10-04 Thread Daniel Dunbar via swift-users
The way that I have done this in the past is pass a protocol as an unsafe 
pointer to an exposed entry point:
```swift
let entryPoint = dlsym(handle, “initializePlugin”)
guard entryPoint != nil else {
fatalError("missing plugin entry point: \(pluginPath)")
}
typealias PluginInitializationFunc = @convention(c) 
(UnsafeRawPointer) -> ()
let f = unsafeBitCast(entryPoint, to: PluginInitializationFunc.self)
f(Unmanaged.passUnretained(self).toOpaque())
```

and then in the plugin convert back to the appropriate type:

```
@_cdecl("initializePlugin")
public func initializePlugin(_ ptr: UnsafeRawPointer) {
let manager = Unmanaged.fromOpaque(ptr).takeUnretainedValue()
```

HTH,
 - Daniel

> On Oct 4, 2017, at 11:02 AM, Ján Kosa via swift-users  
> wrote:
> 
> Hello folks,
> 
> I have been toying with dynamic libraries, trying to implement plugin 
> functionality. I was able to get to the point where I can call simple 
> function in loaded library, but I am having troubles starting more 
> sophisticated communication channel.
> 
> There are 3 projects
> - PluginConsumer is an app that loads plugin libraries 
> - MyPlugin is a plugin implementation, output is dynamic library that 
> PluginConsumer loads
> - PluginInterface is common interface that both MyPlugin and PluginConsumer 
> use, so that they know how to communicate
> 
> My first idea was to have PluginInterface be a simple SPM project with single 
> file where the bare-bones PluginInterface class would be:
> 
> 
> open class PluginInterface {
> 
> open func sayHi()
> 
> }
> 
> 
> 
> Package.swift file:
> 
> 
> 
> // swift-tools-version:4.0
> 
> import PackageDescription
> 
> let package = Package(
> 
> name: "PluginInterface",
> 
> products: [ .library(name: "PluginInterface", type: .dynamic, targets: 
> ["PluginInterface"]) ],
> 
> targets: [ .target(name: "PluginInterface") ]
> 
> 
> )
> 
> 
> 
> 
> 
> UserPlugin is also very simple project containing only one file:
> 
> 
> 
> public func getPlugin() -> AnyObject {
> 
> return MyPlugin()
> 
> 
> }
> 
> 
> 
> class MyPlugin: PluginInterface {
> 
> override func sayHi() {
> 
> print("Hi from my plugin")
> 
> }
> 
> }
> 
> Package.swift:
> 
> 
> 
> // swift-tools-version:4.0
> 
> import PackageDescription
> 
> let package = Package(
> 
> name: "MyPlugin",
> 
> products: [ .library(name: "MyPlugin", type: .dynamic, targets: 
> ["MyPlugin"]) ],
> 
> dependencies: [ .package(url: "url_to_PluginInterface", from: "0.0.0"), ],
> 
> targets: [
> 
> .target(name: "PluginInterface", dependencies: ["PluginInterface"]),
> 
> .target(name: "MyPlugin", dependencies: ["PluginInterface"]),
> 
> ]
> 
> 
> )
> 
> 
> 
> The PluginConsumer is bit more complicated, but here is relevant part (lib 
> loading and function calling):
> 
> 
> 
> typealias InitFunction = @convention(c) () -> AnyObject
> 
> 
> 
> let openRes = dlopen(pathToLib, RTLD_NOW|RTLD_LOCAL)
> 
> if openRes != nil {
> 
> defer {
> 
> dlclose(openRes)
> 
> }
> 
> let symbolName = "mangled_symbol_name"
> 
> let sym = dlsym(openRes, symbolName)
> 
> 
> 
> if sym != nil {
> 
> let f: InitFunction = unsafeBitCast(sym, to: InitFunction.self)
> 
> let plugin = f() as? PluginInterface
> 
> }
> 
> 
> }
> 
> Package.swift file:
> 
> // swift-tools-version:4.0
> 
> import PackageDescription
> 
> let package = Package(
> 
> name: "PluginConsumer",
> 
> dependencies: [ .package(url: "path_to_plugin_interface", from: "0.0.0") 
> ],
> 
> targets: [ .target(name: "PluginConsumer", dependencies: 
> ["PluginConsumer"]) ]
> 
> 
> )
> 
> 
> 
> This all compiles nicely, MyPlugin project creates dylib file that executable 
> created by PluginConsumer can load, but the problem is with following line:
> 
> let plugin = f() as? PluginInterface
> 
> Type of the plugin is MyPlugin, but from the consumer's view, it doesn't 
> inherit from PluginInterface so I can't call sayHi() method. I assume this is 
> because there is no relation between PluginInterface class that compiler uses 
> for MyPlugin project one that it uses for PluginConsumer project. After 
> library is loaded, they are two completely different classes that happen to 
> share same name. Is my assumption correct and how do I go about fixing it?
> 
> I had an idea I could make PluginInterface emit dynamic library that would be 
> dynamically linked by both MyPlugin and PluginConsumer, thus making them 
> share same PluginInterface class, but I can't figure out how to do that (or 
> if it's right way of doing this).
> 
> 
> 
> Any help appreciated :)
> 
> Lope
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing 

[swift-users] Communicating with dynamically loaded swift library

2017-10-04 Thread Ján Kosa via swift-users
Hello folks,

I have been toying with dynamic libraries, trying to implement plugin
functionality. I was able to get to the point where I can call simple
function in loaded library, but I am having troubles starting more
sophisticated communication channel.

There are 3 projects
- PluginConsumer is an app that loads plugin libraries
- MyPlugin is a plugin implementation, output is dynamic library that
PluginConsumer loads
- PluginInterface is common interface that both MyPlugin and PluginConsumer
use, so that they know how to communicate

My first idea was to have PluginInterface be a simple SPM project with
single file where the bare-bones PluginInterface class would be:


open class PluginInterface {

open func sayHi()

}


Package.swift file:


// swift-tools-version:4.0

import PackageDescription

let package = Package(

name: "PluginInterface",

products: [ .library(name: "PluginInterface", type: .dynamic, targets: [
"PluginInterface"]) ],

targets: [ .target(name: "PluginInterface") ]

)



UserPlugin is also very simple project containing only one file:


public func getPlugin() -> AnyObject {

return MyPlugin()

}


class MyPlugin: PluginInterface {

override func sayHi() {

print("Hi from my plugin")

}

}

Package.swift:


// swift-tools-version:4.0

import PackageDescription

let package = Package(

name: "MyPlugin",

products: [ .library(name: "MyPlugin", type: .dynamic, targets: [
"MyPlugin"]) ],

dependencies: [ .package(url: "url_to_PluginInterface", from: "0.0.0"),
],

targets: [

.target(name: "PluginInterface", dependencies: ["PluginInterface"]),

.target(name: "MyPlugin", dependencies: ["PluginInterface"]),

]

)


The PluginConsumer is bit more complicated, but here is relevant part (lib
loading and function calling):


typealias InitFunction = @convention(c) () -> AnyObject


let openRes = dlopen(pathToLib, RTLD_NOW|RTLD_LOCAL)

if openRes != nil {

defer {

dlclose(openRes)

}

let symbolName = "mangled_symbol_name"

let sym = dlsym(openRes, symbolName)


if sym != nil {

let f: InitFunction = unsafeBitCast(sym, to: InitFunction.self)

let plugin = f() as? PluginInterface

}

}

Package.swift file:

// swift-tools-version:4.0

import PackageDescription

let package = Package(

name: "PluginConsumer",

dependencies: [ .package(url: "path_to_plugin_interface", from: "0.0.0"
) ],

targets: [ .target(name: "PluginConsumer", dependencies: [
"PluginConsumer"]) ]

)


This all compiles nicely, MyPlugin project creates dylib file that
executable created by PluginConsumer can load, but the problem is with
following line:

let plugin = f() as? PluginInterface

Type of the plugin is MyPlugin, but from the consumer's view, it doesn't
inherit from PluginInterface so I can't call sayHi() method. I assume this
is because there is no relation between PluginInterface class that compiler
uses for MyPlugin project one that it uses for PluginConsumer project.
After library is loaded, they are two completely different classes that
happen to share same name. Is my assumption correct and how do I go about
fixing it?

I had an idea I could make PluginInterface emit dynamic library that would
be dynamically linked by both MyPlugin and PluginConsumer, thus making them
share same PluginInterface class, but I can't figure out how to do that (or
if it's right way of doing this).


Any help appreciated :)

Lope
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Type inference issue with map and filter chained

2017-10-04 Thread Mark Lacey via swift-users


> On Sep 24, 2017, at 1:52 AM, Trevör ANNE DENISE via swift-users 
>  wrote:
> 
> Hello everyone, I found this on StackOverflow : 
> https://stackoverflow.com/questions/46381752/swift-4-methods-chaining/ 
> 
> 
> Is this a bug of Swift 4 or is this normal ? I don't understand why the 
> problem only happens when methods are chained !

It’s a bug.

The reason you see this when they are chained is because the type checker (in 
general) often finds multiple potential solutions (meaning a set of types and 
particular function overloads) and then has to select the “best” solution from 
those. For example one solution might involve “map” from type A combined with 
“filter” from type B, and another might involve “map” from type X and “filter” 
from type Y.

For the sake of illustration, let’s say it found only those two solutions in 
your case. Selecting the best solution involves examining the components of the 
solutions and comparing each component to determine which is best. In your 
example we may decide A.map is the best map, but Y.filter is the best filter. 
There is no solution that involves A.map combined with Y.filter, so we consider 
the solution to be ambiguous.

The combination of the type checker and standard library design should ensure 
this never happens, but we have some known bugs we need to work through in 
order to fix all of these cases.

Mark

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Netlib

2017-10-04 Thread Edward Connell via swift-users
Hi Vladimir,
To answer your questions:

1) The framework is designed to allow the easy creation of models for
training and inference. The framework is intended to be used both for
training and deployment on all platforms.

2) Yes currently only the CudaComputeService is implemented. I am only one
guy, and I didn't have the resources to implement other service types such
as Metal.

3) The same Swift code should run on iOS, if a compute service is provided
such as Metal.

I started this project when only Caffe1 existed and was hoping Apple would
be interested in my work.
While I was working on the project, Microsoft, Google, Facebook, and Amazon
invested literally thousands of man years of effort into their own
frameworks. My code is still significantly faster, but without a major
investment there is no way one guy can compete anymore. There is also no
good financial reason for an investment now, because the competing products
are free.

Apple bought Turi and is now using CoreML for deployment and private
training tools from the Turi acquisition.
At this point from a business point of view, it doesn't make sense for me
to add any more to this code base. That is why I made it publicly available
and hope it will help others.

Who knows, perhaps maybe someone will offer me an interesting job :)

Today I would suggest that if you are trying to deploy on iOS, use Caffe2
for training and CoreML for deployment. CoreML has a converter from Caffe2
to CoreML to make it easy for you.

In a side mail you mentioned that you hate Python. I don't much like python
either, and I see a lot of benefits of a pure Swift solution, particularly
for the ability to directly connect to all of the Apple UI libraries to
create advanced visualization apps.
Unfortunately all of the major toolkits are using python, including the
internal Turi tools. You can use Caffe2's C++ API if you prefer, but it's
probably in your best interest to just live with the python way of doing
things for now.

The core of all the major frameworks are written in C++, so I think the
reason python was chosen is it is much easier than C++ for running
experiments and visualization. Unfortunately deployment was an after
thought for most of the frameworks. In the Caffe2 rewrite, they made more
of an effort.

On a side note, Microsoft's CNTK defined something called BrainScript for
defining models. It appears to be very clean, concise, and superior to
python. They did a nice job. However, I read in some forums that they are
thinking of phasing it out, because the community just wants to use python.
So a better technical solution is not always the best business decision.

Good luck, Ed

On Tue, Oct 3, 2017 at 11:38 AM, Vladimir.S  wrote:

> On 03.10.2017 19:02, Edward Connell via swift-users wrote:
>
>> Hi All,
>> Sorry something strange happened with the first post, so I am reposting
>> this.
>>
>> I've recently wrapped up an ML framework research project that I've been
>> working on for some time.
>> It addresses a lot of difficult design problems, and works around a lot
>> of compiler bugs and Linux library deficiencies.
>>
>> It's written almost entirely in Swift 4.0 with some C and Cuda kernels.
>> Development and testing were done primarily on Ubuntu 16.04, but it will
>> also build on MacOS.
>> Linux was the primary environment, because there aren't any modern Macs
>> that can host big NVIDIA hardware
>>
>> The framework interfaces with many common C libraries such as: *Cuda,
>> cuDNN, lmdb, png, jpeg, zlib*
>>
>> Anyone in the community that is trying to work with these libraries might
>> benefit from the Swift wrapper classes and examples of successful use.
>> There are other isolated technology pieces that might be of use also.
>>
>> Other people's projects and examples helped me along the way, so I am
>> hoping that my work will help some of you as well.
>>
>> The code and overview docs are published on GitHub
>>
>> docs: https://github.com/ewconnell/Netlib/wiki <
>> https://github.com/ewconnell/Netlib/wiki>
>> code: https://github.com/ewconnell/Netlib > Netlib>
>>
>>
> Ed, it looks awesome! :-) Thank you for doing this and for sharing this!
>
> I'm a beginner in ML world, so could you clarify some points please:
>
> 1. Do I understand correctly, that main purpose of your library is to
> train the model? So, then we can export structure(connections) and
> use them where we need? Or also the purpose is efficient 'calculation' of
> trained model on Mac/Linux, so this could be used in production apps?
>
> 2. Currently this library has only Cuda compute service implemented,
> right? Do you plan to implement the same for Metal soon?
>
> 3. What are your plans to support iOs and its Metal? So, the same
> library/code/way could be used to train/experiment and to 'use' in apps on
> all(macOS/Linux/iOS) platforms.
>
> Thank you.
> Vladimir.
>
> Happy coding, Ed :)
>>
>>
>> 

Re: [swift-users] Is URLSession actually working on Linux

2017-10-04 Thread Alex Blewitt via swift-users

> On 3 Oct 2017, at 19:15, Geordie Jay via swift-users  
> wrote:
> 
> 2017-10-03 20:10 GMT+02:00 Georgios Moschovitis via swift-users 
> >:
> I implemented a simple RSS feed aggregator. I used code like...
> 
> let data = try! Data(contentsOf: feedURL)
> 
> or
> 
> let session = URLSession(configuration: URLSessionConfiguration.default)
> let task = session.dataTask(with: url, completionHandler: completionHandler)
> task.resume()
> 
> ...to fetch the data.
> 
> While my application worked perfectly when running on macOS, when I tried to 
> run
> it on Ubuntu it started crashing randomly with errors like...
> 
> *** Error in `bin/….': double free or corruption (fasttop): 
> 0x7f388ff0 ***
> Aborted

There were some issues which were fixed on the swift-4 branch but which didn't 
make it in before the swift 4.0 release was cut. These fixes will be in the 
next point release of Swift.

Have you tried the code with the latest nightly build to verify whether that 
has fixed the issue you're seeing?

> Are there any issues with the implementation of Foundation for Linux?
> 
> tldr; Pretty sure, yes.

There has been a reasonable amount of work put in recently, particularly with 
Data and URLSession. 

You can have a look at the list of open issues for Foundation on Linux:

https://bugs.swift.org/issues/?jql=status%20in%20(Open%2C%20%22In%20Progress%22%2C%20Reopened)%20AND%20component%20%3D%20Foundation

Note that some of the issues may have been recently closed but not made it into 
a release.

One of my colleagues recently fixed an issue with concurrent data races, which 
has a similar effect to the one you're describing but may not be the same:

https://bugs.swift.org/browse/SR-5936 

Alex___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Wrapping ImageMagick in a Swift Package

2017-10-04 Thread Toni Suter via swift-users
Hi Ankit,

Thank you very much! It works now :-)

Best regards,
Toni

> Am 03.10.2017 um 21:50 schrieb Ankit Aggarwal :
> 
> Hi Toni,
> 
> You're not supposed to build the system module package (because there is 
> nothing to build). Tag and add this package as a dependency and then try to 
> import the `TestPkg` module that you defined in the modulemap. The error here 
> is bogus and is tracked by https://bugs.swift.org/browse/SR-5383 
> 
> 
> On Tue, Oct 3, 2017 at 12:32 AM, Toni Suter via swift-users 
> > wrote:
> Hi,
> 
> I am trying to create a Swift Package that wraps the ImageMagick C API. So I 
> installed ImageMagick using MacPorts and
> I was then able to build the sample program with the following commands:
> 
> export PKG_CONFIG_PATH=/opt/local/lib/pkgconfig
> cc main.c `pkg-config --cflags --libs MagickWand`
> 
> Then I created a package with the command "swift package init 
> --type=system-module" and I modified Package.swift to look
> like this:
> 
> // swift-tools-version:4.0
> 
> import PackageDescription
> 
> let package = Package(
>   name: "TestPkg",
>   pkgConfig: "MagickWand"
> )
> 
> and I modified module.modulemap to the following:
> 
> module TestPkg [system] {
>   header "/opt/local/include/ImageMagick-6/wand/MagickWand.h"
>   link "MagickWand-6.Q16"
>   link "MagickCore-6.Q16"
>   export *
> }
> 
> Now when I run "swift build", I get the following error message:
> 
> :0: error: unexpected 'commands' value (expected map)
> :0: error: unable to load build file
> error: terminated(1): 
> /Library/Developer/Toolchains/swift-4.0-DEVELOPMENT-SNAPSHOT-2017-08-27-a.xctoolchain/usr/bin/swift-build-tool
>  -f /Users/tonisuter/Desktop/TestPkg/.build/debug.yaml main
> 
> Does anybody know how I can fix this error?
> 
> Thanks and best regards
> Toni
> 
> ___
> swift-users mailing list
> swift-users@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-users 
> 
> 
> 

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users