I have a Class defined in C++, I want to pass the instance of class from C++ to Swift as a reference type. By default swift maps C++ classes as value types but we can change this behavior by using SWIFT_IMMORTAL_REFERENCE annotation mentioned here. The example mentioned here is of Singelton class but I have a usecase where i require more than one instance.
Cpp Class Skeleton.
class Cpp {
public:
void Print () noexcept;
void SetValue (int pValue) noexcept;
// Method which is Invoked by Swift.
static Cpp& ReturnObj () noexcept;
private:
int vValue;
} SWIFT_IMMORTAL_REFERENCE;
Definition of Return Obj
Cpp&
Cpp::ReturnObj () noexcept {
static Cpp obj;
return obj;
}
Swift Co
var obj : Cpp = Cpp.ReturnObj()
withUnsafeBytes(of: &obj) {(pointer : UnsafeRawBufferPointer) in
print (pointer)
print (pointer.baseAddress!)
}
Output
Address Printed by C++
0x100008000
Address Printed by Swift
0x00007ff7bfeff108
So from the above observation copy is passed.
How to do pass by reference then?
Dive into the world of programming languages used for app development.
Post
Replies
Boosts
Views
Activity
I’m facing an issue while compiling a project with a CustomSDK on Xcode 16.0 Beta 6. The following error is displayed during the build process:
Failed to build module 'CustomSDK'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 5.9 (swiftlang-5.9.0.128.108 clang-1500.0.40.1)', while this compiler is 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.9.10 clang-1600.0.26.2)'). Please select a toolchain which matches the SDK.
Steps I have taken so far:
Set the BUILD_LIBRARY_FOR_DISTRIBUTION build setting to YES in the post_install script to ensure forward compatibility.
Cleaned the project and deleted Derived Data.
Verified that the latest SDK version was compiled using Swift 5 in Xcode 15.2, which should ensure compatibility with future versions.
Tried re-adding the SDK pod and rebuilt the project.
Despite these steps, the issue persists on Xcode 16 Beta 6. I suspect the problem could be related to a beta version of Xcode and compatibility issues, but I need guidance on how to ensure the SDK works with Xcode 16.
Is this a known issue with Swift versioning in the beta release? Are there any workarounds or specific changes I should apply to make the SDK work with Xcode 16 Beta 6?
Any help or suggestions would be appreciated!
I have a Usecase where I want to pass user-defined swift structure instance from Swift to C++ as argument to the C++ Function.
In the documentation it's mentioned that swift exposes these structures to c++.
Swift Structure.
public struct MyStruct {
public init (_ pValue : Int) {
uValue = pValue
}
public var uValue : Int
}
I am able to Create Instance in C++ .
Code
void
CppClass::CreateSwiftStruct ()
{
Interop::MyStruct my_struct = Interop::MyStruct::init (20);
}
But when I define a C++ Function which takes Interop::MyStruct as argument then that function doesn't get exposed to swift, so i am not able to call it.
Skeleton For CppClass
class CppClass {
static void PassStruct (Interop::MyStruct pStruct);
static void Test ();
}
Here PassStruct Method doesn't get exposed to C++ but Test does.
How can I pass Struct Instance in swift to C++ Function as In Param?
I have a struct defined in Swift, i want to pass it's instance pointer from swift to C++. When I am trying to directly return Typed Pointer from Swift Function to C++, the function doesn't get expose to C++.
Code which i have tried.
// Defined Structure
public struct MyStruct {
public init (_ pValue : Int) {
uValue = pValue
}
public var uValue : Int
}
var my_struct = MyStruct(20)
// Function which returns Struct Pointer to C++
// When I return typed pointer this function doesn't get exposed to C++
public func PassStructPointer () -> UnsafeMutablePointer<MyStruct> {
withUnsafeMutablePointer(to: &my_struct) { pointer in
return pointer
}
}
But when I pass UnsafeRawMutablePointer instead of type pointer then the function does get expose to C++
var my_struct = MyStruct(20)
// This get expose to C++.
public func PassStructPointer () -> UnsafeMutableRawPointer {
return withUnsafeMutableBytes(of: &my_struct) { pointer in
return pointer.baseAddress!
}
}
Can we not pass typed pointer of the types defined by us?
I have a use case where I want to return reference from Swift Function just like we can do in C++.
This is How we do it in C++:
int & ReturnIntRef () noexcept
{
static int a = 4;
return a;
}
Do we have equivalent of this in Swift ?
Hello,
I'm doing some test and I dowload the sample from here https://developer.apple.com/documentation/networkextension/local_push_connectivity/receiving_voice_and_text_communications_on_a_local_network
Everything works correctly and the phones are able to exchange messages without problems and the server sends pushes to the devices.
Now I would like to modify the server so that, when it sends the push to the mobile device, it can change the sound or add other information as is possible when using APN.
Now I would like to modify the server so that, when it sends the push to the mobile device, it can change the sound or add other information as is possible when using APN.
Is there any way to send a payload like for APN?
Thank's
Omar
I am trying to use the swift type UnsafeMutablePointer directly in C++. According to the documentation mentioned, swift expose this type to C++. But I am not able to use it .
void
GetPointerFromSwift () {
// Calls a swift function to get a pointer.
swift::UnsafeMutablePointer<swit::Int> x = Interop::GetPointer ()
}
When we pass a input to swift function it is passed as a constant, so does copy gets created or not here?
public func Test (_ pValue : Int) {
print (pValue)
}
let x : Int = 2
Test (x)
We have an in-house CLI tool built entirely in Python to help us with OS-level workflows. It’s been excellent, but we’re encountering some growing pains.
We’ve encountered a case where we’d like to use Apple’s Authorization Plugin, which we can’t directly utilize in Python.
Since I doubt this’ll be the last time we encounter Swift or Obj-C specific tools, I’m starting to wonder if a total rewrite into Swift might be in order.
Alternatives include writing a wrapper in Swift just for the Auth Plugin, exposing an API that we’ll consume in Python.
Since this will only ever be a macOS, tool, I’m starting to feel like going with Python was a dumb idea in the first place.
Would love to know what you guys think.
p.s.
I was advised to post my question on these forums in hopes of being graced by the Apple god Quinn, “The Eskimo”.
I have a use-case where I want to pass the user defined swift structure instantiated in swift and then pass it to a C++ Function as a Input Param. Is there a way to do that?
When i instantiate a structure defined in swift in C++ and then i pass it to swift function as a IN param, it is passed as a constant value to the function. Here the same structure instance is passed or a copy is created?
🚀 I am thrilled to announce my latest open-source project, RJSwiftMacros!
This Swift package enables developers to enhance efficiency by simplifying code generation and automating repetitive tasks in their projects. 🔥
Here's a glimpse of what you can accomplish with RJSwiftMacros:
Generate mock data using @MockBuilder macro.
Generate coding keys using @CodingKeys macro.
RJSwiftMacros is actively maintained and welcomes contributions! 🤝
🔗 GitHub Repository: https://lnkd.in/dPikQTjD
I look forward to your feedback and ideas to further enhance its value for the Swift community. 💻
Note that I am trying to build my project for IOS 18 using XCode version 16 Beta 6. I have version 18.0 of the iOS beta installed on my iPhone.
My project includes pods for Firebase and GRPC-Core. I ran pod update and it installed Firebase (11.1.0), BoringSSL-GRPC 0.0.36, OpenSSL-Universal 3.3.1000, and gRPC-Core 1.65.5.
When I try to build my project I encounter the following error: Undefined symbol: _c2i_ASN1_INTEGER
This symbol is not referenced in my code. It's unclear which pod references this symbol - although Firebase is a likely candidate. Is anyone else encountering this issue? I'm wondering if I could safely go back to a version of Firebase that does, as the previous version I had installed (10.22.0) didn't have this issue.
Hi I was using Xcode for c++ (for competitive programming purposes, not sure if this is the standard choice but using it anyway)
I included a <bits/stdc++.h> to the include file for XCode.app and they didn't show any error. But then when I ran my code, it showed "Build Succeeded" although no output was visible.
When calling a perl script from an apple script (by dropping a file on it), I get the error:
Can't load '/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle' for module Encode: dlopen(/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle, 0x0001): tried: '/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/System/Volumes/Preboot/Cryptexes/OS/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle' (no such file), '/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')) at /System/Library/Perl/5.34/XSLoader.pm line 96. at /Library/Perl/5.34/darwin-thread-multi-2level/Encode.pm line 12.
When I call the script manually from terminal, it runs fine.
Why is Applescript running as X86 on M2?
I'm looking at performance around large codable nested structures that come in from HTTP/JSON.
We are seeing stalls on the main thread, and after reviewing all the code, the webrequests and parsing are async and background. The post to set the new struct value (80K) is handled on mainthread.
When I looked at the nested structures, they are about 80K.
Reading several articles and posts suggested that observing structs will cause a refresh on any change. And that large structures will take longer as they have to be copied for passing to each observer. And that more observers will slow things down.
So a made a test app to verify these premises.
The app has an timer animating a slider.
A VM with a structure containing a byte array.
Sliders to scale the size of the byte array from 10K to 200K and to scale the number of observers from 1 to 100.
It also measures the actual duration between the timer ticks. My intention is to be able to visual see mainthread stalls and be able to measure them and see the average and max frame delays.
Using this to test I found little difference in performance given different structure sizes or number of observers. I'm not certain if this is expected or if I missing something in creating my test app.
I have also created a variation where the top struct is a an observable class. I see no difference between struct or class.
I'm wondering if this is due to copy-on-mutate causing the struct to actually be passed as reference under the good?
I wonder if other optimizations are minimizing the affect of scaling from 1 to 100 observers.
I appreciate any insights & critiques.
#if CLASS_BASED
class LargeStruct: ObservableObject {
@Published var data: [UInt8]
init(size: Int = 80_000) {
self.data = [UInt8](repeating: 0, count: size)
}
func regenerate(size: Int) {
self.data = [UInt8](repeating: UInt8.random(in: 0...255), count: size)
}
var hashValue: String {
let hash = SHA256.hash(data: Data(data))
return hash.compactMap { String(format: "%02x", $0) }.joined()
}
}
#else
struct LargeStruct {
var data: [UInt8]
init(size: Int = 80_000) {
self.data = [UInt8](repeating: 0, count: size)
}
mutating func regenerate(size: Int) {
self.data = [UInt8](repeating: UInt8.random(in: 0...255), count: size)
}
var hashValue: String {
let hash = SHA256.hash(data: Data(data))
return hash.compactMap { String(format: "%02x", $0) }.joined()
}
}
#endif
class ViewModel: ObservableObject {
@Published var largeStruct = LargeStruct()
}
struct ContentView: View {
@StateObject var vm = ViewModel()
@State private var isRotating = false
@State private var counter = 0.0
@State private var size: Double = 80_000
@State private var observerCount: Double = 10
// Variables to track time intervals
@State private var lastTickTime: Date?
@State private var minInterval: Double = .infinity
@State private var maxInterval: Double = 0
@State private var totalInterval: Double = 0
@State private var tickCount: Int = 0
var body: some View {
VStack {
Model3D(named: "Scene", bundle: realityKitContentBundle)
.padding(.bottom, 50)
// A rotating square to visualize stalling
Rectangle()
.fill(Color.blue)
.frame(width: 50, height: 50)
.rotationEffect(isRotating ? .degrees(360) : .degrees(0))
.animation(.linear(duration: 2).repeatForever(autoreverses: false), value: isRotating)
.onAppear {
isRotating = true
}
Slider(value: $counter, in: 0...100)
.padding()
.onAppear {
Timer.scheduledTimer(withTimeInterval: 0.005, repeats: true) { timer in
let now = Date()
if let lastTime = lastTickTime {
let interval = now.timeIntervalSince(lastTime)
minInterval = min(minInterval, interval)
maxInterval = max(maxInterval, interval)
totalInterval += interval
tickCount += 1
}
lastTickTime = now
counter += 0.2
if counter > 100 {
counter = 0
}
}
}
HStack {
Text(String(format: "Min: %.3f ms", minInterval * 1000))
Text(String(format: "Max: %.3f ms", maxInterval * 1000))
Text(String(format: "Avg: %.3f ms", (totalInterval / Double(tickCount)) * 1000))
}
.padding()
Text("Hash: \(vm.largeStruct.hashValue)")
.padding()
Text("Hello, world!")
Button("Regenerate") {
vm.largeStruct.regenerate(size: Int(size)) // Trigger the regeneration with the selected size
}
Button("Clear Stats") {
minInterval = .infinity
maxInterval = 0
totalInterval = 0
tickCount = 0
lastTickTime = nil
}
.padding(.bottom)
Text("Size: \(Int(size)) bytes")
Slider(value: $size, in: 10_000...200_000, step: 10_000)
.padding()
Text("Number of Observers: \(observerCount)")
Slider(value: $observerCount, in: 1...100, step: 5)
.padding()
HStack {
ForEach(0..<Int(observerCount), id: \.self) { index in
Text("Observer \(index + 1): \(vm.largeStruct.data[index])")
.padding(5)
}
}
}
.padding()
}
}
Hello,
I am using the withUnsafePointer API in Swift and have a question regarding the validity of the pointer returned by this API. Specifically, I want to understand if the pointer remains valid if the CPU performs a context switch due to its time-slicing mechanism while the closure is executing.
Is the pointer returned by withUnsafePointer guaranteed to be valid throughout the entire execution of the closure, even if a CPU context switch occurs as part of time slicing?
The following behavior seems like a bug in the swift compiler that ships with Xcode 16 beta 6.
Add the following code snippet to a new iOS app project using Xcode 16 beta 6 and observe the error an warning called out in the comments within the itemProvider() method:
import WebKit
extension WKWebView {
func allowInspectionForDebugBuilds() {
// commenting out the following line makes it so that the completion closure argument of the trailing closure
// passed to NSItemProvider.registerDataRepresentation(forTypeIdentifier:visibility:loadHandler:) is no longer
// isolated to the main actor, thus resolving the build issues. It is unexpected that the presence or absence of
// the following line would have this kind of impact.
isInspectable = true
}
}
class Foo {
func itemProvider() -> NSItemProvider? {
let itemProvider = NSItemProvider()
itemProvider.registerDataRepresentation(forTypeIdentifier: "", visibility: .all) { completion in
Task.detached {
guard let url = URL(string: "") else {
completion(nil, NSError()) // error: Expression is 'async' but is not marked with 'await'
return
}
let task = URLSession.shared.dataTask(with: url) { data, _, error in
completion(data, error) // warning: Call to main actor-isolated parameter 'completion' in a synchronous nonisolated context; this is an error in the Swift 6 language mode
}
task.resume()
}
return Progress()
}
return itemProvider
}
}
Now, comment out the line isInspectable = true and observe that the error and warning disappear.
Also filed as FB14783405 and https://github.com/swiftlang/swift/issues/76171
Hoping to see this fixed before Xcode 16 stable.
I have a usecase, where I have Data instance as Data is Value type copy will be created on assignment. I want to prevent copying for which I was using this Initializer of Data. Will it prevent copying?.
Hi, I was trying to understand how swift manages it memory just wanted to verify my understanding on it.
For Value Types i.e. Struct ARC (Automatic Reference Counting) is not there, Memory is Managed/Confined on the basis of scope of that Variable. And For Struct whenver we do assignment a Copy is been created.
For Classes, Swift Manages Memroy with the help of ARC i.e. whenever I create a instance of class its reference count get increased and when we assign same instance to new variable then it also result in increment of Reference Count. The Memory will get deallocated when all the variables pointing to that object are no longer in use.