How To Use SetConsoleCursorPosition Func - c

I just wrote the code for tower of hanoi in c and I wanted to show the solution in graphical mode using characters.
I want to use windows.h and SetConsoleCursorPosition function to move cursor in console.
Could you help me by telling me have does this function works and how to use it?Please give some examples.

Here's an example of how to call the SetConsoleCursorPosition function, taken from cplusplus:
void GoToXY(int column, int line)
{
// Create a COORD structure and fill in its members.
// This specifies the new position of the cursor that we will set.
COORD coord;
coord.X = column;
coord.Y = line;
// Obtain a handle to the console screen buffer.
// (You're just using the standard console, so you can use STD_OUTPUT_HANDLE
// in conjunction with the GetStdHandle() to retrieve the handle.)
// Note that because it is a standard handle, we don't need to close it.
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// Finally, call the SetConsoleCursorPosition function.
if (!SetConsoleCursorPosition(hConsole, coord))
{
// Uh-oh! The function call failed, so you need to handle the error.
// You can call GetLastError() to get a more specific error code.
// ...
}
}
You can also find out how to use Win32 functions by checking the SDK documentation. Googling for the name of the function will usually turn up the appropriate doc page as the first hit.
For SetConsoleCursorPosition, the page is here, and for GetStdHandle, the page is here.

Related

Plotting pixels to the screen using a physical Framebuffer (UEFI/GOP)

I’ve been recently getting into OS development (completely from scratch), and I’m stuck on an issue where plotting pixels to the screen does not seem to work at all.
For reference, I’m using EDK2 for the UEFI utilities and compiling my bootloader using its build system.
I obtain the framebuffer from the GOP handle after setting my wanted mode (which should be 1366x768, BGRA colour format), but writing any value to the framebuffer memory space seems to not translate anything to the screen. Here are the projects (bootloader and OS) for references:
* OS: https://github.com/kernel-dev/kernelOS
* Bootloader: https://github.com/kernel-dev/kernelOSBootloader
Furthermore, here are the relevant snippets of code that should work, but don’t:
* Function declarations: https://github.com/kernel-dev/kernelOS/blob/main/src/Kernel/Graphics/KernGraphics.c
* Calling the function for clearing the screen: https://github.com/kernel-dev/kernelOS/blob/main/src/Kernel/Kernel.c
Solved
The reason why it wasn't working is because I wasn't properly getting the passed down arguments in my kernel.
This is how it looked like:
// Entry point for kernel
VOID
KernMain (
IN EFI_RUNTIME_SERVICES *RT,
IN EFI_KERN_MEMORY_MAP *MemoryMap,
IN ACPI_DIFFERENTIATED_SYSTEM_DESCRIPTOR_TABLE *Dsdt,
IN KERN_FRAMEBUFFER *Framebuffer)
{
ScreenClearTerminal (Framebuffer);
//
// Should never reach here.
// Will be removed later.
//
while (TRUE) {};
}
However, the way I actually pass them down is like this:
//
// Prepare the arguments to be passed down.
//
LoaderBlock->MemoryMap = &MemoryMap;
LoaderBlock->Dsdt = Dsdt;
LoaderBlock->RT = SystemTable->RuntimeServices;
LoaderBlock->Framebuffer = FB;
//
// Exit boot services.
//
/* ... */
//
// Locate the EP function and call it with the arguments.
//
typedef void (__attribute__((ms_abi)) *EntryPointFunction) (LOADER_PARAMS *LP);
EntryPointFunction EntryPointPlaceholder = (EntryPointFunction) (BaseAddress + EntryPoint);
EntryPointPlaceholder (LoaderBlock);
It's contained inside of a struct. So the appropriate way to obtain them would be like this:
/**
A structure used to "contain" all
the parameters to be passed down
to the kernel's EP.
**/
typedef struct {
EFI_RUNTIME_SERVICES *RT; /// Pointer to the runtime services.
EFI_KERN_MEMORY_MAP *MemoryMap; /// Pointer to the EFI_KERN_MEMORY_MAP.
ACPI_DIFFERENTIATED_SYSTEM_DESCRIPTOR_TABLE **Dsdt; /// Pointer to the DSDT pointer.
KERN_FRAMEBUFFER *Framebuffer; /// Pointer to the KERN_FRAMEBUFFER.
} LOADER_PARAMS;
// Entry point for kernel
VOID
KernMain (
LOADER_PARAMS *LP)
{
ScreenClearTerminal (LP->Framebuffer);
//
// Should never reach here.
// Will be removed later.
//
while (TRUE) {};
}
or, alternatively keeping the old method, but alternating the way they're passed down:
//
// Locate the EP function and call it with the arguments.
//
typedef void (__attribute__((ms_abi)) *EntryPointFunction) (
EFI_RUNTIME_SERVICES *RT,
EFI_KERN_MEMORY_MAP *MemoryMap,
ACPI_DIFFERENTIATED_SYSTEM_DESCRIPTOR_TABLE **Dsdt,
KERN_FRAMEBUFFER *Framebuffer
);
EntryPointFunction EntryPointPlaceholder = (EntryPointFunction) (BaseAddress + EntryPoint);
EntryPointPlaceholder (
SystemTable->RuntimeServices,
&MemoryMap,
Dsdt,
FB);
Completely my bad lol.
Thank you to #user123 and #Dave S for helping me.

How to do automatic OpenGL error checking using GLEW?

I was recently trying to implement automatic error checking after each OpenGL function call. I considered wrapping each OpenGL function in a caller like this:
CheckForErrors(glCreateBuffers(1, &VBO));
But I saw that GLEW already uses its own function wrapper:
#define GLEW_GET_FUN(x) x
So I decided to edit it instead of writting my own function wrapper:
#ifndef GLEW_GET_FUN
#ifdef DEBUG
#define GLEW_GET_FUN(x) while (glGetError() != GL_NO_ERROR);\
x; {\
GLenum error = glGetError();\
if (error != GL_NO_ERROR) {\
printf("[GLEW]: OpenGL error(s) occured while calling %s in %s (line %s):", #x, __FILE__, __LINE__);\
do printf(" %d", error); while (error = glGetError());\
printf("\n");\
__debugbreak();\
}
#else
#define GLEW_GET_FUN(x) x
#endif
#endif
Unfortunately, this doesn't compile. For example this function call:
GLuint vertexShaderID = glCreateShader(GL_VERTEX_SHADER);
Gets changed to this by the preprocessor:
GLuint vertexShaderID = while (glGetError() != GL_NO_ERROR); __glewCreateShader; { GLenum error = glGetError(); if (error != 0) { printf("[GLEW]: OpenGL error(s) occured while calling %s in %s (line %s):", "__glewCreateShader", "main.cpp", 51); do printf(" %d", error); while (error = glGetError()); printf("\n"); __debugbreak(); }(GL_VERTEX_SHADER);
There are 2 problems here:
The statement starts with a while loop, so it cannot return the value.
The parentheses with function parameters are placed after the whole thing and not right after the function call.
I don't know how to overcome those problems and I will appreciate help.
Notes
I am aware of the glDebugMessageCallback() function, but it is only availble in OpenGL 4.3+ which is a rather new and partially insupported yet version.
I cannot remove the while loop at the beginning, because I have to clear all errors before calling the function (unless there is a diffrent way to do this).
I am trying to do something like this, but without using a separate function wrapper.
I don't know how to overcome those problems
You can't. What you want to do is simply not viable in the way you want to do it. You cannot turn an expression (which is what a function call is) into a statement (or rather, a series of statements) and have that work everywhere. It will only work in circumstances where the expression is used as a statement.
If you are unwilling to just regularly insert error checking code into your application, and are unable to use the modern debug messaging API, then the standard solution is to use an external tool to find and report errors. RenderDoc can detect OpenGL errors, for example. It allows you to log every OpenGL call and can report errors anytime they occur.
As Nicol Bolas said, it is impossible to do it the way I originally wanted, but I will describe why this is the case and what can be done instead.
The Problem
GLEW wraps only the name of the function with GLEW_GET_FUN(), so function parameters will always be placed after the end of the define as they are not included in it:
//In code:
glGenBuffers(1, &VBO);
//After preprocessing:
{stuff generated by GLEW_GET_FUN}(1, &VBO);
Preprocessing isn't very inteligent so it will just put the function parameters at the end.
Other Solutions
As described in the question, one could use glDebugMessageCallback() if availble.
Wrap each function with a custom wrapper. Not automatic at all, but if someone is interested here is a great tutorial on how to make one.

C example of using AntLR

I am wondering where I can find C tutorial/example of using AntLR. All I found is using Java language.
I am focusing to find a main function which use the parser and lexer generated by AntLR.
Take a look at this document
And here is an example:
// Example of a grammar for parsing C sources,
// Adapted from Java equivalent example, by Terence Parr
// Author: Jim Idle - April 2007
// Permission is granted to use this example code in any way you want, so long as
// all the original authors are cited.
//
// set ts=4,sw=4
// Tab size is 4 chars, indent is 4 chars
// Notes: Although all the examples provided are configured to be built
// by Visual Studio 2005, based on the custom build rules
// provided in $(ANTLRSRC)/code/antlr/main/runtime/C/vs2005/rulefiles/antlr3.rules
// there is no reason that this MUST be the case. Provided that you know how
// to run the antlr tool, then just compile the resulting .c files and this
// file together, using say gcc or whatever: gcc *.c -I. -o XXX
// The C code is generic and will compile and run on all platforms (please
// report any warnings or errors to the antlr-interest newsgroup (see www.antlr.org)
// so that they may be corrected for any platform that I have not specifically tested.
//
// The project settings such as additional library paths and include paths have been set
// relative to the place where this source code sits on the ANTLR perforce system. You
// may well need to change the settings to locate the includes and the lib files. UNIX
// people need -L path/to/antlr/libs -lantlr3c (release mode) or -lantlr3cd (debug)
//
// Jim Idle (jimi cut-this at idle ws)
//
// You may adopt your own practices by all means, but in general it is best
// to create a single include for your project, that will include the ANTLR3 C
// runtime header files, the generated header files (all of which are safe to include
// multiple times) and your own project related header files. Use <> to include and
// -I on the compile line (which vs2005 now handles, where vs2003 did not).
//
#include <C.h>
// Main entry point for this example
//
int ANTLR3_CDECL
main (int argc, char *argv[])
{
// Now we declare the ANTLR related local variables we need.
// Note that unless you are convinced you will never need thread safe
// versions for your project, then you should always create such things
// as instance variables for each invocation.
// -------------------
// Name of the input file. Note that we always use the abstract type pANTLR3_UINT8
// for ASCII/8 bit strings - the runtime library guarantees that this will be
// good on all platforms. This is a general rule - always use the ANTLR3 supplied
// typedefs for pointers/types/etc.
//
pANTLR3_UINT8 fName;
// The ANTLR3 character input stream, which abstracts the input source such that
// it is easy to provide input from different sources such as files, or
// memory strings.
//
// For an ASCII/latin-1 memory string use:
// input = antlr3NewAsciiStringInPlaceStream (stringtouse, (ANTLR3_UINT64) length, NULL);
//
// For a UCS2 (16 bit) memory string use:
// input = antlr3NewUCS2StringInPlaceStream (stringtouse, (ANTLR3_UINT64) length, NULL);
//
// For input from a file, see code below
//
// Note that this is essentially a pointer to a structure containing pointers to functions.
// You can create your own input stream type (copy one of the existing ones) and override any
// individual function by installing your own pointer after you have created the standard
// version.
//
pANTLR3_INPUT_STREAM input;
// The lexer is of course generated by ANTLR, and so the lexer type is not upper case.
// The lexer is supplied with a pANTLR3_INPUT_STREAM from whence it consumes its
// input and generates a token stream as output.
//
pCLexer lxr;
// The token stream is produced by the ANTLR3 generated lexer. Again it is a structure based
// API/Object, which you can customise and override methods of as you wish. a Token stream is
// supplied to the generated parser, and you can write your own token stream and pass this in
// if you wish.
//
pANTLR3_COMMON_TOKEN_STREAM tstream;
// The C parser is also generated by ANTLR and accepts a token stream as explained
// above. The token stream can be any source in fact, so long as it implements the
// ANTLR3_TOKEN_SOURCE interface. In this case the parser does not return anything
// but it can of course specify any kind of return type from the rule you invoke
// when calling it.
//
pCParser psr;
// Create the input stream based upon the argument supplied to us on the command line
// for this example, the input will always default to ./input if there is no explicit
// argument.
//
if (argc < 2 || argv[1] == NULL)
{
fName =(pANTLR3_UINT8)"./input"; // Note in VS2005 debug, working directory must be configured
}
else
{
fName = (pANTLR3_UINT8)argv[1];
}
// Create the input stream using the supplied file name
// (Use antlr3AsciiFileStreamNew for UCS2/16bit input).
//
input = antlr3AsciiFileStreamNew(fName);
// The input will be created successfully, providing that there is enough
// memory and the file exists etc
//
if ( input == NULL)
{
fprintf(stderr, "Failed to open file %s\n", (char *)fName);
exit(1);
}
// Our input stream is now open and all set to go, so we can create a new instance of our
// lexer and set the lexer input to our input stream:
// (file | memory | ?) --> inputstream -> lexer --> tokenstream --> parser ( --> treeparser )?
//
lxr = CLexerNew(input); // CLexerNew is generated by ANTLR
// Need to check for errors
//
if ( lxr == NULL )
{
fprintf(stderr, "Unable to create the lexer due to malloc() failure1\n");
exit(1);
}
// Our lexer is in place, so we can create the token stream from it
// NB: Nothing happens yet other than the file has been read. We are just
// connecting all these things together and they will be invoked when we
// call the parser rule. ANTLR3_SIZE_HINT can be left at the default usually
// unless you have a very large token stream/input. Each generated lexer
// provides a token source interface, which is the second argument to the
// token stream creator.
// Note that even if you implement your own token structure, it will always
// contain a standard common token within it and this is the pointer that
// you pass around to everything else. A common token as a pointer within
// it that should point to your own outer token structure.
//
tstream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lxr));
if (tstream == NULL)
{
fprintf(stderr, "Out of memory trying to allocate token stream\n");
exit(1);
}
// Finally, now that we have our lexer constructed, we can create the parser
//
psr = CParserNew(tstream); // CParserNew is generated by ANTLR3
if (psr == NULL)
{
fprintf(stderr, "Out of memory trying to allocate parser\n");
exit(ANTLR3_ERR_NOMEM);
}
// We are all ready to go. Though that looked complicated at first glance,
// I am sure, you will see that in fact most of the code above is dealing
// with errors and there isn't really that much to do (isn't this always the
// case in C? ;-).
//
// So, we now invoke the parser. All elements of ANTLR3 generated C components
// as well as the ANTLR C runtime library itself are pseudo objects. This means
// that they are represented as pointers to structures, which contain any
// instance data they need, and a set of pointers to other interfaces or
// 'methods'. Note that in general, these few pointers we have created here are
// the only things you will ever explicitly free() as everything else is created
// via factories, that allocated memory efficiently and free() everything they use
// automatically when you close the parser/lexer/etc.
//
// Note that this means only that the methods are always called via the object
// pointer and the first argument to any method, is a pointer to the structure itself.
// It also has the side advantage, if you are using an IDE such as VS2005 that can do it
// that when you type ->, you will see a list of tall the methods the object supports.
//
psr->translation_unit(psr);
// We did not return anything from this parser rule, so we can finish. It only remains
// to close down our open objects, in the reverse order we created them
//
psr ->free (psr); psr = NULL;
tstream ->free (tstream); tstream = NULL;
lxr ->free (lxr); lxr = NULL;
input ->close (input); input = NULL;
return 0;
}
contrapunctus.net/blog/2012/antlr-c a simple google would suffice. Note however, the example is C++ I don't think ANTLR supports PURE C – Aniket Jan 1 at 1:56

ncurses write to window not displayed

I've got one function do_refresh which should draw some character in a window like this:
void do_refresh(WINDOW *w_game, int *xPos, int *yPos, char vector[], snake *snake){
mvwaddch(w_game, (*yPos), (*xPos), snake->headsym);// mv to new pos and place char
wrefresh(w_game);
}
The window w_game has also a panel pendant which lies on top of all other panels.
Before that function gets called, I let the user do non blocking input with getch() and timeout(0):
fflush(stdin);
key = getch();
if(key != ERR){ ...
only the first time I call do_refresh, the char gets drawn to the window, later nothing changes though xPos & yPos as well as all other parameters to mvwaddch are valid and change over the time.
Doing a redrawwin on the window causes a segfault, using wgetch(w_game) instead of getch() returns no input.
I would be very grateful if someone could at least link to a decent documentation what has to be considered when using wgetch instead and what it does different.
UPDATE
I found the solution to the problem, The function which sets up the panel stuff modifies the address of the windows!, you have to return the (new) destination of the pointer to main and reset it there like this:
...setup_panels(...){
return w_game; // my window
}
int main(...){
WINDOW *w_game;
[...]
w_game = setup_panels(...);
}

SetProp problem

Can anybody tell me why the following code doesn't work? I don't get any compiler errors.
short value = 10;
SetProp(hCtl, "value", (short*) value);
The third parameter is typed as a HANDLE, so IMO to meet the explicit contract of the function you should save the property as a HANDLE by allocating a HGLOBAL memory block. However, as noted in the comments below, MSDN states that any value can be specified, and indeed when I try it on Windows 7 using...
SetProp(hWnd, _T("TestProp"), (HANDLE)(10)); // or (HANDLE)(short*)(10)
...
(short)GetProp(hWnd, _T("TestProp"));
... I get back 10 from GetProp. I suspect somewhere between your SetProp and GetProp one of two things happens: (1) the value of hWnd is different -- you're checking a different window or (2) a timing issue -- the property hasn't been set yet or had been removed.
If you wanted to use an HGLOBAL instead to follow the specific types of the function signature, you can follow this example in MSDN.
Even though a HANDLE is just a pointer, it's a specific data type that is allocated by calls into the Windows API. Lots of things have handles: icons, cursors, files, ... Unless the documentation explicitly states otherwise, to use a blob of data such as a short when the function calls for a HANDLE, you need a memory handle (an HGLOBAL).
The sample code linked above copies data as a string, but you can instead set it as another data type:
// TODO: Add error handling
hMem = GlobalAlloc(GPTR, sizeof(short));
lpMem = GlobalLock(hMem);
if (lpMem != NULL)
{
*((short*)lpMem) = 10;
GlobalUnlock(hMem);
}
To read it back, when you GetProp to get the HANDLE you must lock it to read the memory:
// TODO: Add error handling
short val;
hMem = (HGLOBAL)GetProp(hwnd, ...);
if (hMem)
{
lpMem = GlobalLock(hMem);
if (lpMem)
{
val = *((short*)lpMem);
}
}
I would create the short on the heap, so that it continues to exist, or perhaps make it global, which is perhaps what you did. Also the cast for the short address needs to be void *, or HANDLE.

Resources