Question

I am working on a project where using Cocoa and Objective C is not desired.

I stumbled across the Objective C runtime library the other day and have been trying to use it to access the dimensions of the screen.

This is the code I have currently:

auto screen = objc_msgSend(objc_lookUpClass("NSScreen"),sel_getUid("mainScreen")); //Returns an NSScreen*
auto frame = objc_msgSend(screen, sel_getUid("frame")); // should return an NSRect but I get an EXC_BAD_ACCESS and the program quits

Using Cocoa isn't an option and Carbon isn't really supported anymore. I'm hoping that someone is familiar with the Objc Runtime and is able to solve this problem.

Was it helpful?

Solution 2

If you really want to avoid Objective-C in getting this information, you'd need to dive into low level Quartz (and good luck with that!).

I think the commands that would help you would be:

CGGetActiveDisplayList and CGDisplayScreenSize

OTHER TIPS

auto screen = objc_msgSend(objc_lookUpClass("NSScreen"),sel_getUid("mainScreen")); //Returns an NSScreen*
auto frame = objc_msgSend(screen, sel_getUid("frame")); // BAD_ACCESS

The specific reason for the crash is because you need to use one of the variants of objc_msgSend(). Specifically, the one that can return large structures that otherwise don't fit on the stack.

Using Cocoa isn't an option

Using Cocoa via objc_msgSend() is still using Cocoa!

The above code is no more portable to any other platform than simply writing everything as Objective-C. You still can't use NSScreen on Linux or Windows and, thus, there is no point in compiling said lines of code on either platform.

You are far better off taking the same approach as other cross-platform libraries.

• create an API that is your generic cross platform UI API

• under that API, implement as much as you can in portable code

• create a low level bridging API that provides the interface between your portable code and the system

• for each platform implement that bridging API specific to the platform technology desired

This would allow you to use Objective-C directly on OS X while still maintaining a cross-platform API on top.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top