Can you use C++ libraries in a Cocoa (Obj-C) project? - c++

I'm considering learning Objective-C and Cocoa, mostly in order to use Apple's tools and GUIs.
However, I'd also like to do some graphics programming; OpenFrameworks and Cinder are two libraries which catch my eye, but then we're in C++ land.
I come from a Java/Swing/Processing background... don't know much about the C family. How effectively can you call C and C++ libraries, like Cinder and OF, from native Cocoa?
And, bonus points: would a solution like this work on an iPhone or iPad?

In short, C++ is just fine for OS X and iOS programs, and plays with Objective-C quite nicely.
In more detail:
However, I'd also like to do some graphics programming; OpenFrameworks and Cinder are two libraries which catch my eye, but then we're in C++ land.
I won't speak for those libraries directly.
To answer your question in more general terms: C++ is just fine in your app, since C, C++, ObjC, and ObjC++ are first class development languages for iOS apps.
I come from a Java/Swing/Processing background... don't know much about the C family. How effectively can you call C and C++ libraries, like Cinder and OF, from native Cocoa?
Objective-C++ allows you to use C, C++, and Objective-C all in the same translation. Feel free to use/combine C++, C, or ObjC where needed. The compile times will increase, and there are some restrictions* if you take this route. Otherwise, support is very good. Even Apple uses a good amount of C++ in their apps/libs.
And, bonus points: would a solution like this work on an iPhone or iPad?
Definitely. c++11 support for iOS and OS X is currently a bit behind. However, the clang team's been adding support for it very very quickly. There will likely be some bumps if you want the latest features, so I'd say hold back on bleeding edge C++ and compiler features if your project depends on it. Of course, it does not hurt to sample your program using the latest clang features with each release in order to determine how well it works with your programs.
Update: At this point (Nov 8, 2011) clang can handle nearly all of the C++ 2003 code I throw at it. Code speed and size does vary compared to GCC+LLVM. I would not want to drop either at this point, but both compilers work well for me with C++ 2003, and Apple's GCC will not support c++11, so it's a good time to start testing clang if you want c++11 features in the near future.
C++ is ideal (IMO) for general performance critical development on iOS, as long as your team knows how to use it.
Mixing C, ObjC and C++ is very powerful if you use the right features of each language for the right reasons, and good compatibility exists. This reaches back years from OS X (although the compiler was GCC at the time).
*restrictions: these are reasonable restrictions - all the features you need exist, but there are some things that people may expect which are not possible. the most common is likely the inability to derive types of different object models. that is, you cannot reasonably not create a c++ type from an objc type, but you can freely declare ivars of multiple types in either object type.

It is possible to use both OpenFrameworks and Cinder in iOS applications (see this related SO question: OpenGL ES, OpenFrameworks, Cinder and IOS creative development), though Apple "prefers" developers to use OpenGL.

As of now you can use Cinder from within a typical Cocoa project via the new CocoaCinderGL wrapper. It lets you add several NSCustomView's to your application, each one running an independent "instance" of Cinder. And obviously you can connect as many NSButtons, NSSliders as you like to those instances. Hope that helps!

Related

Creating an application on Mac OS X using C++? (without Cocoa)

It seems that in Xcode 4 there is no longer a way to create an application that is not limited to the command line using C or C++. I would like to do so, however Glut seems to be one of the only frameworks available for mac that works with C++ and OpenGL, however gluts features are beginning to stop working on modern Operating Systems. Are there other alternatives that will allow me to use C++ or C for software development on a mac? It does not have to be limited to using xcode or opengl.
Yes, it's possible, but it may not be a very good idea. The real question is what problem are you trying to solve?
If you just don't like Obj-C, it should be straightforward to write a very thin shim that wraps the calls you care about in C++.
If you are trying to prove a point, you can actually make calls directly into the Obj-C runtime in plain C code. See this for example: using objc_msgSend to call a Objective C function with named arguments
If it's something else, please enlighten us so we can better answer your question.
QT is your best bet. It comes with a serious IDE and the libraries are written in a very good & intuitive C++.
QT can be found here: http://qt-project.org/downloads
If all you want is a window, an OpenGL context, and user interfacing, then go the SDL way. Completely written in C, cross platform, and almost object-oriented (most data types are structs, anyways). It's also very memory economic (its core DLL is less than 500KB in size and a windowless program uses less than 1MB of RAM on Linux), unlike the monster that is Qt.
I'd also recommend LazyFoo's tutorials to get started, since they indeed cover the learning from the perspective of a C++ programmer, not a C one.

How portable IS C++?

In C++, if I write a simple game like pong using Linux, can that same code be compiled on Windows and OSX? Where can I tell it won't be able to be compiled?
You have three major portability hurdles.
The first, and simplest, is writing C++ code that all the target compilers understand. Note: this is different from writing to the C++ standard. The problem with "writing to the standard" starts with: which standard? You have C++98, C++03, C++TR1 or C++11 or C++14 or C++17? These are all revisions to C++ and the newer one you use the less compliant compilers are likely to be. C++ is very large, and realistically the best you can hope for is C++98 with some C++03 features.
Compilers all add their own extensions, and it's all too easy to unknowingly use them. You would be wise to write to the standard and not to the compiler documentation. Some compilers have a "strict" mode where they will turn off all extensions. You would be wise to do primary development in the compiler which has the most strictures and the best standard compliance. gcc has the -Wstrict family of flags to turn on strict warnings. -ansi will remove extensions which conflict with the standard. -std=c++98 will tell the compiler to work against the C++98 standard and remove GNU C++ extensions.
With that in mind, to remain sane you must restrict yourself to a handful of compilers and only their recent versions. Even writing a relatively simple C library for multiple compilers is difficult. Fortunately, both Linux and OS X use gcc. Windows has Visual C++, but different versions are more like a squabbling family than a single compiler when it comes to compatibility (with the standard or each other), so you'll have to pick a version or two to support. Alternatively, you can use one of the gcc derived compiler environments such as MinGW. Check the [list of C++ compilers](less compliant compilers are likely to be) for compatibility information, but keep in mind this is only for the latest version.
Next is your graphics and sound library. It has to not just be cross platform, it has to look good and be fast on all platforms. These days there's a lot of possibilities, Simple DirectMedia Layer is one. You'll have to choose at what level you want to code. Do you want detailed control? Or do you want an engine to take care of things? There's an existing answer for this so I won't go into details. Be sure to choose one that is dedicated to being cross platform, not just happens to work. Compatibility bugs in your graphics library can sink your project fast.
Finally, there's the simple incompatibilities which exist between the operating systems. POSIX compliance has come a long way, and you're lucky that both Linux and OS X are Unix under the hood, but Windows will always be the odd man out. Things which are likely to bite you mostly have to do with the filesystem. Here's a handful:
Filesystem layout
File path syntax (ie. C:\foo\bar vs /foo/bar)
Mandatory Windows file locking
Differing file permissions systems
Differing models of interprocess communication (ie. fork, shared memory, etc...)
Differing threading models (your graphics library should smooth this out)
There you have it. What a mess, huh? Cross-platform programming is as much a state of mind and statement of purpose as it is a technique. It requires some dedication and extra time. There are some things you can do to make the process less grueling...
Turn on all strictures and warnings and fix them
Turn off all language extensions
Periodically compile and test in Windows, not just at the end
Get programmer who likes Windows on the project
Restrict yourself to as few compilers as you can
Choose a well maintained, well supported graphics library
Isolate platform specific code (for example, in a subclass)
Treat Windows as a first class citizen
The most important thing is to do this all from the start. Portability is not something you bolt on at the end. Not just your code, but your whole design can become unportable if you're not vigilant.
C++ is ultra portable and has compilers available on more platforms than you can shake a stick at. Languages like Java are typically touted as being massively cross platform, ironically they are in fact usually implemented in C++, or C.
That covers "portability". If you actually mean, how cross platform is C++, then not so much: The C++ standard only defines an IO library suitable for console IO - i.e. text based, so as soon as you want develop some kind of GUI, you are going to need to use a GUI framework - and GUI frameworks are historically very platform specific. Windows has multiple "native" GUI frameworks now - the C++ framework made available from Microsoft is still MFC - which wraps the native Win32 API which is a C API. (WPF and WinForms are available to CLR C++).
The Apple Mac's GUI framework is called Cocoa, and is an objective-C library, but its easy to access Objective C from C++ in that development environment.
On Linux there is the GTK+ and Qt frameworks that are both actually ported to Windows and Apple, so one of these C++ frameworks can solve your "how to write a GUI application in C++ once that builds and runs on windows, apple mac and linux".
Of course, its difficult to regard Qt as strictly C++ anymore - Qt defines a special markup for signals and slots that requires a pre-compile compile step.
You can read the standard - if a program respects the standard, it should be compilable on all platforms that have a C++ standard-compliant compiler.
As for 3rd party libraries you might be using, the platform availability is usually specified in the documentation.
When GUI comes to question, there are cross-platform options (such as QT), but you should probably ask yourself - do I really want portability when it comes to UI? Sometimes, it's better to have the GUI part platform-specific.
If you are thinking of porting from Linux to Windows, using OPENGL for the graphical part gives you freedom to run your program on both operating systems as long as you don't use any system specific functionality.
Compared to C, C++ portability is extremely limited, if not completely unexisting. For one you can't disable exceptions (well you can), for the standard specifically says that's undefined behaviour. Many devices don't even support exceptions. So as for that, C++ is ZERO portable. Plus seeing the UB, it's obvioulsy a no-go for zero-fail high-performance real time systems in which exceptions are taboo - undefined behaviour has no place in zero-fail environment. Then there's the name mangling which most, if not every, compiler does completely different. For good portability and inter-compatibility extern "C" would have to be used to export symbols, yet this renders any and all namespace information completely void, resulting in duplicate symbols. One can ofcourse choose to not use namespaces and use unique symbol names. Yet another C++ feature rendered void. Then there's the complexity of the language, which results in implementation difficulties in the various compilers for various architectures. Due to these difficulties, true portability becomes a problem. One can solve this by having a large chain of compiler directives/#ifdefs/macros. Templates? Not even supported by most compilers.
What portability? You mean the semi-portability between a couple of main-stream build targets like MSVC for Windows and GCC for Linux? Even there, in that MAIN-STREAM segment, all the above problems and limitations exist. It's retarded to even think C++ is portable.

C or C++ for a Robot?

Greetings,
I am trying to decide between C and C++ for my robot. I am a 5+ year veteran of Visual Basic.NET, however I'm going with Linux (Ubuntu) on this robot, and there is a compatibility problem between Linux and the .NET Framework. I want to stick with whichever language I choose for all of my projects, so I want to make sure that I choose the most appropriate one for the task.
For reference, I will describe my current robot in progress and what I am going to do with it. I am in the process of building a full-sized R4 Astromech (yep, I'm one of those guys). I have incorporated a PC motherboard with an Intel Core 2 2.1 GHz processor, 1 GB RAM. I will be using a scratch-built parallel interface card to control the drive motors, head motor, as well as a secondary parallel interface card (going to a second parallel port) which all of the sensors (IR, Ultrasonic Ranging, Visual Recognition via webcam, etc.) will be going to. Commands will be given using speech recognition (currently have a VB.NET scratch-built recognition program that I will be adapting to the new language).
Given the specifications and desired goals listed above, would I be better off with C or C++? I greatly appreciate any suggestions that you might have.
Thanks!
Thaskalas
What do you mean by a compatibility problem? Have you looked at Mono? It's an open-source implementation of the .NET libraries. It's geared toward C# not VB.NET but if you're more comfortable in a .NET environment use that. Speed isn't really an issue here as a Core2Duo is plenty fast for what you need to do.
If Mono won't work for you, I'd recommend C++. There are a lot more libraries out there for C++ (or at least, I am familiar with more, e.g. Boost), which can use most C libraries too. There's no real speed penalty for using C++. While using C wouldn't be bad per-se, C++ has some benefits and no drawbacks, so it's probably the better choice.
I would recommend using ROS. It will let you get started with a sophisticated Inter-Process Communications manager, as well as a large library of sophisticated robotics code, including multiple implementations of SLAM and other critical robotics algorithms. ROS also lets you program in multiple languages, including C, C++, and Python, so you aren't stuck with one language or another down the road.
I would also recommend C++ and ROS. In our company we're migrating to it, because there's so many people working on it, expanding it, and adding lots of cool features.
With this, you can forget about implementing most of the basic low-level stuff and start working on what you intend to research.
It's really easy to set up and start developing.
Since you're running Linux on it, I'd recommend a split approach, where you do the lower-level (device interface, where you may need fast performance) stuff in C (or C++), and the higher level stuff in a modern language like C# (using Mono) or Java, or even Python.
Python especially is hugely expressive, has a large set of libraries, and has a pretty straightforward C interface.
Writing your high-level control stuff in a low-level language like C/C++ will get old fast (IMHO). Robots should be fun!
Have you considered D? It's a fairly new language, is compiled to native code and can link directly to C. (The entire C standard library is even available from D, and bindings to the POSIX API are included in the standard library.) Basically all you need to do to use any C library from D is compile it with a C compiler and translate the function prototypes, constant declarations, etc. in the header file.
D is low-level enough that an experimental kernel is written in it, but has modern features like garbage collection (though manual memory management is still permitted), builtin strings and arrays, and more advanced/easier to use template metaprogramming facilities than C++. The biggest disadvantage is lack of a mature toolchain and libraries for enterprise-y things, but for your purposes that probably doesn't matter. BTW, if you need to do a bunch of matrix manipulation and stuff, there's the SciD project, which provides nice templated wrappers over LAPACK and BLAS.
Use C++. You have the space. You can use it "as a better C" to start with.
C++ is a bigger tool bag; why would you not want that!? You need not use all the tools, but with C you'd have no choice. Most importantly with C++ you have the choice of using both C and C++ third-party libraries.

Best way to convert Delphi code to C++?

I have an application written in Delphi that compiles in Delphi 2007. I think it was originally written in Delphi 7.
Anyway, I need to convert all the core non-GUI code into C++ because I want to release a Mac version of the software.
What is the best way to do this? Any shortcuts I can take to speed up the process?
EDIT: The code compiles to native code, not .NET.
Simple answer: You simply can't port non-trivial Delphi code to C++ without a complete rewrite. C++'s object model is very different from Delphi's. It doesn't have a base class like TObject from which all other objects are derived, and it lacks support for a lot of the RTTI stuff that Delphi code often takes for granted. And there's no simple way to reimplement Delphi RTTI in C++, since a lot of it's done at the compiler level, and a lot of it's based on the fact that all Delphi classes descend from TObject.
C++ also lacks support for the concept of unit initialization and finalization sections that are so common in Delphi, and what it has instead is badly broken. (Look up the "static order initialization fiasco" for all the gory details.)
Delphi's exception handling is also much more advanced than C++'s. Part of this is the object model and part of it's compiler magic. Plus, C++ has no support for the try-finally construct.
If you want to port a Delphi project to the Mac, Free Pascal is your best solution. It's not 100% compatible with Delphi, but it's good enough for a lot of things, and you specifically mentioned that you don't need to port the Delphi GUI stuff. AFAIK the GUI area is the source of most of FPC's compatibility weaknesses, so if that's not necessary, FPC is probably pretty close to ideal for your needs, at least until CodeGear gets an OSX compiler out. (Which hasn't been officially announced, but based on various things that have been said it's not unreasonable to suppose that one will be available sometime next year.)
For converting your code from Delphi to Cpp, have a look at
http://ivan.vecerina.com/code/delphi2cpp/.
I used this to convert some of the classes and functions in SysUtils, DateUtils and StrUtils using wxWidgets functions. If you are planning to use wxWidgets for C++ have a look at http://twinforms.com/products/wxwidgets/wxvcl.php which has all the converted source.
If you want directly develop Mac OSX applications using then have a look at wxForms for Delphi - http://twinforms.com/products/wxformsdelphi/index.php
I think this would be difficult to do mechanically, so you are probably looking at a complete re-write. One thing to bear in mind is that typically Delphi uses try...finally structures for resource management, whereas C++ uses a technique known as RAII (resource acquisition is initialisation). You should read up on this and other C++ idioms before you attempt the conversion.
If your code compiles in Delphi 2007 into .NET assemblies, you may have a much easier option than trying to port from Delphi's object pascal to C++.
You could potentially compile your logic into .NET assemblies (and maybe even portions of the UI), and use Mono to run it on Mac. You could write a custom GUI around Mono, or even potentially make a single, platform independent application.
You can use also Delphi Prism. It's for .NET, but it's the last expression in Delphi language spec. It supports also Mac OSX (see the link). Also the guys from CodeGear/EMBT are in the works for a new compiler as well as for a new version of Delphi which is expected to enter in beta in April and narrow the gap between Prism and RAD studio. See their 'Beta Programs' page.
The "correct" way to do this is to rewrite it in Objective C. I find Objective C a little weird, but there are a lot of similarities with Delphi in the way objects connect and delegate.
You may be able to use Free Pascal to do it more quickly, but you should seriously consider a rewrite.
I would be in love with Embarcadero if they could release a Mac OS X version of Delphi that didn't, you know, suck like Kylix did. One can dream.
Edit: There is a great benefit to staying in Delphi, and having a separate version for the Mac in Objective C. First, it means you don't need to rewrite the version on Windows, losing the (presumably) years of investment in Delphi code. Second, Mac software operates differently than Windows, from a UI perspective. A simple port of the product is inappropriate, and hobbles the developer from using the great native features of Windows and Mac. See: older versions of MS Word for Mac, or iTunes for Windows. They look and feel wrong.

How to revive C++ skills

I was a C++ developer (mostly ATL/COM stuff) until, as many of us, I switched to C# in 2001. I didn't do much C++ programming since then.
Do you have any tips on how to revive my C++ skills? What has changed in C++ in the last years? Are there good books, articles or blogs covering the language. The problem is that most material I could find either targets people who are new to the language or those with a lot of experience.
Which C++ libraries are popular these days? I guess I will need to read on the STL because I didn't use it much. What else? Boost? ATL? WTL?
Boost - though it, and other libraries were around back then, its only relatively recently that it's taken off in a big way. Google for TR1 and c++0x standards too. You should defintely read up on STL because (IMHO) its the thing that makes C++ special.
ATL is as good a dead technology (don't get me wrong, I liked it and still use it somewhat, but its not fashionable in the MS world anymore).
Something like QT is probably more new and cool for C++ developers, and has the advantage of getting you into all the new Linux and web development that'll be increasingly popular over the next few years.
However, once you start looking at the things you can do, I think it'll all come back quite quickly.
I personally find that syntax is where i mostly need to catch up when i wander back to a language i havent used in a long time. But the concepts and what the language is about stays the same in memory.
Assuming its the same with you, i would say its a good idea to relook at the texts you remember to have been useful to you while learning C++. I would recommned Thinking in C++ for getting up fast on the syntax.
STL would be really useful yes. Thats one thing i have found commonly appreciated by all mature C++ programmers. It would be useful to know the libraries that Boost provides.
The changes to C++ world, depends on the changes your favourite compiler has decided to implement. Since you mentioned ATl/COM i assume it would be VC++. The changes to MFC would be support for Windows Forms (2005 vc++) and Vista compliant uI's and ribbon support(?) (2008 Vc++)
VC++ now supports managed C++ -i'm sure you know what that is coming from the C# world - 2008 adds supports for managed STL too.
VC++ is trying to be more standards compliant and are making some progress in that area.
They have introduced lots of secure functions that depreciate the old stds like strcpy and the compilers will also give warnings if you use the old fns.
VC++2005 also has something called function attributes, which it uses to describe the parameters so that it can do more checking on the inputs you pass in and statically flag a warning if it sees soething amiss. Usefuli would say though our shop has not progressed to using the 2005 compiler.
MSDN has the list of breaking changes for each releases. Oh & Support for Windows 95, Windows 98, Windows Millennium Edition, and Windows NT 4.0 has been removed from 2005 version of VC++. Additionally the core libraries you required till now (CRT, ATL, MFC etc) now support a new deployment model which makes them shared side sy side assemblies and requires a manifest.
This link should get you going - http://msdn.microsoft.com/en-us/library/y8bt6w34.aspx
2008 adds even more like Tr1 recommendations, more optimizning compiler, parallel compilation(/mp), support for new processor architectures etc. Open Mp support has also been enhanced in one of these versions is what i remember.
Again refer MSDN - thats the suthentic source for all the answers.
Good luck.
Definitely read the latest edition of "Effective C++" by Scott Meyers. I would also recommend "C++ Gotchas: Avoiding Common Problems in Coding and Design" by Stephen C. Dewhurst.
To sharpen your C++ skills I'd suggest going over some of your old C++ code if you still have access to it. Revisiting it will hopefully trigger those parts of your brain that have laid dormant after switching to C# :)
For libraries STL is good, then boost. I don't think there is too much new stuff going on with ATL/WTL from what you would have known back in 2001.
Just start a project. The libraries you use will depend on your project, but you should certainly read up on the STL. If you haven't used C++ for a long time you might need learn more about templates.
Pickup one of the C++ Unit Test frameworks out there (I suggest Google C++ Testing Framework, aka. gtest). Pick a small project that you can start from scratch and try some TDD. The TDD will encourage you to make small steps and to reflect on your code. Also, as you build your suite of unit tests, it gives you a base from which you can experiment with different techniques.
Rewrite some of your C# stuff using C++
For a start, I'd say try writing code that will work on both a Mac and Windows or Linux and Windows. This will force you to write code that is much more portable than the type of C++ code you can get away with on Visual C++ - there a lot of finer points that are very different when you go cross platform.
I'd suggest stay away from libraries for now if you can - perfect your ANSI C++ game first. I'd also suggest reading up on C++0x - the next standard is due soon and it would help you more to work towards that. To that end, brush up on the STL (the concepts behind it, not the implementation so much) and templates.
If you'd like to try BOOST, go ahead, but you can generally get by without using it. The reason I stayed away from it mostly is because of the way templates are used to do what is needed - a lot of which will become much easier once the new standard is introduced.
UPDATE: Once you're comfortable with the STL and start needing to do things that require a lot of code with the STL or are just plain tricky, then head over to BOOST. Buy a book on BOOST and read it and understand it well.
Take some old piece of code and add to it. This won't get you back on top of the latest C++ trends but it will get your feet wet.
At my job I had to add some features to a C++ ActiveX control and I hadn't touched C++ in years and years and have never done it professionally. Figuring out how to do it again was actually pretty damn cool.
I was in a similar situation: switched from C++ to C# in 2005 and then switched back to C++ in 2007. I can't say C++ universe really changed in those 2 years. The most crucial thing was to regain my memory-management instincts, but that can only be done by practicing.
Now that you have both C++ and .NET under your belt you might want to study C++ CLI a bit (new incarnation of late "Managed C++").
As for books, read everything with "Meyers" and "Sutter" on the cover.