In windows I used
__try {
__int64(__fastcall * calladdress)(__int64, __int64);
calladdress = (__int64*)par1;
returnvalue = calladdress(par2, par3);
}
__except (EXCEPTION_EXECUTE_HANDLER) {
returnvalue = 0;
}
In linux,
ptr64 functionaddr = data[0];
ptr64 par1 = data[1];
ptr64 par2 = data[2];
void * returnAddr = (void*) data[3];
ptr64(__fastcall* calladdress(ptr64,ptr64);
calladdress = (ptr64*)functionaddr;
*(ptr64*)returnAddr = calladdress(par1,par2);
Error: expected ')' befor '*' token
ptr64(__fastcall* calladdress(ptr64,ptr64);
^ here
Sorry for newbie question, but I don't know much about gcc.
It worked well in Windows, but I don't know how to compile this code on Linux.
If you know how to solve this problem, please reply.
First of all, I don't know much about Linux, so I can't guarantee that my answer is exactly right.
Just a quick search showed that the Linux kernel seems to be using fastcall like this.
#define FASTCALL(x) x __attribute__((regparm(3)))
#define fastcall __attribute__((regparm(3)))
More references:
x86 gcc compiled assembly code: fastcall behavior
I'm unsure of how to get DXGI GUIDs without the C++-only __uuidof operator. It's used all over the MSDN code. I'm also unsure of the syntax of calling OO Windows APIs in C.
I've checked on MSDN and here, but found nothing.
#ifdef __cplusplus
CreateDXGIFactory(__uuidof(IDXGIFactory), (void **)&factory);
factory->EnumAdapters(0, &adapter);
adapter->EnumOutputs(0, &output);
#else // C version, not correct AFAIK
?? CreateDXGIFactory(&IID_IDXGIFactory, (void **)&factory);
?? IDXGI_EnumAdapters(factory, 0, &adapter);
?? IDXGI_EnumOutputs(adapter, 0, &output);
#endif
The first works, but the C version fails with unresolved, DXGI-related externals (EnumAdapters and EnumOutputs and IID_DXGIFactory).
This should be fine:
#define COBJMACROS
#include <dxgi.h>
void test()
{
IDXGIFactory* factory;
if (SUCCEEDED(CreateDXGIFactory(&IID_IDXGIFactory, (void**) &factory)))
{
IDXGIAdapter* adapter;
if (SUCCEEDED(IDXGIFactory_EnumAdapters(factory, 0, &adapter)))
{
// ...
}
}
}
I'm creating an application in pure C on Mac OSX.
What I want is to create window in witch my app will be stored.
Preferably I want it to be pure C solution, but if I have to use objective-c class to init window and then send context to my C code then it will be fine.
I'm not using xcode, only simple text editor in with I tried to import cocoa but it just generated a lot of errors.
So in summary my question is:
How in simple pure C generate code that will display osx window?
I did a translation of the accepted answer to Pure C:
// based on https://stackoverflow.com/a/30269562
// Minimal Pure C code to create a window in Cocoa
// $ clang minimal.c -framework Cocoa -o minimal.app
#include <objc/runtime.h>
#include <objc/message.h>
#include <Carbon/Carbon.h>
#define cls objc_getClass
#define sel sel_getUid
#define msg ((id (*)(id, SEL, ...))objc_msgSend)
#define cls_msg ((id (*)(Class, SEL, ...))objc_msgSend)
// poor man's bindings!
typedef enum NSApplicationActivationPolicy {
NSApplicationActivationPolicyRegular = 0,
NSApplicationActivationPolicyAccessory = 1,
NSApplicationActivationPolicyERROR = 2,
} NSApplicationActivationPolicy;
typedef enum NSWindowStyleMask {
NSWindowStyleMaskBorderless = 0,
NSWindowStyleMaskTitled = 1 << 0,
NSWindowStyleMaskClosable = 1 << 1,
NSWindowStyleMaskMiniaturizable = 1 << 2,
NSWindowStyleMaskResizable = 1 << 3,
} NSWindowStyleMask;
typedef enum NSBackingStoreType {
NSBackingStoreBuffered = 2,
} NSBackingStoreType;
int main(int argc, char *argv[])
{
// id app = [NSApplication sharedApplication];
id app = cls_msg(cls("NSApplication"), sel("sharedApplication"));
// [app setActivationPolicy:NSApplicationActivationPolicyRegular];
msg(app, sel("setActivationPolicy:"), NSApplicationActivationPolicyRegular);
struct CGRect frameRect = {0, 0, 600, 500};
// id window = [[NSWindow alloc] initWithContentRect:frameRect styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO];
id window = msg(cls_msg(cls("NSWindow"), sel("alloc")),
sel("initWithContentRect:styleMask:backing:defer:"),
frameRect,
NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskResizable,
NSBackingStoreBuffered,
false);
msg(window, sel("setTitle:"), cls_msg(cls("NSString"), sel("stringWithUTF8String:"), "Pure C App"));
// [window makeKeyAndOrderFront:nil];
msg(window, sel("makeKeyAndOrderFront:"), nil);
// [app activateIgnoringOtherApps:YES];
msg(app, sel("activateIgnoringOtherApps:"), true);
msg(app, sel("run"));
}
You can use Objective-C runtime API example (iOS) Creating an iOS app in pure C
Alternative the same code in obj-c :
echo '#import <Cocoa/Cocoa.h>
int main ()
{
#autoreleasepool{
[NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
id applicationName = [[NSProcessInfo processInfo] processName];
id window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 120, 120)
styleMask:NSTitledWindowMask backing:NSBackingStoreBuffered defer:NO];
[window cascadeTopLeftFromPoint:NSMakePoint(20,20)];
[window setTitle: applicationName];
[window makeKeyAndOrderFront:nil];
[NSApp activateIgnoringOtherApps:YES];
[NSApp run];
}
return 0;
}' | gcc -fobjc-arc -framework Cocoa -x objective-c -o MicroApp - ; ./MicroApp
This will run Cocoa app with 1 window. Like on screenshot below
You can actually add menu using NSMenu
id applicationMenuBar = [NSMenu new];
id appMenuItem = [NSMenuItem new];
[applicationMenuBar addItem:appMenuItem];
[NSApp setMainMenu: applicationMenuBar];
Can you do this? Yes and no (you can do anything if you're persistent enough). Yes you can, but no you shouldn't. Regardless, this can be done for the incredibly persistent among you. Since coding up an example will take awhile, I found a generous soul on the net who already did it. Look at this repository on GitHub for the full code and explanations. Here are some snippets:
cmacs_simple_msgSend((id)objc_getClass("NSApplication"), sel_getUid("sharedApplication"));
if (NSApp == NULL) {
fprintf(stderr,"Failed to initialized NSApplication... terminating...\n");
return;
}
id appDelObj = cmacs_simple_msgSend((id)objc_getClass("AppDelegate"), sel_getUid("alloc"));
appDelObj = cmacs_simple_msgSend(appDelObj, sel_getUid("init"));
cmacs_void_msgSend1(NSApp, sel_getUid("setDelegate:"), appDelObj);
cmacs_void_msgSend(NSApp, sel_getUid("run"));
As you'll notice, this code uses the Objective-C runtime API to create a faux AppDelegate. And creating the window is an involved process:
self->window = cmacs_simple_msgSend((id)objc_getClass("NSWindow"), sel_getUid("alloc"));
/// Create an instance of the window.
self->window = cmacs_window_init_msgSend(self->window, sel_getUid("initWithContentRect:styleMask:backing:defer:"), (CMRect){0,0,1024,460}, (NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask | NSMiniaturizableWindowMask), 0, false);
/// Create an instance of our view class.
///
/// Relies on the view having declared a constructor that allocates a class pair for it.
id view = cmacs_rect_msgSend1(cmacs_simple_msgSend((id)objc_getClass("View"), sel_getUid("alloc")), sel_getUid("initWithFrame:"), (CMRect){ 0, 0, 320, 480 });
// here we simply add the view to the window.
cmacs_void_msgSend1(self->window, sel_getUid("setContentView:"), view);
cmacs_simple_msgSend(self->window, sel_getUid("becomeFirstResponder"));
// Shows our window in the bottom-left hand corner of the screen.
cmacs_void_msgSend1(self->window, sel_getUid("makeKeyAndOrderFront:"), self);
return YES;
So, yes. You can write a Cocoa app in pure C. But I wouldn't recommend it. 90% of that code can be replaced by an xib file, and doing it this way really restricts your app because more advanced features of the Apple development stack really on Objective-C features. While it's technically possible to do everything this way, you're making it much harder than it ought to be.
I remember seeing this question about a year ago, back when I so desperately wished I could open up a d*** window, googling for days and only finding the type of answers you see above this post.
I was reading up on the operating system the Mac is built on - Berkley Software Distribution. http://codex.cs.yale.edu/avi/os-book/OS9/appendices-dir/a.pdf Where on page 17 the phrase "...X Windowing System developed at MIT" hit me and I remembered how I couldn't open up a window and how pissed I was about that, and I thought maybe this was finally the solution!
I googled "BSD X Window Programming" and stumbled my way into finally getting a window open in pure C.
I just discovered it so I'm not a master yet but look at this link https://en.wikibooks.org/wiki/X_Window_Programming/Xlib and go to the example, make sure to follow the comments at the top for how to compile with the X11 library (you can ignore the -Wall and -O commands as long as you have the -lX11).
If you can't compile, if it can't find the header files, you'll need to help it find the header files.
There might be a couple different places that the X11 includes could be on your system. More than likely you'll find it in /opt/X11/include which will have all the definitions of the headers you'll need.
You could include the full path in your C programs such as:
#include "/opt/X11/include/X11/Xlib.h"
But we want it to look like this #include <X11/Xlib.h>
So you could add this switch to GCC when you compile -I /opt/X11/include
Or go to your .profile or .bashrc or .bash_profile in your home directory and add:
export C_INCLUDE_PATH="$C_INCLUDE_PATH:/opt/X11/include"
/*
Simple Xlib application drawing a box in a window.
*/
From the wiki:
#include<X11/Xlib.h>
#include<stdio.h>
#include<stdlib.h> // prevents error for exit on line 18 when compiling with gcc
int main() {
Display *d;
int s;
Window w;
XEvent e;
/* open connection with the server */
d=XOpenDisplay(NULL);
if(d==NULL) {
printf("Cannot open display\n");
exit(1);
}
s=DefaultScreen(d);
/* create window */
w=XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 100, 100, 1,
BlackPixel(d, s), WhitePixel(d, s));
// Process Window Close Event through event handler so XNextEvent does Not fail
Atom delWindow = XInternAtom( d, "WM_DELETE_WINDOW", 0 );
XSetWMProtocols(d , w, &delWindow, 1);
/* select kind of events we are interested in */
XSelectInput(d, w, ExposureMask | KeyPressMask);
/* map (show) the window */
XMapWindow(d, w);
/* event loop */
while(1) {
XNextEvent(d, &e);
/* draw or redraw the window */
if(e.type==Expose) {
XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10);
}
/* exit on key press */
if(e.type==KeyPress)
break;
// Handle Windows Close Event
if(e.type==ClientMessage)
break;
}
/* destroy our window */
XDestroyWindow(d, w);
/* close connection to server */
XCloseDisplay(d);
return 0;
}
Compile:
gcc -O2 -Wall -o test test.c -L /usr/X11R6/lib -lX11 -lm
Unfortunately the top rated answer doesn't work on new Apple Silicon powered machines due to an ABI mismatch. Basically on ARM64 you can't use the objc_msgSend declaration with variable arguments, you must specify the correct argument types for each call. Here is the version that runs on Apple Silicon:
// based on https://stackoverflow.com/a/59596600/834108
// Minimal Pure C code to create a window in Cocoa
// Adapted to work on ARM64
// $ clang minimal.c -framework Cocoa -o minimal.app
#include <objc/runtime.h>
#include <objc/message.h>
#include <Carbon/Carbon.h>
#define cls objc_getClass
#define sel sel_getUid
#define msg ((id (*)(id, SEL))objc_msgSend)
#define msg_int ((id (*)(id, SEL, int))objc_msgSend)
#define msg_id ((id (*)(id, SEL, id))objc_msgSend)
#define msg_ptr ((id (*)(id, SEL, void*))objc_msgSend)
#define msg_cls ((id (*)(Class, SEL))objc_msgSend)
#define msg_cls_chr ((id (*)(Class, SEL, char*))objc_msgSend)
// poor man's bindings!
typedef enum NSApplicationActivationPolicy {
NSApplicationActivationPolicyRegular = 0,
NSApplicationActivationPolicyAccessory = 1,
NSApplicationActivationPolicyERROR = 2,
} NSApplicationActivationPolicy;
typedef enum NSWindowStyleMask {
NSWindowStyleMaskBorderless = 0,
NSWindowStyleMaskTitled = 1 << 0,
NSWindowStyleMaskClosable = 1 << 1,
NSWindowStyleMaskMiniaturizable = 1 << 2,
NSWindowStyleMaskResizable = 1 << 3,
} NSWindowStyleMask;
typedef enum NSBackingStoreType {
NSBackingStoreBuffered = 2,
} NSBackingStoreType;
int main(int argc, char *argv[])
{
// id app = [NSApplication sharedApplication];
id app = msg_cls(cls("NSApplication"), sel("sharedApplication"));
// [app setActivationPolicy:NSApplicationActivationPolicyRegular];
msg_int(app, sel("setActivationPolicy:"), NSApplicationActivationPolicyRegular);
struct CGRect frameRect = {0, 0, 600, 500};
// id window = [[NSWindow alloc] initWithContentRect:frameRect styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO];
id window = ((id (*)(id, SEL, struct CGRect, int, int, int))objc_msgSend)(
msg_cls(cls("NSWindow"), sel("alloc")),
sel("initWithContentRect:styleMask:backing:defer:"),
frameRect,
NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskResizable,
NSBackingStoreBuffered,
false
);
msg_id(window, sel("setTitle:"), msg_cls_chr(cls("NSString"), sel("stringWithUTF8String:"), "Pure C App"));
// [window makeKeyAndOrderFront:nil];
msg_ptr(window, sel("makeKeyAndOrderFront:"), nil);
// [app activateIgnoringOtherApps:YES];
msg_int(app, sel("activateIgnoringOtherApps:"), true);
msg(app, sel("run"));
}
Pure C cross-platform example: (Windows/macOS/Linux)
https://nappgui.com/en/demo/products.html
About macOS portability in pure C (updated to BigSur and M1 support):
https://nappgui.com/en/start/win_mac_linux.html#h2
I'm creating an application in pure C on Mac OSX. What I want is to create window in which my app will be stored.
Are you looking for a TTY window?
If so does your application need to create the window?
If not then you can simply write your pure C program and execute it from within Terminal - a TTY environment for "pure C".
If you want a double-clickable app you can write an AppleScript which will open Terminal and run your C. Something like:
tell application "Terminal"
do script "ex /tmp/test; exit"
end tell
This opens a Terminal window showing "ex" and when that quits will terminate the shell process (so no further commands can be typed), but it will not close Terminal itself - for that you will have to work harder.
If you do want you application to create the window itself you either need to write your own simple TTY window, you might find some classes you can use, or you might be able to borrow code from an open source terminal app such as iterm.
HTH
I noticed that GetVersionEx() is declared deprecated. Worse yet, for Windows 8.1 (and presumably future releases) the version number is limited by the application manifest.
My goal is to collect analytics on operating systems which the users are running, so I can appropriately target support. I would like a future-proof solution for collecting this data. Updating the manifest won't work because I can only update the manifest for Windows versions which have already been released, not for future versions. The suggested replacement API, the version helper functions, is useless.
How can I collect the actual Windows version number?
To clarify: By "future proofing", I just mean that I want something that has a reasonably good chance of working on the next version of Windows. Nothing is certain, but the docs do say that GetVersionEx() won't work.
MSDN has an example showing how to use the (useless for your scenario) version helper functions, but in the introduction is the following:
To obtain the full version number for the operating system, call the GetFileVersionInfo function on one of the system DLLs, such as Kernel32.dll, then call VerQueryValue to obtain the \StringFileInfo\\ProductVersion subblock of the file version information.
As of right now, neither the GetFileVersionInfo nor VerQueryValue function are deprecated.
Example
This will extract the product version from kernel32.dll and print it to the console:
#pragma comment(lib, "version.lib")
static const wchar_t kernel32[] = L"\\kernel32.dll";
wchar_t *path = NULL;
void *ver = NULL, *block;
UINT n;
BOOL r;
DWORD versz, blocksz;
VS_FIXEDFILEINFO *vinfo;
path = malloc(sizeof(*path) * MAX_PATH);
if (!path)
abort();
n = GetSystemDirectory(path, MAX_PATH);
if (n >= MAX_PATH || n == 0 ||
n > MAX_PATH - sizeof(kernel32) / sizeof(*kernel32))
abort();
memcpy(path + n, kernel32, sizeof(kernel32));
versz = GetFileVersionInfoSize(path, NULL);
if (versz == 0)
abort();
ver = malloc(versz);
if (!ver)
abort();
r = GetFileVersionInfo(path, 0, versz, ver);
if (!r)
abort();
r = VerQueryValue(ver, L"\\", &block, &blocksz);
if (!r || blocksz < sizeof(VS_FIXEDFILEINFO))
abort();
vinfo = (VS_FIXEDFILEINFO *) block;
printf(
"Windows version: %d.%d.%d",
(int) HIWORD(vinfo->dwProductVersionMS),
(int) LOWORD(vinfo->dwProductVersionMS),
(int) HIWORD(vinfo->dwProductVersionLS));
free(path);
free(ver);
Yikes, the currently accepted answer is over-complicated. Here's how to get the version of the current windows (with build numbers) quickly and reliably without requiring manifests and other nonsense tricks. And works on Windows 2000 and newer (i.e. every version of Windows in existence).
Short answer: use RtlGetVersion.
Don't have the Windows Driver Development Kit? Then it's a little less simple than including the header and using the function. Here's how you do it both with and without the WDK.
With WDK, include:
// Required for RtlGetVersion()
#pragma comment(lib, "ntdll.lib")
#include <Ntddk.h>
Without WDK, include:
// Required for RtlGetVersion()
#pragma comment(lib, "ntdll.lib")
// Define the function because we don't have the driver development
// kit headers. We could probably acquire them but it makes development
// onboarding a pain in the ass for new employees.
extern "C" {
typedef LONG NTSTATUS, *PNTSTATUS;
#define STATUS_SUCCESS (0x00000000)
// Windows 2000 and newer
NTSYSAPI NTSTATUS NTAPI RtlGetVersion(PRTL_OSVERSIONINFOEXW lpVersionInformation);
}
Now, simply get the accurate version details:
RTL_OSVERSIONINFOEXW osVers;
osVers.dwOSVersionInfoSize = sizeof(osVers);
// fill the structure with version details
NTSTATUS status = RtlGetVersion(&osVers);
// this should always succeed
assert(status == STATUS_SUCCESS);
The osVers variable now contains the accurate major, minor, and build number. No need to read file versions and no need to dynamically load libraries at runtime.
Please vote this above the other answer so this correct code can be used in applications rather than the rube-goldberg other answer. Thanks.
I’m looking for a way to make red squiggly underlining in a Rich Edit control (I’m using version 4.1 with Msftedit.dll). I’m able to produce squiggly underlining with this code :
CHARFORMAT2 format;
format.cbSize = sizeof(format);
format.dwMask = CFM_UNDERLINETYPE;
format.bUnderlineType = CFU_UNDERLINEWAVE;
SendMessage(hWndEdit,EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
The MSDN documentation doesn’t specify how to change the color of underlines, just the text (with underlines) and the text background. I’ve found some code that says to use the lower nibble for the underline type (CFU_UNDERLINEWAVE) and the upper one for color. So I’ve tried :
format.bUnderlineType = CFU_UNDERLINEWAVE | 0x50;
But that doesn't work.
UPDATE
I've tested this code with version 3.0 (Riched20.dll) and it's working. So the problem lies in 4.1. Was the feature removed or moved elsewhere ?
It's not working in version 6 (the dll used by office 2007) also.
Expanding on DaveCamp's answer, the CHARFORMAT2W structure contained a bReserved1 entry:
typedef struct _charformat2w
{
UINT cbSize;
DWORD dwMask;
DWORD dwEffects;
...
BYTE bReserved1;
} CHARFORMAT2W;
But if you look at the latest (8.0) SDK, the bReserved1 entry has now been given to underline color:
typedef struct _charformat2w
{
UINT cbSize;
DWORD dwMask;
DWORD dwEffects;
...
#if (_RICHEDIT_VER >= 0x0800)
BYTE bUnderlineColor; // Underline color
#endif
} CHARFORMAT2W;
This is defined as a Widows 8 feature (_RICHEDIT_VER >= 0x0800).
The way to set the underline color is as Dave's answer:
CHARFORMAT2 format;
format.cbSize = sizeof(format);
format.dwMask = CFM_UNDERLINETYPE | CFM_UNDERLINE;
format.dwEffects = CFE_UNDERLINE;
format.bUnderlineType = CFU_UNDERLINEWAVE;
format.bUnderlineColor = 0x05;
SendMessage(hWndEdit,EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &format);
The remaining trick is the color BYTE values. They're not yet documented, but there are 16 colors:
UnderlineColor_Black = 0x00;
UnderlineColor_Blue = 0x01;
UnderlineColor_Aqua = 0x02;
UnderlineColor_Lime = 0x03;
UnderlineColor_Fuchsia = 0x04;
UnderlineColor_Red = 0x05;
UnderlineColor_Yellow = 0x06;
UnderlineColor_White = 0x07;
UnderlineColor_Navy = 0x08;
UnderlineColor_Teal = 0x09;
UnderlineColor_Green = 0x0A;
UnderlineColor_Purple = 0x0B;
UnderlineColor_Maroon = 0x0C;
UnderlineColor_Olive = 0x0D;
UnderlineColor_DkGray = 0x0E;
UnderlineColor_LtGray = 0x0F;
Edit: Changed the name of the color from Cyan to Aqua. Fixed spelling of Fuchsia.
Note: Any code released into public domain. No attribution required.
I know this is digging up an old thread, but I've just searched the 'net for several hours looking for an answer to this only to find similar answers everywhere!
This is in fact documented by Microsoft ( http://msdn.microsoft.com/en-gb/library/windows/desktop/bb787883(v=vs.85).aspx ) and as is very easy to do, ONCE you know how! I've just managed to get it working on Windows7 and Windows8 that use the RichEdit50W control from the msftedit.dll.
One thing to note is that the colour indexes are different in Win8. For RED I have to use color 0x06 as opposed to 0x05.
Ok here's what you need to do:
CHARFORMAT2 format;
format.cbSize = sizeof(format);
format.dwMask = CFM_UNDERLINETYPE | CFM_UNDERLINE;
format.dwEffects = CFE_UNDERLINE;
format.bUnderlineType = CFU_UNDERLINEWAVE;
format.bUnderlineColor = 0x05;
SendMessage(hWndEdit,EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &format);
I'm sorry to say this, but if changing the color of the underline is not documented by Microsoft you should not use it. Undocumented featured like this are subject to be removed in later versions, which might have happened here.
Your best bet is to ask Microsoft.