How to add Eigen to your iOS Swift project.
You’ve gotten OpenCV working inside your app, but still need a Numpy/Scipy alternative for iOS. Since OpenCV is now in C++, we need a C++ linear algebra library that can interop with cv::Mat
.
Eigen is a C++ library for linear algebra with stable tested codebase and deployed extensively in many applications, including Tensorflow. There are other great choices such as dlib and Armadillo, but eigen being a header-only library makes compatibility and compiling with Xcode and Swift much easier.
Setup Eigen
- Download Eigen from official site and extract to your project directory. It helps to rename the directory with current version, e.g.
my_ios_app/eigen_3.3.7
. - In Xcode, goto
Build Settings
thenHeader Search Paths
and add the above eigen directory, e.g.$(PROJECT_DIR)/eigen_3.3.7
Create Wrapper Class
To test that Eigen is added correctly, we’ll create a wrapper class to report the library version.
Goto File
-> New
-> File
and select Cocoa Touch Class
. We’ll name it EigenWrapper
.
Xcode will show a popup, click “Create Bridging Header”.
This will create 2 files, EigenWrapper.h
and EigenWrapper.m
in our project. To use C++ in Xcode, rename EigenWrapper.m
to EigenWrapper.mm
.
Add a static method to EigenWrapper.h
:
@interface EigenWrapper : NSObject+ (NSString *)eigenVersionString;@end
Then in EigenWrapper.mm
we’ll import the header file and the Eigen library:
#import <Eigen/Core>#import "EigenWrapper.h"
The library version is available at build time as macros, and we can return this to Objc with NSString:
+ (NSString *)eigenVersionString { return [NSString stringWithFormat:@"Eigen Version %d.%d.%d", EIGEN_WORLD_VERSION, EIGEN_MAJOR_VERSION, EIGEN_MINOR_VERSION];}
Setup Bridging Header
XCode uses a Bridging Header file to connect Obj-C (and in our case, Obj-C++) to Swift. The Bridging Header file will be named my_ios_app-Bridging-Header.h
. To allow our swift code to access our new wrapper class, we’ll need to import it within this Bridging Header:
#import "EigenWrapper.h"
Compile and Test
To make sure its working, lets call this in AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { print("eigen: ", EigenWrapper.eigenVersionString()) return true}
Hit Cmd+R
and watch the console log. If everything is setup correctly, we’ll see the library version reported:
eigen: Eigen Version 3.3.7
Happy coding!
Tips
- You don’t have to include the eigen library directly in the iOS app project, (it adds 16MB for library size). But it makes the repo easier to share and distribute among team members. It is crucial to setup the
Header Search Path
so that Xcode knows where to find it. - Include the eigen headers directly e.g.
<Eigen/Core>
, not from<Eigen/src/Core>
.
—