The LLVM infrastructure now supports compiling from LLVM IR to WebAssembly (at least experimentally). Swift uses the LLVM compiler infrastructure and can easily be compiled to LLVM IR. So I thought it would be straightforward to compile some Swift code to LLVM IR and then to WebAssembly.
It turned out not to be that easy, however. It looks like LLVM IR is not entirely platform independent? Whatever the reason behind the scenes, when compiling Swift to LLVM IR, a target architecture must be specified and WebAssembly is not available.
I have two questions then:
1) Am I correct that there is currently (as of October 2017) no way to compile Swift to WebAssembly?
2) What would it take to make WebAssembly a supported target for Swift to LLVM IR compilation?
1) To the best of my knowledge as of early Nov, 2017 you are correct: there is no commonly available way to compile Swift to WebAssembly. Maybe some enterprising hacker somewhere has made it happen but if so she hasn't shared her code with us yet.
2) In order to enable Wasm support you will probably need to hack on a few different parts. I think you could do it without knowing much of anything about the internals of the compiler (e.g. the parser & optimizers), but you'd need to learn about how the toolchain works and how it integrates with the platform at runtime.
You can learn a ton about what you'd need to do by studying how Swift was ported to Android. Luckily, Brian Gesiak posted a really detailed blog post about exactly how that port worked (warning: small Patreon donation required):
https://modocache.io/how-to-port-the-swift-runtime-to-android
Seriously, you would be nuts to embark on this project without reading that article.
Though I'm NOT an expert, based on that port and my (basic) understanding of Swift, I think the rough overview of where you'd need to hack would be:
The Swift compiler
You'll need to teach it about the Wasm "triple" used by LLVM, so it knows how to integrate with the rest of its toolchain
You'll need to set up a WebAssembly platform so that people can write #if os(WebAssembly) in places that require conditional compilation
You'll also need to set up similar build-time macros. The Android article explains this sort of thing really well.
The Swift runtime
This is written in C++ and it needs to run on Wasm
Since Wasm is an unusual platform there will probably be some work here. You might need to provide compatibility shims for various system calls and the like.
Projects like Emscripten have demonstrated lots of success compiling C++ to Wasm.
The Swift standard library
In theory you can write & run Swift code that doesn't use the standard library, but who would want to?
Also in theory this should "just work" if the runtime works, but you will likely need to use your #if os(WebAssembly) feature here to work around platform irregularities
Bonus: The Foundation and Dispatch libraries
If you want to use existing Swift code these two libraries will be essential.
Links:
Brian Gesiak's awesome blog post: https://modocache.io/how-to-port-the-swift-runtime-to-android
Link to the Android port's pull request: https://github.com/apple/swift/pull/1442
Interesting article about the challenges and rewards of cross-platform Swift: https://medium.com/#ephemer/how-we-put-an-app-in-the-android-play-store-using-swift-67bd99573e3c
It looks like there is a commercial offering that supports compilation of Swift to WebAssembly. RemObjects, the developer tooling company, has just announced support for WebAssembly with their Elements compiler, which can compile Java, Swift, C# and Oxygene.
As of May 2019 there's an open-source project available called SwiftWasm that allows you to compile Swift code to WebAssembly targeting WASI SDK. This means that binaries produced by SwiftWasm can be executed either in browsers with WASI polyfill or standalone WebAssembly runtimes supporting WASI such as wasmtime, lucet or wasmer.
I was looking for a way to convert Swift code to web assembly, and I found this.
https://swiftwasm.org/
I do not know how mature this platform is (October 2022) and if it can flourish, but having the capability is exciting.
Also, it provides means for writing JavaScript in Swift directly.
WebAssembly target would be like a generic unix target for llvm, so I think someone needs develop that port.
Please note that Swift -> Wasm in browser would be pretty much useless because Wasm has no DOM or DOM API access so you still need JavaScript to do anything meaningful, thus the question: why would anyone bother to make the port? It looks like JavaScript remains the only web language. If you don't like JavaScript you better forget the web development.
Chances are that Swift will run on Android before it runs on the web so stick with Swift/iOS and then make the port to Android whenever that becomes possible. People don't use the web/browser that much anyway.
Related
Simple question really, however there doesn't seem to be a straight answer in the current developer documentation.
Does Swift compile to machine language (i.e. assembly), or does it compile to some intermediary form that then runs on a virtual machine?
(I suspect it does, but being unfamiliar with development in Apple's world it is not clear to me like it may be to someone who is.)
Yes, it compiles to machine language by way of LLVM Bitcode and, as #connor said, runs on top of the Objective-C runtime.
Swift not only compiles to native machine code but it has also been designed specifically for it. Unlike e.g. Java which has been designed specifically as a JITed language. By that I mean Swift achieves best performance with ahead of time compilation while Java benefits most from JITing.
There are many reasons for these design choices but among them is that Swift has a much bigger scope than managed languages like Java. It is supposed to work on both desktop computers and phones with more restricted hardware. You can use Swift as a systems programming language unlike say C#, Java or Python because it has little runtime requirements and allow fairly detailed control of memory. So in theory one should be able to build an OS kernel with Swift which would be difficult with say Java.
Swift, just like objective-c compiles to native code using llvm
A good explanation can be found in Apple's top secret Swift language grew from work to sustain Objective C, which it now aims to replace
From that article, talking about Swift
The compiler is optimized for performance, and the language is
optimized for development, without compromising on either.
Swift, like Objective-C, is compiled to machine code that runs on the Objective-C runtime.
I am curious to know if there is any kind of programming library/framework for the C language for cross-platform programming of course. I mean there are already frameworks like Wxwidgets, Boost, Qt, U++ and etc for C++ available but I have not yet found any for C .
Updated Info:
We are trying to build an underlying Framework/library to be used in our project. We are going to eliminate the dotnet and instead provide a counterpart for those libraries which is fast and less demanding.
We will be working on a server/client based project, and thus the underlying services must be fast and also portable. GUI is not our priority now, but libraries providing threading capabilities is of importance to us.
And for the ANSI part, I think we are fine with that at the moment unless something changes that in the future.
if you write plain ANSI C, it should work on every POSIX system.
The most successful example of cross platform C library is standard C library itself (IMHO).
If you're looking for GUI toolkit GTK is the answer,
if you're looking for terminal UI, ncurses is pretty portable.
If you're looking for general use libraries, as long as they're written in ANSI C, should work almost everywhere, as long as it doesn't use system level APIs.
Can you just tell us, what kind of library/framework you are looking for ?
GTK+ is long established and actively maintained cross-platform C-only (or primarily) toolkit. You'll find not only on-line documentation but also books written about it. It is the framework backing up the GNOME project.
GTK+ is meant to build applications with UI, first of all. However, even if you don't need UI you'll find that some GTK+ components, namely GLib, provide general multiplatform support comparable with Qt. Actually, I needed a framework without UI at first and chose GLib over APR because I was able to find documentation and tutorials easier.
GTK+ was initially developed on UN*X an X-Windows which remains the platform where you can get it running the most easily. I wouldn't say that it is more difficult on Windows; it is just that you have more compiling environment options. I started with prepared GTK+ packages and MinGW but ended up integrating GTK+ with MSVC.
GTK+ exists for a long time and some people may find it old-school. On the other hand, it shows that it has proven to be stable and useful. There are also bindings for C++ and C#.
As with every big framework, the more you need from it the longer you will have to learn. But the other way round it works too; the more you learn the more you'll be able to do with it. Consistent coding style helps getting used to it.
--- Ferda
I have integrated Lua with my ObjC code (iphone game). The setup was pretty easy, but now, I have a little problem with the bridging. I have googled for results, etc... and it seems there isn't anything that could work without modifications. I mean, I have checked luaobjc bridge (it seems pretty old and dicontinued), I heard about LuaCocoa but it seems not to work on iphone, and wax is too thick.
My needs are pretty spare, I just need to be able to call objc methods from lua and don't mind having to do extra work to make it work (I don't need a totally authomatic bridging system).
So, I have decided to build a little bridge myself based on this page http://anti-alias.me/?p=36. It has key information about how to accomplish what I need, but the tutorial is not completed and I have some doubts about how to deal with method overloading when called from lua, etc...
Do anybody know if there exist any working bridge between objc and lua on the iphone or if it could be so hard to complete the bridge the above site offers?
Any information will be welcomed.
Don't reinvent the wheel!
First, you are correct that luaobjc and some other variants are outdated. A good overview can be found on the LuaCocoa page. LuaCocoa is fine but apparently doesn't support iPhone development, so the only other choice is Wax. Both LuaCocoa and Wax are runtime bridges, which means that you can (in theory) access every Objective-C class and method in Lua at the expense of runtime performance.
For games and from my experience the runtime performance overhead is so significant that it doesn't warrant the use of any runtime binding library. From a perspective of why one would use a scripting language, both libraries defy the purpose of favoring a scripting language over a lower-level language: they don't provide a DSL solution - which means you're still going to write what is essentially Objective-C code but with a slightly different syntax, no runtime debugging support, and no code editing support in Xcode. In other words: runtime Lua binding is a questionable solution at best, and has lots of cons going against it. Runtime Lua bindings are particularly unsuited for fast-paced action games aiming at a constantly high framerate.
What you want is a static binding. Static bindings at a minimum require you to declare what kind of methods will be available in Lua code. Some binding libraries scan your header files, others require you to provide a special declaration file similar to a header file. Most binding libraries can use both approaches. The benefit is optimal runtime performance, and being able to actually design what classes, methods and variables Lua scripts have access to.
There are but 3 candidates to bind Lua code to an iPhone app. To be fair, there are a lot more but most have one or more crucial flaws or are simply not stable or for special purposes only, or simply don't work for iPhone apps. The candidates are:
tolua and tolua++
luabind
SWIG
Big disadvantage shared by all Lua static binding libraries: none of them can bind directly to Objective-C code. All require to have an additional C or C++ layer available that ultimately interfaces with your Objective-C code. This has to do with how Objective-C works as a language and how small a role it has played (so far) when it comes to embedding Lua in Objective-C apps.
I recently evaluated all three binding libraries and came to enjoy SWIG. It is very well documented but has a bit of a learning curve. But I believe that learning curve is warranted because SWIG can be used to combine nearly any programming and scripting language, it can be advantageous to know how to use SWIG for future projects. Plus, once you understand their definition file implementation it turns out to be very easy (especially when compared to luabind) and considerably more flexible than tolua.
OK, bit late to the party but in case others come late also to this post here's another approach to add to the choices available: hand-code your LUA APIs.
I did a lecture on this topic where I live coded some basic LUA bindings in an hour. Its not hard. From the lecture I made a set of video tutorials that shows how to get started.
The approach of using a bindings generation tool like SWIG is a good one if you already have exactly the APIs that you need to call written in Objective-C and it makes sense to bring all those same API's over into LUA.
The pros of the hand-coding approach:
your project just compiles with one standard Xcode target
your project is all C & Obj-C
the LUA is just data shipped along with your images
no fiddling with "do I check in generated code" to Git
you create LUA functions for just the things you want
you can easily have hosted scripts that live inside an object
the API is under your control and is well known
dont expose engine APIs to level building team/tools
The last point is just that if you have detail functions that only make sense at the engine level and you don't want to see those when coding the game play you'll need to tell SWIG not to bind those.
Steffens answer is perfect and this approach is just another option, that may suit some folks better depending on the project.
I am in possession of a dictionary application (takes in text as input, outputs definitions + grammar analysis). I have all the source files (about 50 pages of code), written in Ada, as well as Windows and Unix executables. I want to be able to use this dictionary in an iOS app.
I'm not at all familiar with Ada, so my question is, in a nutshell—are there any shortcuts to somehow wrap the application and use it on iOS? Or is the only way just re-writing the entire application in C/Objective-C?
Shark8 mentioned JVM-targeted Ada. ACT sells a version of Gnat that targets the JVM. However, I do not believe iOS devices currently run Java. Apple does not want to lose control of the platform, so they do not allow any development environments other than their own, which is Objective C based. I understand the Java folks are working to fix this, but even if they do Apple will probably refuse to allow any such app into their online store. Note that this is not a problem unique to Ada. Any app written in any language other than C or Objective C has the same problem with iOS. (This is one of the many reasons why developers tend to prefer to target Android platforms than iOS).
So what you really need is something that can get your code compilable with Apple's Objective C compiler. Supposedly Objective C is a strict superset of C. If this is true for Apple's implementation, then an Ada compiler that outputs compilable C sources should do the job for you.
Fortunately, there is such an Ada compiler (or at least there used to be). AdaMagic at one point had C available as a "target". It is now sold by SofCheck. When last I saw a discussion of it years and years ago, they referred to it as a "service" as much as a compiler, so it may not be cheap. But if you have a real business need, it would certainly be cheaper than spending man-years rewriting a working app.
Your other option of course would be to say "Screw Apple and their facist OS", and shoot for Android instead. Sadly, for business reasons, that may not be feasible. :-(
Update (2016/2012): The assets of SofCheck have become available from AdaCore, as the two companies have merged in early 2012.
I want to be able to use this dictionary in an iOS app.
Well, if there is an Ada compiler that targets iOS -- and there probably is considering that GCC has an Ada front-end -- then re-using the packages should be straight-forward so long as the source isn't compiler- (for a different compiler) or architecture-specific.
The most experience I have with porting Ada to other architectures was to port some code I had compiling to the native machine to the JVM (there's an Ada compiler which targets the JVM); the "gotchas" were more along the line of the JVM's case-sensitivity interacting with Ada's case insensitivity for naming classes and packages.
I'm moving away from strict Android development and wanting to create iPhone applications. My understanding is that I can code the backend of iOS applications in C/C++ and also that I can use the NDK to include C/C++ code in Android apps. My question however is how? I've googled quite a bit and I can't find any clear and concise answers.
When looking at sample code for the NDK, it seems that all the function names etc. are Android (or at least Java) specific and so I would not be able to use this C/C++ backend to develop an iPhone frontend?
I'd appreciate some clarification on this issue and if at all available some code to help me out? (even just a simple Hello World that reads a string from a C/C++ file and displays it in an iOS and Android app).
Thanks guys
Chris
Note that I almost exclusively work on "business/utility/productivity" applications; things that rely heavily on fairly standard UI elements and expect to integrate well with their platform. This answer reflects that. See Mitch Lindgren's comment to Shaggy Frog's answer for good comments for game developers, who have a completely different situation.
I believe #Shaggy Frog is incorrect here. If you have effective, tested code in C++, there is no reason not to share it between Android and iPhone, and I've worked on projects that do just that and it can be very successful. There are dangers that should be avoided, however.
Most critically, be careful of "lowest common denominator." Self-contained, algorithmic code, shares very well. Complex frameworks that manage threads, talk on the network, or otherwise interact with the OS are more challenging to do in a way that doesn't force you to break the paradigms of the platform and shoot for the LCD that works equally badly on all platforms. In particular, I recommend writing your networking code using the platform's frameworks. This often requires a "sandwich" approach where the top layer is platform-specific and the very bottom layer is platform-specific, and the middle is portable. This is a very good thing if designed carefully.
Thread management and timers should also be done using the platform's frameworks. In particular, Java uses threads heavily, while iOS typically relies on its runloop to avoid threads. When iOS does use threads, GCD is strongly preferred. Again, the solution here is to isolate the truly portable algorithms, and let platform-specific code manage how it gets called.
If you have a complex, existing framework that is heavily threaded and has a lot of network or UI code spread throughout it, then sharing it may be difficult, but my recommendation still would be to look for ways to refactor it rather than rewrite it.
As an iOS and Mac developer who works extensively with cross-platform code shared on Linux, Windows and Android, I can say that Android is by far the most annoying of the platforms to share with (Windows used to hold this distinction, but Android blew it away). Android has had the most cases where it is not wise to share code. But there are still many opportunities for code reuse and they should be pursued.
While the sentiment is sound (you are following the policy of Don't Repeat Yourself), it's only pragmatic if what you can share that code in an efficient manner. In this case, it's not really possible to have a "write once" approach to cross-platform development where the code for two platforms needs to be written in different languages (C/C++/Obj-C on iPhone, Java for Android).
You'll be better off writing two different codebases in this case (in two different languages). Word of advice: don't write your Java code like it's C++, or your C++ code like it's Java. I worked at a company a number of years ago who had a product they "ported" from Java to C++, and they didn't write the C++ code like it was C++, and it caused all sorts of problems, not to mention being hard to read.
Writing a shared code base is really practical in this situation. There is some overhead to setting up and keeping it organized, but the major benefits are these 1) reduce the amount of code by sharing common functionality 2) Sharing bug fixes to the common code base. I'm currently aware of two routes that I'm considering for a project - use the native c/c++ (gains in speed at the expense of losing garbage collection and setting targets per processor) or use monodroid/monotouch which provide c# bindings for each os's platform functionality (I'm uncertain of how mature this is.)
If I was writing a game using 3d I'd definitely use approach #1.
I posted this same answer to a similar question but I think it's relevant so...
I use BatteryTech for my platform-abstraction stuff and my project structure looks like this:
On my PC:
gamename - contains just the common code
gamename-android - holds mostly BatteryTech's android-specific code and Android config, builders point to gamename project for common code
gamename-win32 - Just for building out to Windows, uses code from gamename project
On my Mac:
gamename - contains just the common code
gamename-ios - The iPhone/iPad build, imports common code
gamename-osx - The OSX native build. imports common code.
And I use SVN to share between my PC and Mac. My only real problems are when I add classes to the common codebase in Windows and then update on the mac to pull them down from SVN. XCode doesn't have a way to automatically add them to the project without scripts, so I have to pull them in manually each time, which is a pain but isn't the end of the world.
All of this stuff comes with BatteryTech so it's easy to figure out once you get it.
Besides using C/C++ share so lib.
If to develop cross-platform apps like game, suggest use mono-based framework like Unity3D.
Else if to develop business apps which require native UI and want to share business logic code cross mobile platforms, I suggest use Lua embedded engine as client business logic center.
The client UI is still native and get best UI performance. i.e Java on Android and ObjectC on iOS etc.
The logic is shared with same Lua scripts for all platform.
So the Lua layer is similar as client services (compare to server side services).
-- Anderson Mao, 2013-03-28
Though I don't use these myself as most of the stuff I write won't port well, I would recommend using something like Appcelerator or Red Foundry to build basic applications that can then be created natively on either platform. In these cases, you're not writing objective-c or java, you use some kind of intermediary. Note that if you move outside the box they've confined you to, you'll need to write your own code closer to the metal.