#include <gl/freeglut.h>
void Keyboard(int value){
glutTimerFunc(33,Keyboard,0);
}
int main(int argc, char **argv){
glutTimerFunc(33,Keyboard);
}
Is there any way to pass data from the main function to the keyboard function without having to use global variables? It seems like the function glutTimerFunc only allows functions with the signature (int value) which seems very restrictive.
so is there another way to get the data into another funcion without having them to be global?
Like other people already suggested: Don't use GLUT. GLUT never was meant to be the foundation of serious application. It's a small framework meant for small OpenGL tech demos. The problem you're running into is that C and C++ lack a concept called "closures", or sometimes also called "delegates". Other languages have them and in fact when you use the GLUT bindings in those languages you don't experience the problem.
Since C/C++'s lack of closures is so prominent a small library (that does crazy but genius things internally) has been written, that allows it, to create closures in C. It's called ffcall, unfortunately seems to be unmaintained, but is in use by projects as the GNU Common Lisp and Scheme compilers.
I wrote about using ffcall already in the StackOverflow answers https://stackoverflow.com/a/8375672/524368 and https://stackoverflow.com/a/10207698/524368
You can use a trick: pass a pointer to the object as value, after casting it to int:
i instance;
keyboard((int)&i);
If you need to call the function with the timer, consider the fact that when a function ends all the object in the stack are deallocated. So in this case you should allocate the object with new, and always have a handle to it in the case you need to deallocate it.
It's very tricky, I know. If you can switch to another library do it.
Related
So, this is a bit of an open question. But let's say that I have a large application which globally overrides the various new and delete operators so that they use home-brewed jemalloc-style arenas and custom alignments.
All fine and good, but I have been running into segfault issues because other C++-based DLLs and their dependencies also use the overloaded allocators when they shouldn't (namely LLVM), putting the little custom allocator to its knees (lack of memory and more stresses).
Testing workarounds, I have wrapped (and moved) those global operators into a class, and I made all base classes inherit from it. And well, that works for classes, but not for base types. That's the problem.
Given that C++ doesn't allow useful things like having separate allocators per namespace, or limiting the new operator per executable module, what is the best way of emulating this in base data types, where I can't directly subclass an int?
The obvious way is wrapping them in a custom template, but the problem is performance. Do I have to emulate all the array and indexing operations under a second layer just so that I can malloc from a different place without having to change the rest of the functional code? There's a better way?
P.S.: I have also been thinking about using special global new/delete operators with extra parameters, while leaving the standard ones alone. Thus ensuring that I am (well, my executable module is) the only one calling those global functions. It should be a simple search-and-replace.
Well, quick update. What I did in the end to 'solve' this conundrum is to manually detect if the code that called the overridden global allocators comes from the main executable module and conditionally redirect all the external new / delete calls to their corresponding malloc / free while still using the custom arena allocator for our own internal code.
How? After doing some R&D I found that this could be done by using the _ReturnAddress() built-in on MSVC and __builtin_extract_return_addr(__builtin_return_address(0)) on GCC/Clang; and I can say that it seems to work fine so far in production software.
Now, when some C++ code from our address space wants some memory we can see where it comes from.
But, how do we find out if that address is part of some other module in our process space or our own? We might need to find out both the base and end addresses of the main program, cache them at startup as globals, and check that the return address is within bounds.
All for extremely little overhead. But, our second problem is that retrieving the base address is different in every platform. After some research I found that things were more straightforward than expected:
In Windows/Win32 we can simply do this:
#include <windows.h>
#include <psapi.h>
inline void __initialize_base_address()
{
MODULEINFO minfo;
GetModuleInformation(GetCurrentProcess(), GetModuleHandle(NULL), &minfo, sizeof(minfo));
base_addr = (uintptr_t) minfo.lpBaseOfDll;
base_end = (uintptr_t) minfo.lpBaseOfDll + minfo.SizeOfImage;
}
In Linux there are a thousand ways of doing this, including linker globals and some debuggey (verbose and unreliable) ways of walking the process module table. I was looking at the linker map output and noticed that the _init and _fini functions always seem to wrap the rest of the .text section symbols. Sometimes it's hard to get to the simplest solution that works everywhere:
#include <link.h>
inline void __initialize_base_address()
{
void *handle = dlopen(0, RTLD_NOW);
base_addr = (uintptr_t) dlsym(handle, "_init");
base_end = (uintptr_t) dlsym(handle, "_fini");
dlclose(handle);
}
While in macOS things are even less documented and I had to cobble together my own thing using the Darwin kernel open-source code and tracking down some obscure low-level tools as reference. Keep in mind that _NSGetMachExecuteHeader() is just a wrapper for the internal _mh_execute_header linker global. If you need to do anything about parsing the Mach-O format and its structures then getsect.h is the way to go:
#include <mach-o/getsect.h>
#include <mach-o/ldsyms.h>
#include <crt_externs.h>
inline void __initialize_base_address()
{
size_t size;
void *ptr = getsectiondata(&_mh_execute_header, SEG_TEXT, SECT_TEXT, &size);
base_addr = (uintptr_t) _NSGetMachExecuteHeader();
base_end = (uintptr_t) ptr + size;
}
Another thing to keep in mind is that this some-other-cpp-module-is-using-our-internal-allocator-that-globally-overrides-new-causing-weird-bugs issue seems to be a problem in Linux and maybe macOS, I didn't have this issue in Windows, probably because no conflicting DLLs were loaded in the process, being mostly C API-based. I think, or maybe the platform uses different C++ runtimes for each module.
The main issue I had was caused by Mesa3D, which uses LLVM (pure C++ in and out) for many of their GLSL shader compilers and liked to gobble up big chunks of my small custom-tailored memory arena uninvited.
Rewriting a legacy program that is structurally dependent on these allocators was out of the question due to its sheer size and complexity, so this turned out to be the best way of making things work as expected.
It's only a few lines of optional, sneaky, extra per-platform code.
I'm working on creating a user-level thread library and what I want to do is run a function inside a stub and so I would like to pass the function pointer to the stub function.
Here is my stub function:
void _ut_function_stub(void (*f)(void), int id)
{
(*f)();
DeleteThread(id);
}
This is what the user calls. What I want to do is get pointer of _ut_function_stub to assign to pc and I've tried various different options including casting but the compiler keeps saying "invalid use of void expression".
int CreateThread (void (*f) (void), int weight)
{
... more code
pc = (address_t)(_ut_function_stub(f, tcb->id));
... more code
}
Any help is appreciated. Thanks!
If you're interested in implementing your own user-level-threads library, I'd suggest looking into the (now deprecated) ucontext implementation. Specifically, looking at the definitions for the structs used in ucontext.h will help you see all the stuff you actually need to capture to get a valid snapshot of the thread state.
What you're really trying to capture with the erroneous (address_t) cast in your example is the current continuation. Unfortunately, C doesn't support first-class continuations, so you're going to be stuck doing something much more low-level, like swapping stacks and dumping registers (hence why I pointed you to ucontext as a reference—it's going to be kind of complicated if you really want to get this right).
I have multiplatform game written in C++. In the mac version, even though I do not have any obj-c code, one of the libraries I use seems to be auto-releasing stuff, and I get memory leaks for that, since I did not create a NSAutoreleasePool.
What I want is to be able to create (and destroy) a NSAutoreleasePool without using obj-c code, so I don't need to create a .m file, and change my build scripts just for that. Is that possible? How can that be done?
OBS: Tagged C and C++, because a solution in any of those languages will do.
You can't avoid instantiating the Objective-C runtime—but apparently you've already got one of those.
If you want to interact with the runtime from C, you can us the Objective-C runtime APIs, as documented in Objective-C Runtime Programming Guide and Objective-C Runtime Reference.
The idea is something like this (untested):
#include <objc/runtime.h>
#include <objc/objc-runtime.h>
id allocAndInitAutoreleasePool() {
Class NSAutoreleasePoolClass = objc_getClass("NSAutoreleasePool");
id pool = class_createInstance(NSAutoreleasePoolClass, 0);
return objc_msgSend(pool, "init");
}
void drainAutoreleasePool(id pool) {
(void)objc_msgSend(pool, "drain");
}
If you want to call these functions from another file, of course you'll have to include objc/runtime.h there as well. Or, alternatively, you can cast the id to void* in the return from the allocAndInit function, and take a void* and cast back to id in the drain function. (You could also forward-declare struct objc_object and typedef struct objc_object *id, but I believe that's not actually guaranteed to be the right definition.)
You shouldn't have to pass -lobjc in your link command.
Needless to say, it's probably less work to just make your build scripts handle .m files.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Dynamic source code in C++
is it possible to let the user type in a function and then run that function without using a lot of if's or a huge switch?
It is not possible to execute arbitrary c++ code in your program, since you than need a c++ compiler inside your program. But you could try to embed Python to your program. Boost python makes this relatively easy. The user can than write a python function that is executed and can interact with the classes and functions of your program. You need to make your functions explicitely visible to python.
What ever a user types in will be text, or a string. The only way I know to have it get mapped to a function is to use if/else or switch statements. That or the cringe inducing option of mapping each of your functions to a UI widget.
The end of the story, is it's your code. You have to write, and live with it. Just be careful, your program may be wildly successful, and you may not write code anymore, and then someone else will have to maintain your code. So be nice to the maintenance programmer who may follow you, and write code that isn't too tricky to figure out.
I assume you want something like eval from php.
You can try to play with command design pattern, but I doubt it will be an easy task. Basically you need to write simple C++ interpreter.
What type of function do you mean? A C++ function? If so, then you will have to either (1)interpret it or (2)compile and execute it. Interpretation would be the more likely choice here. I'm not sure if there are libraries out there already to do this but I'd assume there are.
If you don't like mega-if's or huge switches, you may be SoL on any solution for anything ever, but then again there is seldom one perfect way to do things. Consider looking in to various logic structures and algorithms to see how to do something that would normally be the job of a 23-case switch could be done another way. Like I said initially, however, sometimes you really do just need a million nested if's to do what you want to.
No, in C++ this is not possible. C++ is a compiled language. When the program runs, the compiler doesn't need to be accessible, or even installed on the machine that runs the program.
If you want to do this in C++, you need to write your own interpreter that parses whatever the user enters.
Here is my best idea, but it is a tad memory intensive.
First, create a class, lets call it MyFuncPtr to store a union of several different types of pointers to functions and an integer to tell which type it is. Overload the () operator to call the function stored with a variable length argument list. Make sure to include some sort of run-time argument checking.
Finally create a map of strings to MyFuncPtrs. Store your functions in this map along with their names. Then all you need to do is feed the name into the [] command to get a function that can be easily called. Templates could probably be used to aid in the making of MyFuncPtr instances.
This would be the easiest if it were plain C functions and no name mangling is performed on the symbols (use extern "C" { ... })
With some platform-specific code you can get the address of a function by its name. Then you cast the address as a function pointer which you can use to call the function.
On windows you must be using GetProcAddress and dlsym on Posix compliant platforms.
This may be a short & simple question, but I've never found a satisfying answer to it:
What code does the main() function usually consist of in a large C++ project? Would it be an incorrect assumption to think that it is usually just initializing a (wrapping) class object and calling a function inside of it to set things off?
Why is main() not a method in the first place? Is it to preserve backwards-compatibility with C?
In my code, it's basically a constructor call, possibly a method call, and some exception handling. This is the main for own of my projects (headers and comments omitted, and formatting messed up by SO, as usual):
int main( int argc, char * argv[] ) {
int result = 0;
try {
CLIHandler ch( argc, argv );
result = ch.ExecCommand();
}
catch( const Exception & ex ) {
result = ExceptionHandler::HandleMyError( ex );
}
catch( const std::exception & ex ) {
result = ExceptionHandler::HandleOtherError( ex );
}
catch( ... ) {
result = ExceptionHandler::HandleUnknownError();
}
return result;
}
Mine usually do
Command-line parsing
Initialization of top-level objects
Exception handling
entering main 'exec' loop
As I understand it, int main(int argc, char *argv[]) is essentially a convention due to the C heritage. Never struck me as odd, but rather as useful. C++ extends C after all ... (and yes there are fine difference but that wasn't the question here).
Yes, the reason is backward compatibility. main is the only entry point allowed in a C program producing executables, and therefore in a C++ program.
As for what to do in a C++ main, it depends. In general, I used to:
perform global initialization (e.g. of the logging subsystem)
parse command line arguments and define a proper class containing them
allocate an application object, setting it up etc.
run the application object (in my case, an infinite loop method. GUI programming)
do finalization after the object has completed its task.
oh and I forgot the most important part of an application
show the splashscreen
The short answer: it depends. It may well create a few local objects that are needed for the duration of the program, configure them, tell them about each other and call a long running method on one of them.
A program needs an entry point. If main had to be a method on an object, what class type should it be?
With main as a global entry point it can choose what to set up.
My main() function often constructs various top-level objects, giving them references to one another. This helps minimize coupling, keeping the exact relationships between the different top-level objects confined to the main.
Often those top-level objects have distinct life cycles, with init(), stop(), and start() methods. The main() function manages getting the objects into the desired running state, waits for whatever indicates it is time to shut down, and then shutting everything down in a controlled fashion. Again, this helps keep things properly decoupled, and keeps top-level life cycle management in one easily understood place. I see this pattern a lot in reactive systems, especially those with a lot of threads.
You can use a static class member function in place of main with the MSVC++ compiler by choosing the entry point in the project settings, under the advanced linker options.
It really depends on your project as to what you want to place in there... if it is small you may as well put message loops, initialization and shutdown code in there. In larger projects you will have to move these into their own classes/functions or less have a monolithic entry point function.
Not all C++ applications are OOP and either way all code requires some entry point to start from.
When I'm writing OOP code, my main() tends to include an object instantiation, maybe proceeded by some user input. I do it this way because I feel that the 'work' is meant to be done within an object, otherwise the code isn't written in the 'spirit' of OOP.
I usually use main for reading in the command line, initializing global variables, and then calling the appropriate functions/methods.
Really large projects tend not comprise only a single program. Hence there will be several executables each with their own main. In passing, it's quite common for these executables to communicate asynchronously via queues.
Yes each main does tend to be very small, initialising a framework or whatever.
Do you mean why is main() a function rather than a method of class? Well, what class would it be a method of? I think it's mostly C++'s heritage from C, but ... everything got to start somewhere :-)