Skip to content

How to define a callback in C #1

@cihadturhan

Description

@cihadturhan

Hi @jwtan,

Thank you for sharing this, I spent countless hours to fix Unity + Swift problem. Without your explanation I couldn't understand what are the problems. I wish I could've found this repo earlier.
I think you should share this on unity forums because this is a hidden gem here :)

So, I have a project that I want to integrate with a swift library but I can't use the callback on swift:

I create a header to define my callback

// SwiftToUnityBridge.h
#ifndef SwiftToUnityBridge_h
#define SwiftToUnityBridge_h

#ifdef __cplusplus // gives error without it
extern "C" {
#endif

  typedef void (*SwiftCallback)(); //<- I define the callback here

#ifdef __cplusplus
}
#endif

#endif

Then, add a callback on mm file

// SwiftToUnityBridge.mm
#import <UnityFramework/UnityFramework-Swift.h>

extern "C"
{
    void UnityOnStart()
    {
        [[SwiftToUnity shared]   UnityOnStart];
    }

+    void CallWithACallback(SwiftCallback callback)
+    {
+        [[SwiftToUnity shared] callWithCallback: callback];
+    }
}

and, define a function on swift

// SwiftToUnity.swift
import Foundation

@objc public class SwiftToUnity: NSObject
{
    @objc public static let shared = SwiftToUnity()

    @objc public func UnityOnStart()
    {
        UnitySendMessage("Cube", "OnMessageReceived", "Hello World!");
    }
    
+    @objc public func call(callback: @escaping SwiftCallback)
+    {
+        callback();
+    }
}

And moved the header from project to public (I don't know if I should do this)
image

After that, I added the header to UnityFramework.modulemap

framework module UnityFramework {
  umbrella header "UnityFramework.h"

  export *
  module * { export * }

  module UnityInterface {
      header "UnityInterface.h"
+      header "SwiftToUnityBridge.h"

      export *
  }
}

But I can't find out why it still doesn't let me use the callback
image
Generated UnityFramework-Swift.h:
image

Thank you for sharing this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions