import SomeLibrary.SomeFeatureimport SomeLibrary.AnotherFeature.SmallFeature
// CLib/module.modulemap:module CLib {header "CLib.h"export *}
// CppLib/module.modulemap:module CppLib {header "CppLib-C.h"export *}
// CLib.h#include <stdio.h>int CLibTest(void);
// CppLib.h#include <iostream>int CppLibTest();
// CppLib-C.h#ifdef __cplusplusextern "C" {#endif
int CppLib_CppLibTest();
#ifdef __cplusplus}#endif
// CppLib-C.cpp#include "CppLib-C.h"#include "CppLib.h"
int CppLib_CppLibTest() {return CppLibTest();}
import UIKitimport CLibimport CppLib
class ViewController: UIViewController {override func viewDidLoad() {super.viewDidLoad()let cValue = CLibTest()let cppValue = CppLib_CppLibTest()}}
// CLib.h
typedef void(*show_alert_f)(const char *message);show_alert_f showAlertFunc;
bool DoSomeWork(void);The following C function is called from Swift and will trigger an alert.// CLib.c
show_alert_f showAlertFunc = NULL;
bool DoSomeWork() {char *alertMessage = "This is an alert message from C!";if (showAlertFunc) {showAlertFunc(alertMessage);return true;}
return false;}
import SomeLibrary.SomeFeatureimport SomeLibrary.AnotherFeature.SmallFeature
import UIKitimport CLib
class ViewController: UIViewController {override func viewDidLoad() {super.viewDidLoad()
// Assign the C function pointer, showAlertFunc, to local Swift function showAlertshowAlertFunc = showAlert}
@IBActionfunc buttonTapped(_ sender: UIButton?) {alertViewController = self// Call the C function DoSomeWork, which will trigger the alert to be shown via the function pointer showAlertFuncguard DoSomeWork() else {debugPrint("No function assigned to show alert")return}}}
fileprivate var alertViewController: UIViewController?
fileprivate func showAlert(_ message: UnsafePointer<Int8>?) {guard let viewController = alertViewController else {debugPrint("No view controller assigned for alert")return}
var alertMessage: String?if let message = message {alertMessage = String(cString: message)}let alert = UIAlertController(title: "Message", message: alertMessage, preferredStyle: .alert)alert.addAction(UIAlertAction(title: "Ok", style: .default))viewController.present(alert, animated: true)}
Find out how we can work together to bring your ideas to life.