Skip to content

Instantly share code, notes, and snippets.

@xiaozhuai
Created August 27, 2025 11:53
Show Gist options
  • Select an option

  • Save xiaozhuai/d2b823fa860993ac2b518dd1ce773cfb to your computer and use it in GitHub Desktop.

Select an option

Save xiaozhuai/d2b823fa860993ac2b518dd1ce773cfb to your computer and use it in GitHub Desktop.
Call objc function from c++ world
#if defined(__APPLE__)
#include <objc/message.h>
#include <objc/objc.h>
#include <objc/runtime.h>
template <typename T, typename... Args>
T objc_call(id obj, const char *sel, Args... args) {
using FuncPtr = T (*)(id, SEL, Args...);
return reinterpret_cast<FuncPtr>(objc_msgSend)(obj, sel_registerName(sel), args...);
}
template <typename T, typename... Args>
T objc_call(const char *clazz, const char *sel, Args... args) {
return objc_call<T>(reinterpret_cast<id>(objc_getClass(clazz)), sel, args...);
}
#endif
void test() {
auto ns_window = glfwGetCocoaWindow(window);
CFRetain(ns_window);
auto view = objc_call<id>(ns_window, "contentView");
CFRetain(view);
objc_call<void, BOOL>(view, "setWantsLayer:", YES);
auto layer = objc_call<id>("CAMetalLayer", "layer");
auto scale_factor = objc_call<CGFloat>(ns_window, "backingScaleFactor");
objc_call<void, CGFloat>(layer, "setContentsScale:", scale_factor);
objc_call<void, id>(view, "setLayer:", layer);
CFRelease(view);
CFRelease(ns_window);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment