I'm trying to use the OpenMP library for some parallel computing in a Swift application. I installed native libomp using homebrew.
- Create new Swift MacOS app project in Xcode.
- Add new C file and H file
Header file:
#include <omp.h>
size_t getNThreads(void);
C file:
#include "c_omp_test.h"
size_t getNThreads(void){
return omp_get_num_threads();
}
- Xcode automatically add bridging header
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#include "c_omp_test.h"
- Add "-Xpreprocessor -fopenmp" to "Other C flags"
- Add "Header Search Paths" and "Library Search Paths"
- Add "-lopm" to "Other Linker Flags"
- Add call getNThreads from Swift
import SwiftUI
struct ContentView: View {
@State private var nThreads : Int = 0
var body: some View {
VStack{
Text ("Number of threads \(nThreads)")
Button("Get number of threads"){
nThreads = getNThreads()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
First I got the following error message when launching the application
'/opt/homebrew/*/libomp.dylib' (code signature in <39E30DBF-F7E5-3113-954E-1798A7F5B050> '/opt/homebrew/Cellar/libomp/13.0.0/lib/libomp.dylib' not valid for use in process: mapped file has no Team ID and is not a platform binary (signed with custom identity or adhoc?))
After that I disable Library Validation checkbox in "Hardened Runtime" section. Now the application starts normally, but when calling the getNThreads() function I get
OMP: Error #178: Function Can't open SHM2 failed: OMP: System error #1: Operation not permitted
and crush report.
If I create a swift console application, everything works just fine.