question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
862,068
868,461
How do I dynamically change the text of a CMFCRibbonLabel
My CMDIFrameWndEx derived main frame window uses a CMFCRibbonStatusBar to which I add a CMFCRibbonLabel. I'd like to change the text of this label at runtime: m_pLabel->SetText(description); m_pLabel->Redraw(); It only updates the text but not the rectangle in which to draw it. So if the original text was too short, the new string won't be visible completely. How do I get it to resize correctly?
Answering my own question again... I worked around the issue by adding and removing the label instead of trying to change the text. Code for adding the label: CMFCRibbonLabel* pLabel = new CMFCRibbonLabel(description); pLabel->SetID(ID_MYLABEL); // ID is 0 by default m_wndStatusBar.AddDynamicElement(pLabel); m_wndStatusBar.RecalcLayout(); m_wndStatusBar.RedrawWindow(); Note that I'm setting an ID so I can later call CMFCRibbonStatusBar::RemoveElement() with that ID. The calls to RecalcLayout() and RedrawWindow() are needed to make the changes visible. Code for removing the label: if(m_wndStatusBar.RemoveElement(ID_MYLABEL)) { m_wndStatusBar.RecalcLayout(); m_wndStatusBar.RedrawWindow(); }
862,093
862,246
Object delete itself from container
So I have a container(any kind, probably std::map or std::vector) which contains objects of a class with some network thing running in a thread that checks if it is still connected (the thread is defined inside that class and launches when constructed). Is there any way I can make the object delete itself from the container when its disconnected or should I move the thread outside the object and use that class just to store data?
I would have am unload queue. When a thread notices that the connection is down it registers the object (and continer) with the unload queue tides everything up as much as possible then the thred terminates. A separate thread is then inside the unload queue. Its sole purpose is to monitor the queue. When it sees a new object on the queue, remove it from the container and then destroy it (syncing with the objects thread as required).
862,256
862,647
How can I end a Lua thread cleanly?
My situation is that I'm using the Lua (C) API to execute a script held in a string. I would like the user to be able to terminate the execution of the script (this is essential if the script contains an infinite loop), how can I do this? lua_State *Lua = lua_open(); char * code; // Initialisation code luaL_dostring(L, code);
You can use a hook to callback to C every time lua executes a line of the script. In this hook function you can check if the user wanted to quit, and call lua_error if they did. static bool ms_quit = false; void IWantToQuit() { ms_quit = true; } void LineHookFunc(lua_State *L, lua_Debug *ar) { if(ar.event == LUA_HOOKLINE) if(ms_quit == true) luaL_error(L, "Too Many Lines Error"); } //... lua_State *Lua = lua_open(); char * code; // Initialisation code lua_sethook(Lua, &LineHookFunc, LUA_MASKLINE, 0); luaL_dostring(L, code);
862,699
862,758
C++ SpellChecker Library
Can anybody recommend a good (ideally open source) C++ spell checker library. We are currenly using Talo, which isn't very good, so we are looking to change. One which includes a grammar checker would also be good. Thanks
I have heard good things about hunspell. I have used and integrated aspell, which has some nice features and some which I did not like.
862,846
862,903
Why in this example using floats makes me go 2x slower than with doubles?
I've been doing some profiling lately and I've encountered one case which is driving me nuts. The following is a piece of unsafe C# code which basically copies a source sample buffer to a target buffer with a different sample rate. As it is now, it takes up ~0.17% of the total processing time per frame. What I don't get is that if I use floats instead of doubles, the processing time will raise to 0.38%. Could someone please explain what's going on here? Fast version (~17%) double rateIncr = ... double readOffset = ... double offsetIncr = ... float v = ... // volume // Source and target buffers. float* src = ... float* tgt = ... for( var c = 0; c < chunkCount; ++c) { for( var s = 0; s < chunkSampleSize; ++s ) { // Source sample var iReadOffset = (int)readOffset; // Interpolate factor var k = (float)readOffset - iReadOffset; // Linearly interpolate 2 contiguous samples and write result to target. *tgt++ += (src[ iReadOffset ] * (1f - k) + src[ iReadOffset + 1 ] * k) * v; // Increment source offset. readOffset += offsetIncr; } // Increment sample rate offsetIncr += rateIncr; } Slow version (~38%) float rateIncr = ... float readOffset = ... float offsetIncr = ... float v = ... // volume // Source and target buffers. float* src = ... float* tgt = ... for( var c = 0; c < chunkCount; ++c) { for( var s = 0; s < chunkSampleSize; ++s ) { var iReadOffset = (int)readOffset; // The cast to float is removed var k = readOffset - iReadOffset; *tgt++ += (src[ iReadOffset ] * (1f - k) + src[ iReadOffset + 1 ] * k) * v; readOffset += offsetIncr; } offsetIncr += rateIncr; } Odd version(~22%) float rateIncr = ... float readOffset = ... float offsetIncr = ... float v = ... // volume // Source and target buffers. float* src = ... float* tgt = ... for( var c = 0; c < chunkCount; ++c) { for( var s = 0; s < chunkSampleSize; ++s ) { var iReadOffset = (int)readOffset; var k = readOffset - iReadOffset; // By just placing this test it goes down from 38% to 22%, // and the condition is NEVER met. if( (k != 0) && Math.Abs( k ) < 1e-38 ) { Console.WriteLine( "Denormalized float?" ); } *tgt++ += (src[ iReadOffset ] * (1f - k) + src[ iReadOffset + 1 ] * k) * v; readOffset += offsetIncr; } offsetIncr += rateIncr; } All I know by now is that I know nothing
Are you running this on a 64 or 32 bit processor? My experience has been that in some edge cases there are optimisations the CPU can do with low level functionality like this if the size of your object matches the size of the registers (even though you may assume that two floats would fit neatly in a 64 bit register you may still lose the optimisation benefit). You may find the situation reversed if you run it on a 32 bit system... A quick search and the best I can do for a cite on this is a couple of posts to C++ game development forums (it was during my one year in game dev that I noticed this myself, but then that was the only time I was profiling to this level). This post has some interesting disassembly results from a C++ method that may be applicable at a very low level. Another thought: This article from MSDN goes into a lot of the internal specifics of using floats in .NET primarily to address the problematic issue of float comparison. There is one interesting paragraph from it which sums up the CLR spec for handling float values: This spec clearly had in mind the x87 FPU. The spec is basically saying that a CLR implementation is allowed to use an internal representation (in our case, the x87 80 bit representation) as long as there is no explicit storage to a coerced location (a class or valuet type field), that forces narrowing. Also, at any point, the IL stream may have conv.r4 and conv.r8 instructions, which will force the narrowing to happen. So your floats may not actually be floats when operations are being performed against them, instead they could be 80-bit numbers on a x87 FPU or anything else that the compiler may think is an optimisation or required for calculation accuracy. Without looking in the IL you won't know for sure, but there could be many costly casts when you are working with floats that don't hit when you are using doubles. It's a shame that you can't define the required precision for floating point operations in C# as you can through the fp switches in C++, since that would stop the compiler from putting everything into a larger container before operating on it.
862,858
863,761
What other useful casts can be used in C++
C++ comes with four built-in casts. static_cast dynamic_cast const_cast reinterpret_cast Not to meantion the frowned upon C (style*)cast. Additionally boost supplies a lexical_cast, are there any other useful casts that you use or would like to exist?
My favorite and most loved cast is implicit_cast. It only succeeds if the types can be implicitly converted. Useful for conversion from some type into void* or from some derived class into a base (if you want to select a specific instance of an overloaded function or constructor) or to safely add const-qualifications and any other scenario where you really just need implicit conversions to happen and even static_cast is too powerful. Also read How does C++ pick which overload to call. boost/implicit_cast.hpp. You can add this to your code collection too, if you want template<typename T> struct identity { typedef T type; }; template<typename Dst> Dst implicit_cast(typename identity<Dst>::type t) { return t; }
862,934
863,061
Count the network interfaces with WSAIoctl function (WIN32 API)
I'm trying to list available interfaces using the WSAIoctl function. I have to pass in a buffer to hold the complete list. I want to get a count of the interfaces before I allocate memory to hold the interface details but if I pass in a NULL pointer the call just fails (I dont get a valid count returned). Any way to get this count befor I have to allocate memory? Background is that I am starting a load of processes/threads on on Windows machine which all connect to a single server. I want the server to see these individual connections as coming from different IP addresses and I have added a load of aliases to the test machine to allow for this (lots). The WSAIoct does correctly find all the ones I added. Cheers...
From the msdn documentation for WSAIoctl: Note: If the output buffer is not large enough to contain the address list, SOCKET_ERROR is returned as the result of this IOCTL and WSAGetLastError returns WSAEFAULT. The required size, in bytes, for the output buffer is returned in the lpcbBytesReturned parameter in this case. Note the WSAEFAULT error code is also returned if the lpvInBuffer, lpvOutBuffer, or lpcbBytesReturned parameter is not completely contained in a valid part of the user address space. So you have to call the WSAIoctl function twice. The first time with an arbitrary buffer and then check for the error codes mentioned in the documentation. Then use the the size returned in lpcbBytesReturned to allocate the buffer and call the WSAIoctl function a second time.
863,240
863,281
Cross-Platform Objective-C / C++ Development
I work in a team of developers, one of us works specifically under Windows, and I work primarily in Mac OS X. We're wanting to develop C-based applications either in C++ or Objective-C however I'm not really knowledgeable in how to go about a cross-platform development project. Is it viable to work in C++ using Mac OS X? Obviously they're geared towards Objective-C but is there just as much support for C++. What about cross-platform development in these languages? I'd use something like boost and some kind of UI library. Has anyone got any experience in developing for multiple platforms yet allow applications to run natively without the need for a VM? EDIT: There's a lot of answers I want to mark as correct now. It seems like Qt is the way to go and develop it in C++. Chances are this will be for *nix, OS X and Windows so that would be the best option for us personally. If I can avoid writing Objective-C so the team sticks to C++ then all the better. If I have to write the GUI in Objective-C and mix and match then that's not too much bother either.
You could look at Qt. I've used it successfully on Windows, Linux and Mac OSX projects.
863,523
863,700
Does the OS (POSIX) flush a memory-mapped file if the process is SIGKILLed?
If a process is killed with SIGKILL, will the changes it has made to a memory-mapped file be flushed to disk? I assume that if the OS ensures a memory-mapped file is flushed to disk when the process is killed via SIGKILL, then it will also do so with other terminating signals (SIGABRT, SIGSEGV, etc...).
It will depend on whether the memory-mapped file is opened with modifications private (MAP_PRIVATE) or not (MAP_SHARED). If private, then no; the modifications will not be written back to disk. If shared, the kernel buffer pool contains the modified buffers, and these will be written to disk in due course - regardless of the cause of death.
863,575
863,616
Using nibbles (4 bits variables) in windows C/C++
I'm programming network headers and a lot of protocols use 4 bits fields. Is there a convenient type I can use to represent this information? The smallest type I've found is a BYTE. I must then use a lot of binary operations to reference only a few bits inside that variable.
Since the memory is byte-addressed, you can't address any unit smaller than a single byte. However, you can build the struct you want to send over the network and use bit fields like this: struct A { unsigned int nibble1 : 4; unsigned int nibble2 : 4; };
863,991
864,073
Using C++ to edit the registry
I have a limited c++ background and I would like to edit the registry. For example, I want to grab the value of HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\NoDriveTypeAutoRun and check to see if 0x20 is in it, and then if it is, subtract 0x20 from it's value and write it back (and kill and restart explorer.exe but I can figure that out on my own). How would you do it?
Open the registry : RegOpenKeyEx Query the value : RegQueryValueEx /* do something with value*/ Set the value back : RegSetValueEx close the registry : RegCloseKey
864,124
864,145
How do I create const arrays and calculated const values in C++ class?
I'm running into some compiler errors I don't understand. I'm pretty sure I'm doing something very wrong here but I don't know what. I would like all the world constants to be defined as belonging to the class. Notes: I'm only using classes as structs with attached members. I'm not following strict Object-Orriented Design on purpose. Please do not comment the public variables. I'm not concerned very much about the compiler inlining stuff. I'm using this structure because it's easy for me to use. (If it worked) class Board{ public: enum PhysicsResult{ BOUNCE, OUT_OF_BOUNDS_TOP, OUT_OF_BOUNDS_BOTTOM, CONTINUE }; //World constants const static float Height = 500; const static float Width = 300; //ERROR: 'Board::Width' cannot appear in a constant-expression. const static float PaddleWidth = Width/15; const static float BallRadius = 5; const static float BounceDistance = 1.5; //World Objects Ball ball; Paddle paddle1; Paddle paddle2; /* 1---2 | | 0---3 */ //ERROR: a brace-enclosed initalizer is not allowed here before '{' token //ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[4]' const static Pair corners[4] = {Pair(0, 0), Pair(0, Height), Pair(Width, Height), Pair(Width, 0)}; //ERROR: a brace-enclosed initalizer is not allowed here before '{' token //ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[2]' const static Pair left_wall[2] = {corners[0], corners[1]}; //ERROR: a brace-enclosed initalizer is not allowed here before '{' token //ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[2]' const static Pair right_wall[2] = {corners[3], corners[2]}; //ERROR: a brace-enclosed initalizer is not allowed here before '{' token //ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[2]' const static Pair top_wall[2] = {corners[1], corners[2]}; //ERROR: a brace-enclosed initalizer is not allowed here before '{' token //ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[2]' const static Pair bottom_wall[2] = {corners[0], corners[3]}; If it is possible to do this, what is the proper syntax for doing this? If this is not possible, what alternative should I use?
Defining the static consts outside of the body of the class compiles and executes with gcc. #include <iostream> using namespace std; struct Pair { int a; int b; Pair(int x, int y) : a(x),b(y) {}}; struct F { static const float blah = 200.0; static const Pair corners[4]; }; // square boards are so ordinary const Pair F::corners[4] = { Pair(0,0), Pair(0,1), Pair(2,0), Pair(2,2) }; const float F::blah ; int main(int, char **) { cout << F::corners[0].a << endl ; cout << F::blah << endl; return 0; } I cannot overemphasize the importance of ebo's comment about order of initialization.
864,204
864,223
What happens to memory that is not freed after end of program?
Duplicate: What REALLY happens when you don’t free after malloc? Let's say, for example: int main() { char* test = new char[50000]; return 0; } What happens to the allocated memory after the program had finished? Does it get freed for other applications immediately? Or perhaps after some time? Or maybe it's lost to the system forever? Or does it get swapped to the disk never to return to RAM? Or maybe something completely different? I would like to know what happens on the major 3 OS's: Windows (XP and up, if there are any differences), Linux, Mac OS X.
See: What REALLY happens when you don't free after malloc?
864,250
864,263
Converting Double to String in C++
I am having some issues trying to convert a double to C++ string. Here is my code std::string doubleToString(double val) { std::ostringstream out; out << val; return out.str(); } The problem I have is if a double is being passed in as '10000000'. Then the string value being returned is 1e+007 How can i get the string value as "10000000"
#include <iomanip> using namespace std; // ... out << fixed << val; // ... You might also consider using setprecision to set the number of decimal digits: out << fixed << setprecision(2) << val;
864,394
864,401
Why isn't my change to the registry persisting in C++?
I'm attempting to edit the registry with C++ and this is my first time trying to do so, and I'm failing. I'm not getting any error code, everything says it completed successfully, but it doesn't actually change the registry key. Here is the code I am using: HKEY hkey; DWORD dwDisposition, dwType, dwSize; int autorun = 0x00; int CD_AUTORUN_DISABLED = 0x20; long errorCode; errorCode = RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"), 0, KEY_ALL_ACCESS, &hkey); if(errorCode == ERROR_SUCCESS) { dwType = REG_DWORD; dwSize = sizeof(dwType); errorCode = RegQueryValueEx(hkey, TEXT("NoDriveTypeAutoRun"), NULL, &dwType, (PBYTE)&autorun, &dwSize); cout << "Autorun value: " << autorun << endl; if((autorun & CD_AUTORUN_DISABLED) == 0x20){ int newAutorun = (autorun - CD_AUTORUN_DISABLED); cout << "New value: " << newAutorun << endl; errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) &autorun, dwSize); if(errorCode == ERROR_SUCCESS){ errorCode = RegCloseKey(hkey); if(errorCode == ERROR_SUCCESS){ cout << "Value changed." << endl; } }else{ cout << "Value change failed, error code: " << errorCode << endl; } }else{ cout << "Keep current value." << endl; } }else{ if(errorCode == ERROR_ACCESS_DENIED){ cout << "Access denied." << endl; }else{ cout << "Error! " << errorCode << " : " << ERROR_SUCCESS << endl; } } What am I doing wrong?
You appear to be setting the registry key to the same value that you read it. int newAutorun = (autorun - CD_AUTORUN_DISABLED); cout << "New value: " << newAutorun << endl; errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) **&autorun**, dwSize); Should be int newAutorun = (autorun - CD_AUTORUN_DISABLED); cout << "New value: " << newAutorun << endl; errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) &newAutorun, dwSize);
864,858
899,710
Managed C++ - Importing different DLLs based on configuration file
I am currently writing an application that will serve a similar purpose for multiple clients, but requires adaptations to how it will handle the data it is feed. In essence it will serve the same purpose, but hand out data totally differently. So I decided to prodeed like this: -Make common engine library that will hold the common functionalities of all ways and present the default interface ensuring that the different engines will respond the same way. -Write a specific engine for each way of functioning....each one compiles into its own .dll. So my project will end up with a bunch of libraries with some looking like this: project_engine_base.dll project_engine_way1.dll project_engine_way2.dll Now in the configuration file that we use for the user preferences there will an engine section so that we may decide which engine to use: [ENGINE] Way1 So somewhere in the code we will want to do: If (this->M_ENGINE == "Way1") //load dll for way1 Else If (this->M_ENGINE == "Way2") //load dll for way2 Else //no engines selected...tell user to modify settings and restart application The question is...How will I import my dll(s) this way? Is it even possible? If not can I get some suggestions on how to achieve a similar way of functioning? I am aware I could just import all of the dlls right at the start and just choose which engine to use, but the idea was that I didn't want to import too many engines for nothing and waste resources and we didn't want to have to ship all of those dlls to our customers. One customer will use one engine another will use a different one. Some of our customer will use more than one possibly hence the reason why I wanted to externalize this and allow our users to use a configuration file for engine switching. Any ideas? EDIT: Just realized that even though each of my engine would present the same interface if they are loaded dynamically at runtime and not all referenced in the project, my project would not compile. So I don't have a choice but to include them all in my project don't I? That also means they all have to be shipped to my customers. The settings in the configuration would only dictate with class I would use to initialize my engine member. OR I could have each of these engines be compiled to the same name. Only import one dll in my main project and that particular engine would be used all the time. That would render my customers unable to use our application for multiple clients of their own. Unless they were willing to manually switch dlls. Yuck Any suggestions? EDIT #2: At this point seeing my options, I could also juste make one big dll containing the base engine as well as all the child ones and my configuration to let the user chose. Instead of referencing multiple dlls and shipping them all. Just have one huge one and ship/reference that one only. I am not too fond of this either as it means shipping one big dll to all of my customers instead of just one or two small ones that suit there needs. This is still the best solution that I've come up with though. I am still looking for better suggestions or answers to my original question. Thanks.
The solution I came to is the following: Engine_Base^ engine_for_app; Assembly^ SampleAssembly; Type^ engineType; if (this->M_ENGINE == "A") { SampleAssembly = Assembly::LoadFrom("path\\Engine_A.dll"); engineType = SampleAssembly->GetType("Engine_A"); engine_for_app = static_cast<Engine_Base^>(Activator::CreateInstance(engineType, param1, param2)); } else { SampleAssembly = Assembly::LoadFrom("path\\Engine_B.dll"); engineType = SampleAssembly->GetType("Engine_B"); engine_for_app = static_cast<Engine_Base^>(Activator::CreateInstance(engineType, param1, param2, param3, param4)); } I used the answer from Daniel and the comments that were made on his answer. After some extra research I came across the LoadFrom method.
865,000
865,287
Collision-Detection methods in C++
I am new to c++ and I have been practicing collision in a small game program that does nothing and I just can't get the collision right So I use images loaded into variables background = oslLoadImageFile("background.png", OSL_IN_RAM, OSL_PF_5551); sprite = oslLoadImageFile("sprite.png", OSL_IN_RAM, OSL_PF_5551); bush = oslLoadImageFile("bush.png", OSL_IN_RAM, OSL_PF_5551); While there are variables stored like sprite->x = 3; if ( (sprite->x + spritewidth > bush->x) && (sprite->x < bush->x + bushwidth) && (sprite->y + spriteheight > bush->y) && (sprite->y < bush->y + bushheight) ) { bushcol = 1; } else { bushcol = 0; } So when i press a button if (osl_keys->held.down) { if (bushcol == 1) { sprite->y = bush->y + 38; } else { sprite->y += 3; } } if (osl_keys->held.up) { if (bushcol == 1) { sprite->y = bush->y - 23; } else { sprite->y -= 3; } } if (osl_keys->held.right) { if (bushcol == 1) { sprite->x = bush->x - 28; } else { sprite->x += 3; } } if (osl_keys->held.left) { if (bushcol == 1) { sprite->x = bush->x + 28; } else { sprite->x -= 3; } } i was thinking of things like sprite->y = bushheight - 24; but it doesnt work Any suggestions?
I think you have the basic idea. Just check your work. Here is a simple version which compiles: #import <stdlib.h> typedef struct { // I'm going to say x, y, is in the center int x; int y; int width; int height; } Rect; Rect newRect(int x, int y, int w, int h) { Rect r = {x, y, w, h}; return r; } int rectsCollide(Rect *r1, Rect *r2) { if (r1->x + r1->width/2 < r2->x - r2->width/2) return 0; if (r1->x - r1->width/2 > r2->x + r2->width/2) return 0; if (r1->y + r1->height/2 < r2->y - r2->height/2) return 0; if (r1->y - r1->height/2 > r2->y + r2->height/2) return 0; return 1; } int main() { Rect r1 = newRect(100,200,40,40); Rect r2 = newRect(110,210,40,40); Rect r3 = newRect(150,250,40,40); if (rectsCollide(&r1, &r2)) printf("r1 collides with r2\n"); else printf("r1 doesnt collide with r2\n"); if (rectsCollide(&r1, &r3)) printf("r1 collides with r3\n"); else printf("r1 doesnt collide with r3\n"); }
865,035
1,237,432
"error C2248: 'CObject::CObject' : cannot access private member declared in class 'CObject'
Possible Duplicate: error using CArray Duplicate : error using CArray so, i am trying to use CArray like this : CArray<CPerson,CPerson&> allPersons; int i=0; for(int i=0;i<10;i++) { allPersons.SetAtGrow(i,CPerson(i)); i++; } but when compiling my program, i get this error : "error C2248: 'CObject::CObject' : cannot access private member declared in class 'CObject' c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtempl.h" I don't even understand where this is coming from. HELP !
Write a constructor for your class (CPerson) and make it public. it should solve the problem.
865,152
865,201
How can I get a process handle by its name in C++?
I'm trying to get the process handle of, say example.exe, so I can call TerminateProcess on it. How can I do this? Notice, it doesn't have a window so FindWindow won't work.
#include <cstdio> #include <windows.h> #include <tlhelp32.h> int main( int, char *[] ) { PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { if (stricmp(entry.szExeFile, "target.exe") == 0) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); // Do stuff.. CloseHandle(hProcess); } } } CloseHandle(snapshot); return 0; } Also, if you'd like to use PROCESS_ALL_ACCESS in OpenProcess, you could try this: #include <cstdio> #include <windows.h> #include <tlhelp32.h> void EnableDebugPriv() { HANDLE hToken; LUID luid; TOKEN_PRIVILEGES tkp; OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken); LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid); tkp.PrivilegeCount = 1; tkp.Privileges[0].Luid = luid; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL); CloseHandle(hToken); } int main( int, char *[] ) { EnableDebugPriv(); PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { if (stricmp(entry.szExeFile, "target.exe") == 0) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); // Do stuff.. CloseHandle(hProcess); } } } CloseHandle(snapshot); return 0; }
865,209
865,256
Should I learn C++ based on new or old standard (specification)?
OK, I am considering of getting into c++ development in coming months (there is no set date). I am vaguely familiar with the language (primarily C), as well as some basics of OO, MI, templates, exceptions, patterns, used STL. And now I am at the point in time where I would like to master the language in depth. And the natural question is whether I should start with current C++03 or C++0x standard. Please suggest what the best way to go from a user to guru, given that new standard is almost here, and likely to remain for many years to come. Thanks
My recommendation is to start out in the middle. Start with C++03, but check the features and C++0x libs that some compilers are already offering each so often. As of now, C++03 is THE standard (not only formally, but most code you will find will be strictly C++03). Now, if you intend on learning go for the best: start quickly with STL basics and jump into Boost libraries right away. Learn templates the whole way, read on metaprogramming. Modern C++03 usage will get you right on track for C++0x.
865,395
865,411
How can I start explorer.exe via C++?
I'm trying to programmatically start explorer.exe but I'm not having any luck. This is my code: cout << pName << "died, lets restart it." << endl; STARTUPINFO startupInfo = {0}; startupInfo.cb = sizeof(startupInfo); PROCESS_INFORMATION processInformation; if(CreateProcess(pName, NULL, NULL, NULL, false, NORMAL_PRIORITY_CLASS, NULL, NULL, &startupInfo, &processInformation) == 0){ cout << "Error starting " << pName << ": " << GetLastError() << endl; } and pName is explorer.exe Can someone tell me what I'm doing wrong? I get the error code '2' which is ERROR_FILE_NOT_FOUND
The first parameter is the application name; the second is the command line. Try specifying "explorer.exe" as the second parameter. See this MSDN article: lpApplicationName [in, optional] The name of the module to be executed. This module can be a Windows-based application. It can be some other type of module (for example, MS-DOS or OS/2) if the appropriate subsystem is available on the local computer. The string can specify the full path and file name of the module to execute or it can specify a partial name. In the case of a partial name, the function uses the current drive and current directory to complete the specification. The function will not use the search path. This parameter must include the file name extension; no default extension is assumed.
865,546
871,315
Generating Symbols in release binaries with Visual Studio
Update: I posted a comment on John Robbins blog about the. He wrote a response here: http://www.wintellect.com/CS/blogs/jrobbins/archive/2009/06/19/do-pdb-files-affect-performance.aspx The project I am working on does not build symbols for its release binaries, and I would like to change this. Some info: Mostly C++ code base, some C#. Compiled under VS2k5, will be moving to VS2k8 Team System. Time critical software. Must have optimizations enabled. Source code is provided to customer so full symbols are fine. What are the best command line switches to generate what I need, and what, if any, performance hits am I going to take? Also, are there any "Gotchas" to be aware of?
Update: I posted a comment on John Robbins blog about the. He wrote a response here: http://www.wintellect.com/CS/blogs/jrobbins/archive/2009/06/19/do-pdb-files-affect-performance.aspx I found the following link on microsofts website: Generating and Deploying Debug Symbols with Microsoft Visual C++ 6.0 This link pertains to Visual C++ 6, but I am assuming these instructions are the same for Visual C++ 8(2005) and 9(2008). The information it gives is very similar to the link provided by TheBlack but more in-depth.
865,666
865,682
How come random deletion from a std::vector is faster than a std::list?
How come that random deletion from a std::vector is faster than a std::list? What I'm doing to speed it up is swapping the random element with the last and then deleting the last. I would have thought that the list would be faster since random deletion is what it was built for. for(int i = 500; i < 600; i++){ swap(vector1[i], vector1[vector1.size()-1]); vector1.pop_back(); } for(int i = 0; i < 100; i++){ list1.pop_front(); } Results (in seconds): Vec swap delete: 0.00000909461232367903 List normal delete: 0.00011785102105932310
What you're doing is not random deletion though. You're deleting from the end, which is what vectors are built for (among other things). And when swapping, you're doing a single random indexing operation, which is also what vectors are good at.
865,668
865,687
Parsing Command Line Arguments in C++?
What is the best way of parsing command-line arguments in C++ if the program is specified to be run like this: prog [-abc] [input [output]] Is there some way of doing this built into the standard library, or do I need to write my own code? Related: Parsing command line arguments in a unicode C++ application
Boost.Program_options should do the trick
865,689
865,750
"Echo" device for Unit Testing
I'm currently writing up some CPPunit tests for a program that tests a hardware communication port (yes, I'm writing unit tests for a tester app ;-) ). One of the classes I'm testing is basically a wrapper around the device's file descriptor; I make read() and write() calls on the file descriptor. Is there a device file/driver on Linux where if you write() to it, when you read() from it you will read back what you wrote (like a FIFO queue device)? If I had this device file, it would be really simple to plop that in place of the actual device file in my wrapper and would make it easy to emulate "loopback" scenarios that might occur on real-world hardware. Essentially what I'm looking for would be a sort of hypothetical "/dev/echo" device. Ex: The device would behave as follows: open("/dev/echo", O_RDRW); write(fdEcho, 123, sizeof(int)); write(fdEcho, 456, sizeof(int)); write(fdEcho, 789, sizeof(int)); read(fdEcho, iData, sizeof(int); // returns 123 read(fdEcho, iData2, sizeof(int); // returns 456 read(fdEcho, iData3, sizeof(int); // returns 789
Why don't you use a UNIX pipe in the filesystem? mkfifo /dev/test echo test > /dev/test on a second terminal: cat /dev/test Then the first will unblock and the second will show the text!
865,756
2,923,148
Can't call base class method even though I have a pointer to it (Decorator)?
I have a template class that I've subclassed with a pointer to it (Decorator pattern). I added a getBase() call to return the pointer to the base class for any further subclasses. However, when I use that getBase() and call the base classes only method, I get a linker error that it can't find the symbol for that method in the intervening (Decorator) class? Like this: template <typename T> class B { public: typedef std::auto_ptr<T> MYFUN( std::istream&, const std::string&, const std::string& ); public: B<T>( MYFUN* p ); auto_ptr<T> fun( istream& ); private: MYFUN *fptr; }; template <typename T> class D : public class B<T> { D( typename B<T>::MYFUN *fPtr, B<T> *providedBase ); //Looks like B B* getBase() { return base_ ; } private: B* base_; }; template <typename T> class Dagain : public class D<T> { //Looks like D auto_ptr<T> fun( istream& ); }; auto_ptr<T> Dagain::fun( istream& is ) { this->getBase()->fun( is ); } Note that there is no definition for fun( istream& ) in D<T>. The intention is for the client to use the pointer to the base to call B<T>::fun( istream& ) When the client constructs a Dagain object, the linker says (basically): Client.o: (.data.rel.ro. --stuff-- [vtable for D<T>]: undefined reference to 'D<T>::fun( basic_istream<char, char_traits<char> >&)' But, I'm not calling D's definition of fun(istream&)... it doesn't even have one! I'm using the pointer directly to the base class... When I add a definition for D<T>::fun(istream&) things work, but I don't understand why?
You have forgotten to specify the template parameter in the template definition. Furthermore you had some more errors. Here is the working code: template <typename T> class B { public: typedef std::auto_ptr<T> MYFUN( std::istream&, const std::string&, const std::string& ); public: B<T>( MYFUN* p ); auto_ptr<T> fun( istream& ); private: MYFUN *fptr; }; template <typename T> class D : public B<T> { D( typename B<T>::MYFUN *fPtr, B<T> *providedBase ); //Looks like B B<T>* getBase() { return base_ ; } private: B<T>* base_; }; template <typename T> class Dagain : public D<T> { //Looks like D auto_ptr<T> fun( istream& ); }; template <typename T> auto_ptr<T> Dagain<T>::fun( istream& is ) { this->getBase()->fun( is ); }
865,785
865,810
Why does the order of my #includes matter? (C++)
I've created a header file called "list_dec.h", put it in a folder "C:\Headers", and set my compiler to include files from "C:\Headers", so now I can do things like #include<list_dec.h> int main(){return(0);} but when I try to do something like #include<iostream> #include<list_dec.h> int main(){return(0);} I get an error (not anything specific, just a huge list of syntax errors in "list_dec.h", which I know aren't real because I've been able to compile it as both a main.cpp file and a .h file in a separate project). However, when I change to order so "list_dec.h" is on top: #include<list_dec.h> #include<iostream> int main(){return(0);} all of the errors go away. So why does the order of the error matter? NB: As far as I know, this occurs when I use "list_dec.h" with all header files, but the files I'm absolutely positive it occurs in are: #include<iostream> #include<vector> #include<time.h> #include<stdlib.h> EDIT: These are the errors I get when "list_dec.h" is below any other header: c:\headers\list_dec.h(14) : error C2143: syntax error : missing ')' before 'constant' c:\headers\list_dec.h(51) : see reference to class template instantiation 'list<T,limit>' being compiled c:\headers\list_dec.h(14) : error C2143: syntax error : missing ';' before 'constant' c:\headers\list_dec.h(14) : error C2059: syntax error : ')' c:\headers\list_dec.h(14) : error C2238: unexpected token(s) preceding ';' c:\headers\list_dec.h(69) : warning C4346: 'list<T,limit>::{ctor}' : dependent name is not a type prefix with 'typename' to indicate a type c:\headers\list_dec.h(69) : error C2143: syntax error : missing ')' before 'constant' c:\headers\list_dec.h(69) : error C2143: syntax error : missing ';' before 'constant' c:\headers\list_dec.h(69) : error C2988: unrecognizable template declaration/definition c:\headers\list_dec.h(69) : error C2059: syntax error : 'constant' c:\headers\list_dec.h(69) : error C2059: syntax error : ')' c:\headers\list_dec.h(78) : error C2065: 'T' : undeclared identifier c:\headers\list_dec.h(78) : error C2065: 'limit' : undeclared identifier c:\headers\list_dec.h(78) : error C2065: 'T' : undeclared identifier c:\headers\list_dec.h(78) : error C2065: 'limit' : undeclared identifier c:\headers\list_dec.h(79) : error C2143: syntax error : missing ';' before '{' c:\headers\list_dec.h(79) : error C2447: '{' : missing function header (old-style formal list?) If it helps, these are the lines mentioned in the errors (14, 69, 78, and 79): Line 14: list(const T& NULL); (A constructor for "list" class) Line 69: inline list<T, limit>::list(const T& NULL): (Definition for the constructor, also, the colon at the end is intentional, It part of the definion ie: void x(int n): VAR(n).) Line 78: inline list<T, limit>::list(const list<T, limit>& lst) (def for the copy constructor) Line 79: { (the begining of the list-copy contructor) And a lot of people want to see the beginning of "list_dec.h": template<class T, size_t limit> class list NB: These aren't the first lines, but they're where I think the problem is, the lines before them are simply an enumeration called "err". EDIT: Just a note, "list_dec.h" contains no includes, defines, ifdefs, or anything precede with a '#'. Besides the enumeration, it only contains the "list" class declaration and the "list" class member function definitions.
Generally speaking it should not, however it may be possible for there to be conflicting definitions of symbols or preprocessor macros that end up confusing the compiler. Try to narrow down the size of the problem by removing pieces and includes from the conflicting header until you can see what is causing it. In response to the error messages you posted, the symbol NULL is often implemented as a preprocessor macro for the number 0. This is so that you can easily use it as a null pointer. Therefore this: list(const T& NULL); Could be converted into this syntax error by the preprocessor: list(const T& 0); Change the name of the parameter to something other than NULL.
866,012
866,283
Is there a way to define variables of two different types in a for loop initializer?
You can define 2 variables of the same type in a for loop: int main() { for (int i = 0, j = 0; i < 10; i += 1, j = 2*i) { cout << j << endl; } } But it is illegal to define variables of different types: int main() { for (int i = 0, float j = 0.0; i < 10; i += 1, j = 2*i) { cout << j << endl; } } Is there a way to do this? (I don't need to use i inside the loop, just j.) If you have totally hacked and obscure solution, It's OK for me. In this contrived example I know you could just use double for both variables. I'm looking for a general answer. Please do not suggest to move any of the variables outside of for body, probably not usable for me as one is an iterator that has to disappear just after the loop and the for statement is to be enclosed in my foreach macro: #define foreach(var, iter, instr) { \ typeof(iter) var##IT = iter; \ typeof(iter)::Element var = *var##IT; \ for (; var##_iterIT.is_still_ok(); ++var##IT, var = *var#IT) { \ instr; \ } \ } It can be used thus: foreach(ii, collection, { cout << ii; }). But I need something that will be used like that: foreach(ii, collection) cout << ii; Please do not introduce any runtime overhead (but it might be slow to compile).
Here is a version using boost preprocessor (This is just for fun. For the real-world answer, see @kitchen's one above): FOR((int i = 0)(int j = 0.0), i < 10, (i += 1, j = 2 * i)) { } The first part specifies a sequence of declarations: (a)(b).... The variables declared later can refer to variables declared before them. The second and third part are as usual. Where commas occur in the second and third parts, parentheses can be used to prevent them to separate macro arguments. There are two tricks known to me used to declare variables that are later visible in a compound statement added outside a macro. The first uses conditions, like an if: if(int k = 0) ; else COMPOUND_STATEMENT Then k is visible. Naturally, it always have to evaluate to false. So it can't be used by us. The other context is this one: for(int k = 0; ...; ...) COMPOUND_STATEMENT That's what i'm going to use here. We'll have to watch to only make one iteration of COMPOUND_STATEMENT. The actual for loop that does the increment and condition checking has to come at the end, so the appended compound statement appertains to it. #include <boost/preprocessor.hpp> #include <iostream> #define EMIT_DEC_(R,D,DEC) \ for(DEC; !_k; ) #define FOR(DECS, COND, INC) \ if(bool _k = false) ; else \ BOOST_PP_SEQ_FOR_EACH(EMIT_DEC_, DECS, DECS) \ for(_k = true; COND; INC) int main() { FOR((int i = 0)(float j = 0.0f), i < 10, (i += 1, j = 2 * i)) { std::cout << j << std::endl; } } It's creating a bunch of for statements, each nested into another one. It expands into: if(bool _k = false) ; else for(int i = 0; !_k; ) for(float j = 0.0f; !_k; ) for(_k = true; i < 10; (i += 1, j = 2 * i)) { std::cout << j << std::endl; }
866,664
866,726
How to organise source code in a modular manner
I'm currently working on a project that has scope to become quite large, however being relatively new to C++ and coming from a Java background I'm not sure about the best way to proceed. I would like to have a directory structure similar to: + Root - main.cpp + Engine + Core - foo.cpp - foo.h + Utilities - bar.cpp - bar.h + Sound + Input + Collision Detection + Particle System At the moment I have a load of .ccp/.h files sitting in the Engine directory. When I move them to their appropriate folders and try to tie them together I just get pages of compile errors relating to classes being undefined. Can some kind soul help point a novice in the right direction?!
You're almost certainly having trouble with include files being included. You need to add to the compile command -I flags for the directories from which you're bringing in your .h files. Several of your directory names have spaces in them, so be careful that you're quoting the directory names correctly. Or, even better, since that's often a major pain, change, eg, "Collision Detection" to be "CollisionDetection" or "Collision_Detection"
866,672
866,685
Switching stacks in C++
I have some old code written in C for 16-bit using Borland C++ that switches between multiple stacks, using longjmps. It creates a new stack by doing a malloc, and then setting the SS and SP registers to the segment and offset, resp., of the address of the malloc'd area, using inline Assembler. I would like to convert it to Win32, and it looks like the two instructions should be replaced by a single one setting the ESP. The two instructions were surrounded by a CLI/STI pair, but in Win32 these give "privileged instructions", so I have cut them out for now. I am a real innocent when it comes to Windows, so, I was rather surprised that my first test case worked! So, my rather vague question is to ask the experts here if what I am doing is a) too dangerous to continue with, or b) will work if I add some code, take certain precautions, etc.? If the latter, what should be added, and where can I find out about it? Do I have to worry about any other registers, like the SS, EBX, etc.? I am using no optimization... Thanks for any tips people can give me.
Removing CLI/STI still works due to the differences in the operating environment. On 16-bit DOS, an interrupt could occur and this interrupt would be initially running on the same stack. If you got interrupted in the middle of the operation, the interrupt could crash because you only updated ss and not sp. On Windows, and any other modern environment, each user mode thread gets its own stack. If your thread is interrupted for whatever reason, it's stack and context are safely preserved - you don't have to worry about something else running on your thread and your stack. cli/sti in this case would be protecting against something you're already protected against by the OS. As Greg mentioned, the safe, supported way of swapping stacks like this on Windows is CreateFiber/SwitchToFiber. This does have the side-effect of changing your entire context, so it is not like just switching the stack. This really raises the question of what you want to do. A lot of times, switching stacks is to get by limited stack space, which was 64k on 16-bit DOS. On Windows, you have a 1 MB stack and you can allocate even larger. Why are you trying to switch stacks?
866,679
866,716
Using OpenGL /GLUT how would I detect if two keys are held down at the same time?
Using OpenGL /GLUT how would I detect if two keys, say 'a' and 'j' are held down at the same time? (This program needs to compile with OSX GCC, Windows GCC, Windows VS2005 so no OS dependent hacks please.)
Try the following: Use glutIgnoreKeyRepeat to only get physical keydown/keyup events Use glutKeyboardFunc to register a callback listening to keydown events. Use glutKeyboardUpFunc to register a callback listening to keyup events. Create a bool keystates[256] array to store the state of the keyboard keys. When receiving an event through your keydown callback, set keystates[key] = true. When receiving an event through your keyup callback, set keystates[key] = false. In your run loop, test if (keystates['a'] || keystates['A']) && (keystates['j'] || keystates['J']). Look in that direction. Although I haven't tested it, it should work. You might also need glutSpecialFunc and glutSpecialUpFunc to receive messages for 'special' keys. Also, be aware that GLUT is really old stuff and that there are much nicer alternatives.
866,718
866,755
Precompiled headers supported on gcc 3.3.3?
Are precompiled headers supported on gcc 3.3.3 ? If yes what is the syntax to generate and use precompiled headers on Linux with gcc 3.3.3. We crosscompile our projects on Windows and Linux, on Windows we precompile stdafx.h and I'm investigating how to set it up so that it is precompiled on Linux as well. I'm aware of the gcc doc , I'm searching for the actual solution. On gcc 3.3.3 I get this: > gcc stdafx.h gcc: compilation of header file requested And last, if it worked what would be the name of generated file? EDIT: Precompiled headers do not seem to be supported on gcc 3.3.3 and on newer gcc the generated file is named with .gch extension.
I don't know from what version gcc supports it, but for how to use them just read the gcc documentation. Anyway, gcc 3.3.3 is pretty old, too. Maybe there's a chance that you can upgrade to a more recent 4.X version? That should support recompiled headers. Maybe you could try the latest 3.X GCC (GCC 3.4.6). I assume the ABI break is from 3.X to 4.X, so 3.4 may be compatible. I think it may be worth checking. from http://gcc.gnu.org/gcc-3.4/changes.html C/Objective-C/C++ Precompiled headers are now supported.
866,730
866,756
Memory Efficient Methods To Find Unique Strings
I have a data set that looks like this: 000 100 200 300 010 020 030 001 002 003 001 101 201 301 011 021 031 000 002 003 002 102 202 302 012 022 032 001 000 003 003 103 203 303 013 023 033 001 002 000 010 110 210 310 000 020 030 011 012 013 020 120 220 320 010 000 030 021 022 023 030 130 230 330 010 020 000 031 032 033 033 133 233 333 013 023 003 031 032 030 100 000 200 300 110 120 130 101 102 103 133 033 233 333 113 123 103 131 132 130 200 100 000 300 210 220 230 201 202 203 233 133 033 333 213 223 203 231 232 230 300 100 200 000 310 320 330 301 302 303 303 103 203 003 313 323 333 301 302 300 313 113 213 013 303 323 333 311 312 310 330 130 230 030 310 320 300 331 332 333 331 131 231 031 311 321 301 330 332 333 332 132 232 032 312 322 302 331 330 333 333 133 233 033 313 323 303 331 332 330 What I intend to do is to generate list of unique strings from it, yielding: 000 001 002 003 010 011 012 013 020 021 022 023 030 031 032 033 100 101 102 103 110 113 120 123 130 131 132 133 200 201 202 203 210 213 220 223 230 231 232 233 300 301 302 303 310 311 312 313 320 321 322 323 330 331 332 333 The code I have to generate that is this. But it is very memory consumptive. Because in reality the string is of length >36 and there are more than 35 million lines in a file. Each line with >36*3 number of columns/entries. Is there a memory efficient way to do it? #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <map> using namespace std; int main ( int arg_count, char *arg_vec[] ) { if (arg_count !=2 ) { cerr << "expected one argument" << endl; return EXIT_FAILURE; } string line; ifstream myfile (arg_vec[1]); map <string,int> Tags; if (myfile.is_open()) { while (getline(myfile,line) ) { stringstream ss(line); string Elem; while (ss >> Elem) { Tags[Elem] = 1; } } myfile.close(); } else { cout << "Unable to open file";} for (map <string,int>::iterator iter = Tags.begin(); iter != Tags.end();iter++) { cout << (*iter).first << endl; } return 0; }
This depends a bit on the characteristics of your dataset. In the worse case, where all strings are unique, you will need either O(n) memory to record your seen-set, or O(n^2) time to re-scan the entire file on each word. However, there are improvements that can be made. First off, if your dataset only consists of 3-digit integers, then a simple array of 1000 bools will be much more memory effieicnt than a map. If you're using general data, then another good approach would be to sort the set, so copies of the same string end up adjacent, then simply remove adjacent words. There are well-researched algorithms for sorting a dataset too large to fit in memory. This is most effective when a large percentage of the words in the set are unique, and thus holding a set of seen words in memory is prohibitively expensive. Incidentally, this can be implemented easily with a shell pipeline, as GNU sort does the external sort for you: tr " " "\n" < testdata | LC_ALL=C sort | uniq Passing LC_ALL=C to sort disables locale processing and multibyte character set support, which can give a significant speed boost here.
866,733
868,359
Monitoring storage space on windows mobile
In a native(c++) windows mobile app. There are ways to be notified of low memory, WM_HIBERNATE, and low power, RequestPowerNotifications(). Is there any way to be notified when storage space is running low? Or must an app just poll regularly with GetDiskFreeSpaceEx()?
No, there are no system notifications for storage space.
866,776
866,782
What does this code in "vector" mean? (C++)
I created a program, and it uses the vector.h #include, and iterators, etc... But when I run the program, under certain circumstances (I'm still trying to figure out what those would be) I get an assertion error refering me to line 98 of vector.h. I went to line 98 of vector.h and got this: #if _HAS_ITERATOR_DEBUGGING if (this->_Mycont == 0 || _Myptr < ((_Myvec *)this->_Mycont)->_Myfirst || ((_Myvec *)this->_Mycont)->_Mylast <= _Myptr) { _DEBUG_ERROR("vector iterator not dereferencable"); _SCL_SECURE_OUT_OF_RANGE; } Can somebody please tell me what this means and what in my program is causing this assertion? NB: Line 98, for the record, is the one that begins "_DEBUG_ERROR("vect..." NB: This is the code in my program that I BELIEVE triggered the error, I'm not entirely sure, though. CODE: for(aI = antiviral_data.begin(); aI < antiviral_data.end();) { for(vI = viral_data.begin(); vI < viral_data.end();) { if((*aI)->x == (*vI)->x && (*aI)->y == (*vI)->y) { vI = viral_data.erase(vI); aI = antiviral_data.erase(aI); } else { vI++; } } if((*aI)->x >= maxx || (*aI)->x < 0 || (*aI)->y >= maxy || (*aI)->y < 0) { aI = antiviral_data.erase(aI); } else { aI++; } }
The runtime is detecting that you are dereferencing an iterator that is before begin() or after end(). Imagine if you delete the last item in the antiviral_data vector in line 7: aI = antiviral_data.erase(aI); aI gets set to antiviral_data.end(), and when you dereference it in line 14: if((*aI)->x >= maxx ... and also in line 5: if((*aI)->x == (*vI)->x You are dereferencing an out of bounds iterator. The fix is to check that aI != antiviral_data.end() after the erase call to make sure you haven't hit the end of the vector before you continue on using it.
867,135
867,241
How to find the difference between two times in c?
my first time is 12:10:20 PM and second time is 7:10:20 Am of the same day how can i find diff b/w them?? My idea is convert all the time to seconds and find the difference again convert to time is it good Approch r anything else??
Not necessarily the best way, but if you wish to use what's available on the system, difftime() and mktime() can help - #include <time.h> tm Time1 = { 0 }; // Make sure everything is initialized to start with. /* 12:10:20 */ Time1.tm_hour = 12; Time1.tm_min = 10; Time1.tm_sec = 20; /* Give the function a sane date to work with (01/01/2000, here). */ Time1.tm_mday = 1; Time1.tm_mon = 0; Time1.tm_year = 100; tm Time2 = Time1; // Base Time2 on Time1, to get the same date... /* 07:10:20 */ Time2.tm_hour = 7; Time2.tm_min = 10; Time2.tm_sec = 20; /* Convert to time_t. */ time_t TimeT1 = mktime( &Time1 ); time_t TimeT2 = mktime( &Time2 ); /* Use difftime() to find the difference, in seconds. */ double Diff = difftime( TimeT1, TimeT2 );
867,270
867,281
Passing a **Class as an argument
I'm trying to declare a method in main.h like this: void buildGraph(int gNum, Graph** gArray); Where Graph is a class and I'm trying to pass a pointer to an array of pointers to Graph objects. I get the error message: "Graph has not been declared". Even though I have #include "graph.h" at the top of the page and I've been using the graph class plenty until now, so I know it works. Any ideas?
Maybe the name Graph is in a namespace? What does that graph.h file say -- is Graph at top-level, or inside a namespace statement?
867,462
867,804
C++ implicit conversions
Several comments on a recent answer of mine, What other useful casts can be used in C++, suggest that my understanding of C++ conversions is faulty. Just to clarify the issue, consider the following code: #include <string> struct A { A( const std::string & s ) {} }; void func( const A & a ) { } int main() { func( "one" ); // error func( A("two") ); // ok func( std::string("three") ); // ok } My assertion was that the the first function call is an error, becauuse there is no conversion from a const char * to an A. There is a conversion from a string to an A, but using this would involve more than one conversion. My understanding is that this is not allowed, and this seems to be confirmed by g++ 4.4.0 & Comeau compilers. With Comeau, I get the following error: "ComeauTest.c", line 11: error: no suitable constructor exists to convert from "const char [4]" to "A" func( "one" ); // error If you can point out, where I am wrong, either here or in the original answer, preferably with reference to the C++ Standard, please do so. And the answer from the C++ standard seems to be: At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value. Thanks to Abhay for providing the quote.
I think the answer from sharptooth is precise. The C++ Standard (SC22-N-4411.pdf) section 12.3.4 titled 'Conversions' makes it clear that only one implicit user-defined conversion is allowed. 1 Type conversions of class objects can be specified by constructors and by conversion functions. These conversions are called user-defined conversions and are used for implicit type conversions (Clause 4), for initialization (8.5), and for explicit type conversions (5.4, 5.2.9). 2 User-defined conversions are applied only where they are unambiguous (10.2, 12.3.2). Conversions obey the access control rules (Clause 11). Access control is applied after ambiguity resolution (3.4). 3 [ Note: See 13.3 for a discussion of the use of conversions in function calls as well as examples below. —end note ] 4 At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value.
867,724
1,446,878
How to modify the tool rect of a CToolTipCtrl?
This question is related to this one. In a CDockablePane derived class I have a CTreeCtrl member for which I add a ToolTip in OnCreate(): int CMyPane::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDockablePane::OnCreate(lpCreateStruct) == -1) return -1; const DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | TVS_CHECKBOXES | TVS_DISABLEDRAGDROP | TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT | TVS_INFOTIP | TVS_NOHSCROLL | TVS_SHOWSELALWAYS; if(!m_tree.Create(dwStyle, m_treeRect, this, TREECTRL_ID) ) { return -1; } m_pToolTip->AddTool(&m_tree, LPSTR_TEXTCALLBACK, &m_treeRect, TREECTRL_ID); m_tree.SetToolTips(m_pToolTip); return 0; } I have to call AddTool() with all of the optional parameters because the default values won't work with CDockablePane. m_treeRect is a CRect member set to (0, 0, 10000, 10000) in the CTor. This is really ugly. I would like to adjust the tool's rectangle whenever m_tree's size changes. So I tried some stuff in CMyPane::OnSize() but none of it worked: Calling m_pToolTip->GetToolInfo() then modify the CToolInfo's rect member, then calling SetToolInfo() Calling m_pToolTip->SetToolRect() How is it meant to be done?
I know no other way to do this other than calling DelTool then AddTool again in your OnSize handler: void CMyPane::OnSize(UINT nType, int cx, int cy) { CDockablePane::OnSize(nType, cx, cy); if (m_pToolTip != NULL) { m_pToolTip->DelTool(&m_tree, TREECTRL_ID); CRect treeRect; m_tree.GetClientRect(treeRect); m_pToolTip->AddTool(&m_tree, LPSTR_TEXTCALLBACK, &treeRect, TREECTRL_ID); } }
867,813
869,043
How do I plot the output from a C++ Win32 console app?
I have a small Win32 console application which is essentially a test harness. I read data in, do some processing on it and currently just output some of the numbers to the console. This isn't a huge problem - I can get an idea of what the data looks like, but it would be much easier to analyse if there was a way of getting that information into a graph for each run of the software. I've been getting to grips with GNUPlot recently, but can't work out a simple way to get the data sent to it. Has anyone tried this? ..or is there another graphing application I should try? Excel and OO Calc are great tools and I've loaded .csv data into them for graphing data plenty of times myself. I was, however, hoping for a way to dynamically pipe data into a graphing application to avoid having to close/reopen excel and plot a graph each time I want to look at some data. I think you can pipe data into GNUPlot (which is why I mentioned it) but the details of how to do so are rather scant.
You don't really need to touch VBA to do this In Excel you can set up a Data Connection to a file, it supports many files type but CSV does work fine. Go to List item Data Tab Click Connections Click Add select the file go to the connection properties - un-tick prompt for file name set the required period. close the connections dialog select the start cell for importing the data - cell 1a on worksheet 2 click existing connections select you data connection flip to worksheet1 add your chart and hookup the data. the chart will now update automatically this is Excel 2007 - but think older version had this and I think OO can do it to.
868,108
868,127
Polymorphic or generic approach is better? C#
I have two classes and an interface like interface IVehicle { void Drive(); } class Benz :IVehicle { public void Drive() { Console.WriteLine("WOW! driving benz"); } } class Ferrari : IVehicle { public void Drive() { Console.WriteLine("WOW! driving ferrari"); } } I got a Driver class which uses this. class Driver { public void StartDriving(IVehicle vehicle) { vehicle.Drive(); } } There is one more driver which is generic. class GenericDriver { public void StartDriving<T>() where T : IVehicle , new() { T vehicle = new T(); vehicle.Drive(); } } Questions Do you see any advantages for the generic implementation compared to normal Driver? If yes, what are they? Which one do you prefer? A generic one or the normal one? Is there a better way to implement a generic driver? I am getting a feeling that generics in C# is very limited when compared with C++ templates. Is that true? Any thoughts?
Absolutely no advantages in this case whatsoever. Except if you really want to create an instance of T in Drive(), which can be done without generics with delegate IVehicle VehicleBuilder(); It depends on the situation. But generally speaking I'd prefer first. Again: it depends on what you want to do. Yes, this is true. Remember though, that C++ templates are compile-time (JIT time) constructs, whereas C# generics are run-time constructs. Now on why would I want a generic Driver. Consider: class Driver<TVehicle> where TVehicle : class, IVehicle, new() { public TVehicle Vehicle { get; set } public Driver() { Vehicle = new TVehicle(); } } This way I'll be able to use a strongly-typed Driver<>.Vehicle property which will be of a particular type, rather than of a more common IVehicle.
868,306
869,597
What is the difference between static_cast and Implicit_cast?
What is implicit_cast? when should I prefer implicit_cast rather than static_cast?
I'm copying over from a comment i made to answer this comment at another place. You can down-cast with static_cast. Not so with implicit_cast. static_cast basically allows you to do any implicit conversion, and in addition the reverse of any implicit conversion (up to some limits. you can't downcast if there is a virtual base-class involved). But implicit_cast will only accept implicit conversions. no down-cast, no void*->T*, no U->T if T has only explicit constructors for U. Note that it's important to note the difference between a cast and a conversion. In the following no cast is going on int a = 3.4; But an implicit conversion happens from double to int. Things like an "implicit cast" don't exist, since a cast is always an explicit conversion request. The name construct for boost::implicit_cast is a lovely combination of "cast using implicit conversions". Now the whole implementation of boost::implicit_cast is this (explained here): template<typename T> struct identity { typedef T type; }; template<typename Dst> Dst implicit_cast(typename identity<Dst>::type t) { return t; } The idea is to use a non-deduced context for the parameter t. That will avoid pitfalls like the following: call_const_version(implicit_cast(this)); // oops, wrong! What was desired is to write it out like this call_const_version(implicit_cast<MyClass const*>(this)); // right! The compiler can't deduce what type the template parameter Dst should name, because it first must know what identity<Dst> is, since it is part of the parameter used for deduction. But it in turn depends on the parameter Dst (identity could be explicitly specialized for some types). Now, we got a circular dependency, for which the Standard just says such a parameter is a non-deduced context, and an explicit template-argument must be provided.
868,530
868,546
Reading binary file defined by a struct
Could somebody point me in the right direction of how I could read a binary file that is defined by a C struct? It has a few #define inside of the struct, which makes me thing that it will complicate things. The structure looks something like this: (although its larger and more complicated than this) struct Format { unsigned long str_totalstrings; unsigned long str_name; #define STR_ORDERED 0x2 #define STR_ROT13 0x4 unsigned char stuff[4]; #define str_delimiter stuff[0] } I would really appreciate it if somebody could point me in the right direction on how to do this. Or if theres any tutorial out there that covers this topic? Thanks a lot in advance for your help.
Reading a binary defined by a struct is easy. Format myFormat; fread(&myFormat, sizeof(Format), 1, fp); the #defines don't affect the structure at all. (Inside is an odd place to put them, though). However, this is not cross-platform safe. It is the simplest thing that will possibly work, in situations where you are assured the reader and writer are using the same platform. The better way would be to re-define your structure as such: struct Format { Uint32 str_totalstrings; //assuming unsigned long was 32 bits on the writer. Uint32 str_name; unsigned char stuff[4]; }; and then have a 'platform_types.h" which typedefs Uint32 correctly for your compiler. Now you can read directly into the structure, but for endianness issues you still need to do something like this: myFormat.str_totalstrings = FileToNative32(myFormat.str_totalstrings); myFormat.str_name = FileToNative32(str_name); where FileToNative is either a no-op or a byte reverser depending on platform.
868,773
868,969
Central Clickable MSDN like Linux System/C/C++ Standard Library Documentation
If you are windows programmer and you want to program something new where you are going to use some new API with which you are not that familiar then you can type MSDN on your web browser and you get immediately what you need. Nicely grouped API functions where you can see what to include and what to link. I am looking for something similar in the Linux world. I want to sleep my function for some milliseconds and I type "man sleep" then I get the explanation of shell command "sleep". But I don't want that. I am programming and I just want see the programmatical usage of that function. So the question is: Is there a central, clickable and browsable documentation of C, C++ standard libraries AND linux system calls which are not part of the C/C++ standard but quite often used in linux programming ? Thanks in advance, G.
Man is broken down into sections If you type "man man" you can see them. 1 Executable programs or shell commands 2 System calls (functions provided by the kernel) 3 Library calls (functions within program libraries) 4 Special files (usually found in /dev) 5 File formats and conventions eg /etc/passwd 6 Games 7 Miscellaneous (including macro packages and conven‐ tions), e.g. man(7), groff(7) 8 System administration commands (usually only for root) 9 Kernel routines [Non standard] So since you wnat the library call version of sleep() you would write "man 3 sleep". Also "info" is another way to access the same information. You can also do a search with "man -k sleep", which will list everything matching sleep. There are hyperlinked man pages scattered around the internet if you want to bookmark them. For C++ APIs there are some good sites that many people have bookmarked and open a good portion of the time. The important thing to remember is that unlike Windows, no one really owns or controls Linux. You can build any kind of distribution you want with many different kernel options. It makes things less tidy in some ways but far more flexible in others.
868,853
869,948
Redirect barcode scanner input to specific widget in linux
I have a Symbol LS2208 barcode scanner and works OK in my linux box (Kubuntu 8.10 Intrepid Ibex). Whenever you scan a barcode the scanner (connected to an USB port) sends the reading to wherever the text caret is. I would like to redirect all the readings from the scanner to an specific widget in my application (i.e. a text edit control). How can I do it? Though I use C++ with Qt GUI library sample code is welcome in any language or GUI library.
I don't know the answer, but here are some suggestions to find out what your options are: Install an event filter on QCoreApplication::instance() (or reimplement QCoreApplication::notify()) In event filter handler, output each event looking for anything useful: void eventFilter(QObject *obj, QEvent *evt) { qDebug() << obj << evt; } Examine the debug output to determine which events are triggered by the scanner. qDebug() understands virtually every type and should give you reasonable output that will allow you to tell whether the it's coming in as keyboard events or something else.
868,966
959,014
Fast JPEG encoding library
anyone know of a free open-source jpeg encoding library for C/C++? Currently I'm using ImageMagick, which is easy to use, but it's pretty slow. I compared it to an evaluation of Intel Performance Primitives and the speed of IPP is insane. Unfortunately it also costs 200$, and I don't need 99% of the IPP). Also it will only work fast on Intel. Anyone do any tests? Any other good libraries out there faster than ImageMagick? Edit: I was using 8 bit version of ImageMagick which is supposed to be faster.
ImageMagick uses libjpeg (a.k.a Independent JPEG Group library). If you improve the speed of libjpeg, ImageMagick JPEG speed will increase. There are a few options: Compile an optimized libjpeg. If you have a modern gcc and at least a Pentium 4, you can try -O3 -msse2 and see if it can boost your speed. Then you can use LD_LIBRARY_PATH or some other way to load your libjpeg instead of the system one. Try out libjpeg-mmx. It is unmaintained, and supposedly buggy and with security flaws, but it may give a speed boost in your case.
869,281
869,310
passing this from constructor initializer list
Are there any issues when passing 'this' to another object in the initializer list in the following code? class Callback { public: virtual void DoCallback() = 0; }; class B { Callback& cb; public: B(Callback& callback) : cb(callback) {} void StartThread(); static void Thread() { while (!Shutdown()) { WaitForSomething(); cb.DoCallback(); } } }; class A : public Callback { B b; public: A() : b(*this) {b.StartThread();} void DoCallback() {} }; If it is unsafe to do that, what's the best alternative?
If you are extremely careful this will work fine. You will get into a lot of trouble if you start calling virtual methods or using methods which depend on other objects in the type. But if you're just setting a reference this should work fine. A safer (but not completely safe) alternative is to set b later on once the constructor is completed. This won't eliminate vtable issues but will remove problems like accessing other member variables before they are constructed. class A : public Callback { std::auto_ptr<B> spB; public: A() { spB.reset(new B(this)); spB->StartThread(); } };
869,503
869,846
Failsafe conversion between different character encodings
I need to convert strings from one encoding (UTF-8) to another. The problem is that in the target encoding we do not have all characters from the source encoding and libc iconv(3) function fails in such situation. What I want is to be able to perform conversion but in output string have this problematic characters been replaced with some symbol, say '?'. Programming language is C or C++. Is there a way to address this issue ?
Try appending "//TRANSLIT" or "//IGNORE" to the end of the destination charset string. Note that this is only supported under the GNU C library. From iconv_open(3): //TRANSLIT When the string "//TRANSLIT" is appended to tocode, translitera‐ tion is activated. This means that when a character cannot be represented in the target character set, it can be approximated through one or several similarly looking characters. //IGNORE When the string "//IGNORE" is appended to tocode, characters that cannot be represented in the target character set will be silently discarded. Alternately, manually skip a character and insert a substitution in the output when you get -EILSEQ from iconv(3).
869,593
869,661
compare function for upper_bound / lower_bound
I want to find the first item in a sorted vector that has a field less than some value x. I need to supply a compare function that compares 'x' with the internal value in MyClass but I can't work out the function declaration. Can't I simply overload '<' but how do I do this when the args are '&MyClass' and 'float' ? float x; std::vector< MyClass >::iterator last = std::upper_bound(myClass.begin(),myClass.end(),x);
What function did you pass to the sort algorithm? You should be able to use the same one for upper_bound and lower_bound. The easiest way to make the comparison work is to create a dummy object with the key field set to your search value. Then the comparison will always be between like objects. Edit: If for some reason you can't obtain a dummy object with the proper comparison value, then you can create a comparison functor. The functor can provide three overloads for operator() : struct MyClassLessThan { bool operator() (const MyClass & left, const MyClass & right) { return left.key < right.key; } bool operator() (const MyClass & left, float right) { return left.key < right; } bool operator() (float left, const MyClass & right) { return left < right.key; } }; As you can see, that's the long way to go about it.
869,648
869,658
Re-throwing exception caught by pointer
In C++, what is the difference between the following examples? Re-throw pointer: catch (CException* ex) { throw ex; } Simple re-throw: catch (CException* ex) { throw; } When the re-throw is caught, will the stack trace be different?
Yes. Basically, you are throwing the object yourself in the first case. It looks like you generated the exception yourself in the throw ex line. In the second case, you are just letting the original object go up in the call stack (and thus preserving the original call stack), those are different. Usually, you should be using throw;.
869,664
879,487
Multithreading with Inheritance (C++)
I am trying to call the "Run" function in a new thread. Right now, I have this code using openMP that doesn't actually run "Run" in a new thread. NOTE: I am not asking for help using OpenMP. This code was just a quick fix. I would prefer a CreateThread() method of going about this. vector<ICommand*>* commands; string strInput; // For each command... for(vector<ICommand*>::iterator i = commands->begin(); i != commands->end(); ++i) { // ...if the current command we're examining is valid... if((*i)->ContainsCommand(strInput)) { // ...run it in a new thread and don't let ZChatInput handle it normally... #pragma omp sections nowait { #pragma omp section (*i)->Run(strInput); #pragma omp section bRet = false; } // ...and don't check any more commands. break; } } So how would this be done using just standard and STL? Of course, I'm looking for a way that works :)
So I figured it out after double-checking the MSDN documentation. Here's how I did it, in case any of you are interested: static vector<ICommand*>* commands; // This is what we pass to CommandOnThread. struct CommandParameter { string strInput; ICommand* command; }; int CommandOnThread(CommandParameter* cp) { cp->command->Run(cp->strInput); delete cp; return 0; } void foo() { string strInput; ... // For each command... for(vector<ICommand*>::iterator i = commands->begin(); i != commands->end(); ++i) { // ...if the current command we're examining is valid... if((*i)->ContainsCommand(strInput)) { // Put the CP on the stack. CommandParameter* temp = new CommandParameter; if(temp == NULL) { Print("Out of memory!"); bRet = false; break; } // ...set up the parameters to createthread... temp->strInput = strInput; temp->command = *i; // ...run it in a new thread... CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)CommandOnThread, temp, NULL, NULL); // ...and don't check any more commands. bRet = false; break; } } }
870,138
978,112
Statically linked unmanaged libs and C++ CLR
Is it possible to use to use libs compiled with /MT in C++ CLR? It throws me either a ton of LNK2022 "metadata operation failed (8013118D)" errors (if I use /MD in the CLR project) or " '/MT' and '/clr:pure' command-line options are incompatible" if I use /MT. What do I need to change in the library? The library is mine, but it includes several third party static libs.
LNK2022 are a pain to pinpoint. It usually means one of your module's configuration affecting structure layout is different from the others. Check for the following usual causes: Make sure all your projects are using the same runtime library (/MDd or /MD) for your current solution configuration. If one project is using Debug while others are using Release or vice-versa, you will get LNK2022 errors. Make sure all your projects are using the same structure member alignment. Pay special attention if one project is using /Zp switch. Also, make sure you dont use #pragma pack(n) conditionally. You can use /d1reportSingleClassLayout_your-class-name_ (without space) to get information about the problematic class' layout. For more information see : Diagnosing Hidden ODR Violations in Visual C++
870,167
873,161
in windows, how to have non-blocking stdin that is a redirected pipe?
I have a Windows C program that gets its data through a redirected stdin pipe, sort of like this: ./some-data-generator | ./myprogram The problem is that I need to be able to read from stdin in a non-blocking manner. The reason for this is that (1) the input is a data stream and there is no EOF and (2) the program needs to be able to abort its stdin-reading thread at any time. fread blocks when there's no data, so this makes it very difficult. In Unix this is no problem, as you can set the blocking mode of a file descriptor with fcntl and O_NONBLOCK. However, fcntl doesn't exist on windows. I tried using SetNamedPipeHandleState: DWORD mode= PIPE_READMODE_BYTE|PIPE_NOWAIT; BOOL ok= SetNamedPipeHandleState(GetStdHandle(STD_INPUT_HANDLE), &mode, NULL, NULL); DWORD err= GetLastError(); but this fails with ERROR_ACCESS_DENIED (0x5). I'm not sure what else to do. Is this actually impossible (!) or is it just highly obfuscated? The resources on the net are rather sparse for this particular issue.
The order apprach, check there is input ready to read: For console mode, you can use GetNumberOfConsoleInputEvents(). For pipe redirection, you can use PeekNamedPipe()
870,173
870,224
Is there a limit on number of open files in Windows
I'm opening lots of files with fopen() in VC++ but after a while it fails. Is there a limit to the number of files you can open simultaneously?
The C run-time libraries have a 512 limit for the number of files that can be open at any one time. Attempting to open more than the maximum number of file descriptors or file streams causes program failure. Use _setmaxstdio to change this number. More information about this can be read here Also you may have to check if your version of windows supports the upper limit you are trying to set with _setmaxstdio. For more information on _setmaxstdio check here Information on the subject corresponding to VS 2015 can be found here
870,225
871,147
Overview rpg tiled space
I'm trying to make it where the character is in a tile and when they move up or down it moves to the next tile but I'm not sure how to do that. Right now, I have it set up where the character moves by pixels but I want it to move by 1 square. The code right now is this, and it works, but it's glitchy in pixel mode. I believe if it was by blocks it might work better but I might change it anyway. float spritewidth = sprite->stretchX; float spriteheight = sprite->stretchY; float bushwidth = bush->stretchX; float bushheight = bush->stretchY; //Basic border collision if (sprite->x <= 0) sprite->x = 0; if (sprite->y <= 0) sprite->y = 0; if (sprite->x >= 455) sprite->x = 455; if (sprite->y >= 237) sprite->y = 237; if ( (sprite->x + spritewidth > bush->x) && (sprite->x < bush->x + bushwidth) && (sprite->y + spriteheight > bush->y) && (sprite->y < bush->y + bushheight) ) { bushcol = 1; } else { bushcol = 0; } if (osl_keys->held.down) { if (bushcol == 1) { sprite->y = bush->y - spriteheight - 3; bushcol = 0; } else { bushcol = 0; sprite->y += 3; } } if (osl_keys->held.up) { if (bushcol == 1) { sprite->y = bush->y + bushheight + 3; bushcol = 0; } else { bushcol = 0; sprite->y -= 3; } } if (osl_keys->held.right) { if (bushcol == 1) { sprite->x = bush->x - spritewidth - 3; bushcol = 0; } else { bushcol = 0; sprite->x += 3;} } if (osl_keys->held.left) { if (bushcol == 1) { sprite->x = bush->x + bushwidth + 3; bushcol = 0; } else { bushcol = 0; sprite->x -= 3; } }
If you want the character to move one tile/square/block at a time, just move the sprite the number of pixels the tile is wide (or tall). const int tile_width = 32; // or something // and then sprite->x += tile_width;
870,441
870,643
How would I go about making an efficient key value store (e.g. memcache) / simple database?
For a few projects I'm working on I need a persistent key value store (something akin to memcache). It would ideally run as a server; it needs to be really efficient. I'm aware that memcachedb exists, but I'd like to have a go at writing it myself as there's going to be a lot of custom functionality that I'll need to include later on. I'll probably be writing this in C++ (or possibly C or Java if there is a good reason to do so). Should I be looking at database implementation (B-trees, indexes, etc.) or is that unnecessary for this kind of job? What would be a good way of storing most of the content on disk, but being able to access it quickly, utilising memory for caching? Thanks.
There are lots of key-value stores, from the tried and true BDB to the hip Tockyo Cabinet. If you must implement your own, i'd recommend to check Varnish sources, especially the Architecture page.
870,469
870,596
Is there a tool for cross platform continuous integration (c++ Win32 and linux)
I looked at a couple other questions on SO - and not really sure they answer this question. We are building C++ applications for Win32 and Linux. Right now we have some scripts (bat files for win32) that run on a schedule to do builds. We'd like to have CI for our projects, but I'd like to have only one CI server that handles building on both platforms. Integration with SVN is important. Is it possible to have one configuration/one CI product/server do this? Has anyone done this successfully? Bamboo looks like it might solve our needs, but I hate to jump into an expenditure like that as a bootstrapped startup if we can avoid the cost.
You might want to have a go at Hudson or Jenkins . Though primarily for Java-based projects, you could tweak them to suit your needs. They integrate with SVN smoothly, plus you could use the muti-step build feature to call your (existing) batch files, and process further.
870,474
870,514
Burn CD/DVD from C++ program
I need to burn CD/DVD disks from my C++ program. Can you recommend me a method? Edit: The platform is Windows.
On Windows, I have previously used the IMAPI2 interface very successfully. This site gives a really good set of sample code for this. You may need to extensively modify the code for your implementation, but it works, and works well. One thing about the IMAPI2 interface; it's what you pretty much need to use if you're going to be writing to DVDs, as previous iterations of the IMAPI interface had inconsistent handling of writing to DVDs.
870,878
888,829
Why is iplRotate() not giving me correct results?
sigh I'm sorry to say that I'm using Intel IPL (Image Processing Library) in some image processing code I'm working on. This is the tale of my struggle with getting my images to rotate correctly. I have a source image. It has a size (w, h) which is not necessarily square. It is going to be rotated by angle theta. I've calculated the output size required to fit an image of size (w, h) rotated by angle theta. This size is (dw, dh). I've allocated a destination buffer with that size. I want to rotate the source image by angle theta about the source image's center (w/2, h/2) and have that rotated image be centered in my destination buffer. iplRotate() takes 2 shift parameters, xShift and yShift, which indicate the distance the image should be shifted along the x and y axis after the rotate is performed. The problem is I cannot get iplRotate to center the rotated image in the destination image. It's always off center. My best guess for what xShift and yShift should be is the following: xShift = dw - w yShift = dh - h But this doesn't work, and I'm not sure what else to do to calculate xShift and yShift. Does anyone have any suggestions for how to use iplRotate to do what I want? One last bit of info: I've attempted to use iplGetRotateShift() to calculate xShift and yShift, again, to no avail. I would imagine that this would work: iplGetRotateShift(dw / 2.0, dh / 2.0, theta, &xShift, &yShift); But it does not. Edit: I rewrote the code using Intel IPP 6.0 instead of IPL and I'm seeing identical wrong results. I can't imagine that Intel got rotation wrong in 2 different libraries, so I must be doing something wrong. Edit: I tried the following (IPP) code that Dani van der Meer suggested: xShift = (dw - w) / 2.0; yShift = (dh - h) / 2.0; ippiAddRotateShift(w / 2.0, h / 2.0, angle, &xShift, &yShift); Unfortunately, still no luck. That does not work either.
When using iplGetRotateShift you need to specify the center of rotation in the source image. This will work well if the size of the source and destination image is the same. In your case you want an extra shift to center the image in your destination image: xShift = (dw - w) / 2.0; yShift = (dh - h) / 2.0; To combine the two shift you need to use ippiAddRotateShift instead of ippiGetRotateShift. Note: These functions refer to the IPP library version 5.3 (the version I have). I am not sure that AddRotateShift is available in IPL. But you mentioned in the question that you tried the same using IPP, so hopefully you can use IPP instead of IPL. You get something like this xShift = (dw - w) / 2.0; yShift = (dh - h) / 2.0; ippiAddRotateShift(w / 2.0, h / 2.0, angle, &xShift, &yShift); If you use these shifts in the call to ippiRotate the image should be centered in the destination image. I hope this helps. EDIT: Here is the code I used to test (the change from w to dw and h to dh and the rotation angle are just random): //Ipp8u* dst_p; Initialized somewhere else in the code //Ipp8u* src_p; Initialized somewhere else in the code int w = 1032; int h = 778; int dw = w - 40; // -40 is just a random change int dh = h + 200; // 200 is just a random change int src_step = w * 3; int dst_step = dw * 3; IppiSize src_size = { w, h }; IppiRect src_roi = { 0, 0, w, h }; IppiRect dst_rect = { 0, 0, dw, dh }; double xShift = ((double)dw - (double)w) / 2.0; double yShift = ((double)dh - (double)h) / 2.0; ippiAddRotateShift((double)w / 2, (double)h / 2, 37.0, &xShift, &yShift); ippiRotate_8u_C3R(src_p, src_size, src_step, src_roi, dst_p, dst_step, dst_rect, 37.0, xShift, yShift, IPPI_INTER_NN);
871,264
871,280
What does "operator = must be a non-static member" mean?
I'm in the process of creating a double-linked list, and have overloaded the operator= to make on list equal another: template<class T> void operator=(const list<T>& lst) { clear(); copy(lst); return; } but I get this error when I try to compile: container_def.h(74) : error C2801: 'operator =' must be a non-static member Also, if it helps, line 74 is the last line of the definition, with the "}".
Exactly what it says: operator overloads must be member functions. (declared inside the class) template<class T> void list<T>::operator=(const list<T>& rhs) { ... } Also, it's probably a good idea to return the LHS from = so you can chain it (like a = b = c) - so make it list<T>& list<T>::operator=....
871,267
871,510
How do you transfer ownership of an element of boost::ptr_vector?
#include <boost/ptr_container/ptr_vector.hpp> #include <iostream> using namespace std; using namespace boost; struct A { ~A() { cout << "deleted " << (void*)this << endl; } }; int main() { ptr_vector<A> v; v.push_back(new A); A *temp = &v.front(); v.release(v.begin()); delete temp; return 0; } outputs: deleted 0x300300 deleted 0x300300 c(6832) malloc: *** error for object 0x300300: double free
ptr_vector<A>::release returns a ptr_vector<A>::auto_type, which is a kind of light-weight smart pointer in that when an auto_type item goes out of scope, the thing it points to is automatically deleted. To recover a raw pointer to the thing, and keep it from being deleted by the auto_ptr that's holding it, you need to call release on that too: int main() { ptr_vector<A> v; v.push_back(new A); A *temp=v.release(v.begin()).release(); delete temp; return 0; } The first release tells the ptr_vector to give it up; the second tells the auto_ptr to give it up too.
871,328
871,353
Visual Studio: how do I have the debugger stop when a member variable is modified?
I have program that has a variable that should never change. However, somehow, it is being changed. Is there a way to have the debugger stop when that particular member variable is modified?
Set a data breakpoint to stop execution whenever some variable changes. Break on the initialization of your variable, or someplace where your variable is visible - you need to be able get its address in memory. Then, from the menus choose Debug -> New Breakpoint -> New Data Breakpoint. Enter "&var" (with var replaced by the name of your variable.) This will break into the debugger on the exact line of code that is modifying your variable. More documentation here: http://msdn.microsoft.com/en-us/library/350dyxd0.aspx
871,336
871,358
is there a way to combine Qt-Creator + Boost Library?
I was wondering if there was a way to use the boost library in Qt-creator (the IDE version of Qt). Thanks, A.
I'm pretty sure Qt Creator doesn't require the use of Qt in your application. If you don't want to link to any Qt libraries, or run MOC on any header files (which you only need to do for subclasses of QObject), then just do QT -= core gui (to get rid of Qt libraries from the link command. Perhaps QT = would work, too), and don't specify any HEADERS. Good luck, post back if it works.
871,354
887,999
Adding the ! operator and sqrt(), pow(), etc. to a calculator example application
I'm doing the exercises in Stroustrup's new book "Programming Principles and Practice Using C++" and was wondering if anyone on Stack Overflow has done them and is willing to share the knowledge? Specifically about the calculator that's developed in Chap 6 and 7. For example, the questions about adding the ! operator and sqrt(), pow(), etc. I have done these, but I don't know if the solution I have is the "good" way of doing things, and there are no published solutions on Bjarne's website. I'd like to know if I am going down the right track. Maybe we can make a wiki for the exercises? Basically I have a token parser. It reads a char at a time from cin. It's meant to tokenise expressions like 5*3+1 and it works great for that. One of the exercises is to add a sqrt() function. So I modified the tokenising code to detect "sqrt(" and then return a Token object representing sqrt. In this case I use the char 's'. Is this how others would do it? What if I need to implement sin()? The case statement would get messy. char ch; cin >> ch; // Note that >> skips whitespace (space, newline, tab, etc.) switch (ch) { case ';': // For "print" case 'q': // For "quit" case '(': case ')': case '+': case '-': case '*': case '/': case '!': return Token(ch); // Let each character represent itself case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { cin.putback(ch); // Put digit back into the input stream double val; cin >> val; // Read a floating-point number return Token('8', val); // Let '8' represent "a number" } case 's': { char q, r, t, br; cin >> q >> r >> t >> br; if (q == 'q' && r == 'r' && t == 't' && br == '(') { cin.putback('('); // Put back the bracket return Token('s'); // Let 's' represent sqrt } } default: error("Bad token"); }
There are a few solutions posted on Stroustrup - Programming and more will be coming over time. Try solving exercises only with the language features and the library facilities presented so far in the book -- real novice users can't do anything else. Then return later to see how a solution can be improved.
871,423
871,614
Cross-Platform way to get CPU/Memory utilization
Looking for a library or a fairly cross platform method to get CPU utilization, memory utilization, etc in C/C++. Something OTHER than getrusage(), I need for entire system, not one process. I've checked around, but haven't found much. I really need it on Linux, Mac Os X, and Windows, but if there's a solution for *nix systems (including OS X) but not Windows, I can work around that. If all else fails, then ANY methods to do this on ANY of the above platforms would be good to know, and I can figure out how to package them myself! Thanks
The cross platform framework ACE has a wrapper for getrusage that should work on most if not all supported platforms.
871,435
871,794
Odd/Incorrect sem_getvalue Semaphore Behavior on OS X
I have some very basic semaphore code that works great on Linux, but cannot for the life of me get it to run properly on OS X... It returns the oddest of results... #include <iostream> #include <fcntl.h> #include <stdio.h> #include <semaphore.h> int main() { sem_t* test; test = sem_open("test", O_CREAT, 0, 1); int value; sem_getvalue(test, &value); printf("Semaphore initialized to %d\n", value); } Compiling this on OS X with g++ returns the following output: iQudsi:Desktop mqudsi$ g++ test.cpp iQudsi:Desktop mqudsi$ ./a.out Semaphore initialized to -1881139893 Whereas on Ubuntu, I get the decidedly more-sane result: iQudsi: Desktop mqudsi$ g++ test.cpp -lrt iQudsi:Desktop mqudsi$ ./a.out Semaphore initialized to 1 I've been at this for 3 hours straight, and cannot figure out why OS X is returning such bizarre results... I've tried using file paths as the semaphore name, it didn't make a difference. I'd appreciate any help I could get.
$ g++ sem-testing.cc -Wall $ ./a.out sem_getvalue: Function not implemented $ man sem_getvalue No manual entry for sem_getvalue You are using a function that is not currently implemented in Mac OS X, and the integer you are printing out contains the default data that the integer was initialised with which was probably random data that was still in memory. Had you zero'd it out, by setting it with int value = 0; you might have caught this mistake sooner. This is the code I used (thanks to bdonlan): #include <iostream> #include <fcntl.h> #include <stdio.h> #include <semaphore.h> int main() { sem_t* test; test = sem_open("test", O_CREAT, 0, 1); if (test == SEM_FAILED) { perror("sem_open"); return 1; } int value; if (sem_getvalue(test, &value)) { perror("sem_getvalue"); return 1; } printf("Semaphore initialized to %d\n", value); }
871,444
871,455
Is it possible to create a "friend class" in C++?
I know it's possible to create a friend function in C++: class box { friend void add(int num); private: int contents; }; void add(int num) { box::contents = num; return; } But is there a way to create friend classes? NB: I know there are probably a lot of errors in this code, I don't use friend functions and am still pretty new to the language; if there are any, please tell me.
Yup - inside the declaration of class Box, do friend class SomeOtherClass; All member functions of SomeOtherClass will be able to access the contents member (and any other private members) of any Box.
871,475
871,487
Is it possible to declare a class without implementing it? (C++)
I know the questions seems ambiguous, but I couldn't think of any other way to put it, but, Is it possible to do something like this: #include<iostream> class wsx; class wsx { public: wsx(); } wsx::wsx() { std::cout<<"WSX"; } ?
Yes, that is possible. The following just declares wsx class wsx; That kind of declaration is called a forward declaration, because it's needed when two classes refer to each other: class A; class B { A * a; }; class A { B * b; }; One of them needs to be forward declared then.
871,504
871,506
What do the Items on the properties tab of MSVC++ mean?
I was playing around with my MSVC++ compiler, and the properties tab for my point class said: IsAbstract - false IsInjected - false IsManaged - false IsSealed - false IsTemplate - false IsValue - false What do these mean, and why were all of them greyed out except IsAbstract and IsSealed?
A sealed class is one that you cannot inherit. I assume IsSealed - false means that you can inherit from it.
871,574
896,655
construct two shared_ptr objects from the same pointer
I have a problem from "The C++ Standard Library Extensions": Exercise 6 I said in Section 2.4.2 that you shouldn't construct two shared_ptr objects from the same pointer. The danger is that both shared_ptr objects or their progeny will eventually try to delete the resource, and that usually leads to trouble. In fact, you can do this if you're careful. It's not particularly useful, but write a program that constructs two shared_ptr objects from the same pointer and deletes the resource only once. below is my answer: template <typename T> void nonsence(T*){} struct SX { int data; SX(int i = 0) : data(i) { cout << "SX" << endl; } ~SX() { cout << "~SX" << endl; } }; int main(int argc, char **argv) { SX* psx=new SX; shared_ptr<SX> sp1(psx),sp2(psx,nonsence<SX>); cout<<sp1.use_count()<<endl; return 0; } but I don't think it is a good solution--because i don't want solving it by use constructor. can anyone give me a better one? thx, forgive my bad english.
I got the "STANDARD" answer from boost doc : http://www.boost.org/doc/libs/1%5F38%5F0/libs/smart%5Fptr/sp%5Ftechniques.html#another_sp
871,579
871,595
Where is this code dereferencing an invalid iterator? (C++)
I have a loop for(aI = antiviral_data.begin(); aI != antiviral_data.end();) { for(vI = viral_data.begin(); vI != viral_data.end();) { if((*aI)->x == (*vI)->x && (*aI)->y == (*vI)->y) { vI = viral_data.erase(vI); aI = antiviral_data.erase(aI); } else { vI++; aI++; } } } But when ever antiviral_data contains an item, I get an error "vector iterator not dereferencable." Why am I geting this error and where am I dereferencing an invalid iterator? NB: So far th error only occurs when the if() statement is false. I don't know what happens if the if() statement is true.
What are the sizes of the vectors? If viral_data has more elements then antiviral_data, then, since you increment aI and vI at the same rate, aI would go out of bounds before the vI loop would end. Take a short example here: for(int i = 0; i < 5;) { for(int j = 0; j < 10;) { i++; j++; } } If you go over the for loops, you'll notice that the inner loop will not end until both j and i are 10, but according to your outer loop, i should not be more then 5. You'll want to increment i (or in your case, aI) in the outer loop like so: for(int i = 0; i < 5;) { for(int j = 0; j < 10;) { j++; } i++; }
871,644
871,972
Eclipse Ganymede and MinGW in Windows
I'm trying to get eclipse to work with MinGW. I've done the following: Downloaded CDT for eclipse. Installed MinGW. Added C:\MinGW\bin to my path. Opening a command prompt (CMD) and typing g++ or alike works fine. I run eclipse, create a "New C++ Project", and only get the option saying "other toolchains". There's a MILLION tutorials out there saying eclipse should identify MinGW on its own. It doesn't, and I don't know what to do. I've tried reinstalling everying in just about every order posible. Still no luck. I've also noted some tutorials say something about creating a "Managed C++ Project". I've no such option, all I get is "C++ Project" and "C Project" edit: I have eclipse ganymede, windows x86_64, version 3.4.2 http://download.eclipse.org/eclipse/downloads/drops/R-3.4.2-200902111700/index.php Running the "Eclipse IDE for C/C++ developers" fails, since there's no x64 version for windows. The x86 version requires x86 JAVA installed as well, and installing two versions of java, gave nothing but trouble in the past.
The distinction between managed make projects and makefile project was removed in CDT 4.x, I think. Now there is only one type of project, but you can select different builders. CDT includes an internal builder which does not use makefiles and another one which does. First, save yourself the effort of "reinstalling in every order possible". That is also known as trial-and-error, and will only make you more frustrated. Apply the normal problem-solving skills you have as a programmer. Given that you have MinGW installed, what happens if you download "Eclipse IDE for C/C++ developers", start eclipse.exe, and try to create a C++-project with a MinGW toolchain? EDIT: remember: the key in getting help with problems like these is to produce a minimal example which fails. Also, it would help if you provided URLs to the packages you installed (MinGW, Eclipse, etc.). EDIT: I just installed CDT using the Ganymede update site, downloaded and installed MinGW from here, and restarted Eclipse, and everything worked fine. I know that doesn't help you, but it does prove that the toolchain detection isn't completely broken. Something is weird on your side.
871,666
871,670
Why is it better to use '!=" than '<' in a vector loop? (C++)
Why is it better to use '!=" than '<' in a vector loop? I just can't see the difference.
Because you're using iterators, and it'll make the loop look exactly the same as other containers, should you choose to switch to other container types, such as set, list, unordered_set, etc. where < has no meaning.
871,888
872,000
Is there any temporary created while returning an object from function?
when ever a function has a object passed by value it uses either copy constructor or bit wise copy to create a temporary to place on stack to use inside the function,How about some object returned from function ? //just a sample code to support the qn rnObj somefunction() { return rnObj(); } and also explain how the return value is taken to the called function.
As can be judged by the other answers - the compiler can optimize this. A concrete example generated using MSVC, to explain how this is possible (as asked in one of the comments) - Take a class - class AClass { public: AClass( int Data1, int Data2, int Data3 ); int GetData1(); private: int Data1; int Data2; int Data3; }; With the following trivial implementation - AClass::AClass( int Data1, int Data2, int Data3 ) { this->Data1 = Data1; this->Data2 = Data2; this->Data3 = Data3; } int AClass::GetData1() { return Data1; } And the following calling code - AClass Func( int Data1, int Data2, int Data3 ) { return AClass( Data1, Data2, Data3 ); } int main() { AClass TheClass = Func( 10, 20, 30 ); printf( "%d", TheClass.GetData1() ); } (the printf() added just to make sure the compiler doesn't optimize everything away...). In a non-optimized code, we would expect Func() to create a local AClass on its stack, construct it there and copy it as its return variable. However, the generated assembly actually looks like (removing unneeded lines) - _TEXT SEGMENT ___$ReturnUdt$ = 8 ; size = 4 _Data1$ = 12 ; size = 4 _Data2$ = 16 ; size = 4 _Data3$ = 20 ; size = 4 mov eax, DWORD PTR _Data3$[esp-4] mov ecx, DWORD PTR _Data2$[esp-4] mov edx, DWORD PTR _Data1$[esp-4] push esi mov esi, DWORD PTR ___$ReturnUdt$[esp] push eax push ecx push edx mov ecx, esi call ??0AClass@@QAE@HHH@Z ; AClass::AClass mov eax, esi pop esi ret 0 The 3 function variables are extracted from the stack and placed into eax, ecx and edx. Another forth value is placed into esi (and passed on to ecx). The constructor is called with the 3 parameters on the stack, and ecx still containing the forth value. Let's take a look in the constructor - _TEXT SEGMENT _Data1$ = 8 ; size = 4 _Data2$ = 12 ; size = 4 _Data3$ = 16 ; size = 4 mov edx, DWORD PTR _Data2$[esp-4] mov eax, ecx mov ecx, DWORD PTR _Data1$[esp-4] mov DWORD PTR [eax], ecx mov ecx, DWORD PTR _Data3$[esp-4] mov DWORD PTR [eax+4], edx mov DWORD PTR [eax+8], ecx ret 12 ; 0000000cH The 3 constructor parameters are read into offsets of eax - eax being a copy of ecx, the forth parameter from the call above. So, the constructor builts the object where it is told to - the forth parameter of Func(). And, you guessed it, the forth parameter of Func() is actually the real single place in the entire program where a constructed AClass exists. Let's look at the relevant part of main() - _TEXT SEGMENT _TheClass$ = -12 ; size = 12 _main PROC sub esp, 12 push 30 push 20 lea eax, DWORD PTR _TheClass$[esp+20] push 10 push eax call ?Func@@YA?AVAClass@@HHH@Z ; Func 12 bytes are reserved for an AClass and the three arguments to Func() are passed, along with the forth one - pointing to those 12 bytes. This is a specific example with a specific compiler. Other compilers do this differently. But that's the spirit of things.
871,917
872,032
Web access authentication in C++?
I'm trying to write a simple GUI application using Qt framework. The purpose of this app is to retrieve data from my isp and parse them for presentation. How do i authenticate my user/password with the webserver and retrieve the html page in question? Are there any utility libs that make this task trivial? I figure i need to interact with the server php script and simulate a form input somehow. Am i on the right track?
The way to authenticate depends completely on the authentication method used by the server. If it's some form to log in you need to retrieve that and send the correct data to the forms action target (usually as POST request). You could do this by constructing your request using QHttpRequestHeader and then simply sending it to the server. If you even know about the form you might even not need to retrieve the login page. If the website uses HTTP authentication you should be able using QAuthenticator.
871,952
1,964,446
GCC build problem (#include_next limits.h)
When i try to $ make depend -f gcc.mak a middleware on my Ubuntu machine I get this /usr/include/../include/limits.h:125:26: error: no include path in which to search for limits.h This is the contents around limits.h:125: /* Get the compiler's limits.h, which defines almost all the ISO constants. We put this #include_next outside the double inclusion check because it should be possible to include this file more than once and still get the definitions from gcc's header. */ #if defined __GNUC__ && !defined _GCC_LIMITS_H_ /* `_GCC_LIMITS_H_' is what GCC's file defines. */ # include_next <limits.h> #endif I tried setting $ export INCLUDE=/usr/lib/gcc/x86_64-linux-gnu/4.3/include-fixed/ $ export C_INCLUDE_PATH=/usr/lib/gcc/x86_64-linux-gnu/4.3/include-fixed/ $ export CPLUS_INCLUDE_PATH=/usr/lib/gcc/x86_64-linux-gnu/4.3/include-fixed/ (which is where I found another limits.h on my system). I already have libc6-dev installed, could it be that its limits.h has been overwritten by another package? Do I need another -dev package? Or is an environment variable required; perhaps this could be circumvented in some other way?
the package that you need is glibc.
871,982
872,451
Making references to classes you havn't #include'd (C++)
I'm playing around with Box2D for fun right now, and after getting the hang of some of the concepts I decided to make my own test for the test bed (Box2D comes with a set of examples and has a simple extendable Test class for making your own tests). I started by grabbing one of the other tests, ripping out everything but the function signatures, and inserting some of my own code. However, there's no #includes to any of Box2D's libraries so it doesn't compile (but only my file errors, remove my test file and it compiles fine). I figured I must have accidentally deleted them when I was moving stuff around, but upon checking the other test files there's no #includes anywhere to be seen. Each one of the files uses datastructures and functions that are declared in various Box2D header files. How does this compile at all? For example, this is one of the prepackaged tests stripped of the constructor body and some comments at the top: #ifndef CHAIN_H #define CHAIN_H class Chain : public Test { public: Chain() { // Since b2BodyDef isn't defined in this file, and no // other files are included how does this even compile? b2BodyDef bd; // rest of constructor... } static Test* Create() { return new Chain; } }; #endif
Each cpp file gets compiled. Before it is compiled though, the preprocessor runs. The preprocesser deals with all of the keywords starting with #, like #include. The preprocessor takes the text of any #include'd files and replaces the #include statement with all the text in the file it includes. If the #include'd file includes other files, their text is fetched too. After the preprocessor has run, you end up with a great big text file called a translation unit. This is what gets compiled. So.. probably as other people have said. The cpp file somewhere includes the Box2D stuff before it includes chain.h, so everything works. There is often an option on the compiler or the project settings that will get the preprocessor to create a file with all of the text in the translation unit so you can see it. This is sometimes useful to track down errors with #includes or macros.
872,087
872,111
Templates and Syntax
Working on an algorithm to look at a STL container of STL strings (or other strings, making it general) Basically it loops through something like a std::list and returns the length of the longest beginning in common. It's for processing lists of files, like this: C:\Windows\System32\Stuff.exe C:\Windows\Things\InHere.txt C:\Windows\Foo\Bar.txt This should return 11, because "C:\Windows\" is in common. Never written a templatized function before, and my compiler is complaining. Here's my code: Header: // longestBegin.h -- Longest beginning subsequence solver template <typename SequenceSequenceT, typename SequenceT, typename T > size_t longestBegin(InputIterator firstCandidates, InputIterator lastCandidates); Implementation: // longestBegin.cpp -- Longest beginning subsequence solver #include <stdafx.h> template <typename SequenceSequenceT, typename SequenceT, typename T > size_t longestBegin(InputIterator firstCandidates, InputIterator lastCandidates) { SequenceT firstString = *firstCandidates; size_t longestValue = firstString.length(); firstCandidates++; for(size_t idx = 0; idx < longestValue; idx++) { T curChar = firstString[idx]; for(InputIterator curCandidate = firstCandidates;curCandidate != lastCandidates; curCandidate++) { if ((*curCandidate)[idx] != curChar) return idx - 1; } } return longestValue; } I have a funny feeling I'm missing something fundamental here...... The compiler bombs with the following error: error C2998: 'size_t longestBegin' : cannot be a template definition Any ideas? Thanks! Billy3
Your parameter names in the template line need to include any types of function parameters or return types. This means that you need to mention InputIterator in your template parameter list. Try changing your function declaration to: template <typename InputIterator> size_t longestBegin(InputIterator firstCandidates, InputIterator lastCandidates) Your next problem is: how does the compiler know what SequenceT is? The answer is that it's the result of dereferencing an InputIterator. Iterators that aren't pointers have a nested typedef called reference, which is just what you need here. Add this to the start of your function so the compiler knows what SequenceT is: template <typename InputIterator> size_t longestBegin(InputIterator firstCandidates, InputIterator lastCandidates) { typedef typename InputIterator::reference SequenceT; [etc.] You could have kept SequenceT as a template parameter, but then the compiler couldn't guess what it is from looking at the arguments, and you'd have to call your function by typing e.g. longestBegin<string>(arguments), which isn't necessary here. Also, you'll notice that this doesn't work if InputIterator is a pointer -- pointers don't have nested typedefs. So you can use a special struct called std::iterator_traits from the <iterator> standard header that can sort out these problems for you: //(At the top of your file) #include <iterator> template <typename InputIterator> size_t longestBegin(InputIterator firstCandidates, InputIterator lastCandidates) { typedef typename std::iterator_traits<InputIterator>::reference SequenceT; [etc.] Finally, unless the first string is always the longest, you could end up accessing a string past the end of its array inside the second for loop. You can check the length of the string before you access it: //(At the top of your file) #include <iterator> template <typename InputIterator> size_t longestBegin(InputIterator firstCandidates, InputIterator lastCandidates) { typedef typename std::iterator_traits<InputIterator>::reference SequenceT; SequenceT firstString = *firstCandidates; size_t longestValue = firstString.length(); firstCandidates++; for(size_t idx = 0; idx < longestValue; idx++) { T curChar = firstString[idx]; for(InputIterator curCandidate = firstCandidates;curCandidate != lastCandidates; curCandidate++) { if (curCandidate->size() >= idx || (*curCandidate)[idx] != curChar) return idx - 1; } } return longestValue; } Also note that the function returns (size_t)(-1) if there is no common prefix.
872,143
872,171
How to force destruction order of static objects in different dlls?
I have 2 static objects in 2 different dlls: An object Resources (which is a singleton), and an object User. Object User in its destructor has to access object Resources. How can I force object Resources not to be destructed before object User?
Global objects are destroyed when their corresponding DLL is unloaded. So as your 'User' dll is probably dependent of your 'Resource' dll, you are in trouble: 'resource' will always be destroyed before 'user'. I'm also interested by a good answer to this question, if one exist. Until now, I'm using a cleanup function that must be called by application before it quits, and I only keep harmless code in destructors.
872,354
872,485
Getting the reference of a template iterator reference
I need to get a reference to an iterator of a reference. However, my compiler is choking on this code: template <typename InputIterator> size_t iLongestBegin(InputIterator first, InputIterator last) { typedef typename std::iterator_traits<InputIterator>::reference SequenceT; //Problem is next line typedef typename std::iterator_traits<typename SequenceT::iterator>::reference T; for(size_t idx; idx < first->length(); idx++) { T curChar = (*first)[idx]; for (InputIterator cur = first; cur != last; cur++) { if (cur->length() < idx) return idx; if (_tolower(cur->at(idx)) != _tolower(curChar)) return idx; } } return first->length(); } Any ideas on how to fix it? The error is error C2825: 'SequenceT': must be a class or namespace when followed by '::'
Actually, just solved it :) Problem is that SequenceT is a reference, not a type. Since you can't generally take the address of a reference type, the compiler won't generate iterators for it. I need to use value_type instead of reference: template <typename InputIterator> size_t iLongestBegin(InputIterator first, InputIterator last) { typedef typename std::iterator_traits<InputIterator>::reference SequenceT; typedef typename std::iterator_traits<std::iterator_traits<InputIterator>::value_type::iterator>::reference T; for(size_t idx; idx < first->length(); idx++) { typename T curChar = (*first)[idx]; for (InputIterator cur = first; cur != last; cur++) { if (cur->length() < idx) return idx; if (_tolower(cur->at(idx)) != _tolower(curChar)) return idx; } } return first->length(); }
872,414
874,065
Compiling C++ using -pthreads for Openwrt Linux-Get segmentation fault
I´m pretty new to programming in C++ and I´m using pthreads. I´m cross compiling my code for OpenWRT but for some reason I get segmentation fault when I run the program on my board but it runs fine on my PC. I suspect that the error occurs in the linking stage of the compilation because I tried a small C program and that worked fine. Also if I change the name of the file to .cpp and compile it with g++ it also works. #include <pthread.h> #include <stdio.h> #include <stdlib.h> void *run(void *dummyPtr) { printf("I am a thread...\n"); return NULL; } int main(int argc, char **argv) { printf("Main start...\n"); pthread_t connector; pthread_create(&connector, NULL, run, NULL); printf("Main end...\n"); return 0; } The output from the eclipse compiler: **** Build of configuration Release for project ThreadTest **** make all Building file: ../src/ThreadTest.cpp Invoking: GCC C++ Compiler mipsel-linux-g++ -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/ThreadTest.d" -MT"src/ThreadTest.d" -o"src/ThreadTest.o" "../src/ThreadTest.cpp" -lpthread mipsel-linux-g++: -lpthread: linker input file unused because linking not done Finished building: ../src/ThreadTest.cpp Building target: ThreadTest Invoking: GCC C++ Linker mipsel-linux-g++ -o"ThreadTest" ./src/ThreadTest.o -lpthread -static Finished building target: ThreadTest Edit: Removed the old code and put in a new simpler example. This code runs if I compile it as a C program but no if I compile it as a c++ program. I´m runnig the 2.6.26.3 kernel on the board.
This could easily be due to a low memory condition. You should try to enable some form of page file and free up any other memory. Also, why -static? if your using a dynamic -lpthread, wouldn't linking the shared library be preferable? Also, it could be due to your C++ lib being mis-matched, make sure your uclibc++ is the correct version, you may also want to install ldd if you have not already. Depends on your firmware.
872,491
872,534
New unicode characters in C++0x
I'm buiding an API that allows me to fetch strings in various encodings, including utf8, utf16, utf32 and wchar_t (that may be utf32 or utf16 according to OS). New C++ standard had introduced new types char16_t and char32_t that do not have this sizeof ambiguity and should be used in future, so I would like to support them as well, but the question is, would they interfere with normal uint16_t, uint32_t, wchar_t types not allowing overload because they may refer to same type? class some_class { public: void set(std::string); // utf8 string void set(std::wstring); // wchar string utf16 or utf32 according // to sizeof(wchar_t) void set(std::basic_string<uint16_t>) // wchar independent utf16 string void set(std::basic_string<uint32_t>); // wchar independent utf32 string #ifdef HAVE_NEW_UNICODE_CHARRECTERS void set(std::basic_string<char16_t>) // new standard utf16 string void set(std::basic_string<char32_t>); // new standard utf32 string #endif }; So I can just write: foo.set(U"Some utf32 String"); foo.set(u"Some utf16 string"); What are the typedef of std::basic_string<char16_t> and std::basic_string<char32_t> as there is today: typedef basic_string<wchar_t> wstring. I can't find any reference. Edit: according to headers of gcc-4.4, that introduced these new types: typedef basic_string<char16_t> u16string; typedef basic_string<char32_t> u32string; I just want to make sure that this is actual standard requirement and not gcc-ism.
1) char16_t and char32_t will be distinct new types, so overloading on them will be possible. Quote from ISO/IEC JTC1 SC22 WG21 N2018: Define char16_t to be a typedef to a distinct new type, with the name _Char16_t that has the same size and representation as uint_least16_t. Likewise, define char32_t to be a typedef to a distinct new type, with the name _Char32_t that has the same size and representation as uint_least32_t. Further explanation (from a devx.com article "Prepare Yourself for the Unicode Revolution"): You're probably wondering why the _Char16_t and _Char32_t types and keywords are needed in the first place when the typedefs uint_least16_t and uint_least32_t are already available. The main problem that the new types solve is overloading. It's now possible to overload functions that take _Char16_t and _Char32_t arguments, and create specializations such as std::basic_string<_Char16_t> that are distinct from std::basic_string <wchar_t>. 2) u16string and u32string are indeed part of C++0x and not just GCC'isms, as they are mentioned in various standard draft papers. They will be included in the new <string> header. Quote from the same article: The Standard Library will also provide _Char16_t and _Char32_t typedefs, in analogy to the typedefs wstring, wcout, etc., for the following standard classes: filebuf, streambuf, streampos, streamoff, ios, istream, ostream, fstream, ifstream, ofstream, stringstream, istringstream, ostringstream, string
872,677
872,720
What are all the differences between WH_MOUSE and WH_MOUSE_LL hooks?
I've found that WH_MOUSE is not always called. Could the problem be that I'm using WH_MOUSE and not WH_MOUSE_LL? The code: class MouseHook { public: static signal<void(UINT, const MOUSEHOOKSTRUCT&)> clickEvent; static bool install() { if (isInstalled()) return true; hook = ::SetWindowsHookEx(WH_MOUSE, (HOOKPROC)&mouseProc, ::GetModuleHandle(NULL), NULL); return(hook != NULL); } static bool uninstall() { if (hook == NULL) return TRUE; bool fOk = ::UnhookWindowsHookEx(hook); hook = NULL; return fOk != FALSE; } static bool isInstalled() { return hook != NULL; } private: static LRESULT CALLBACK mouseProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode == HC_ACTION && (wParam == WM_LBUTTONDOWN || wParam == WM_NCLBUTTONDOWN || wParam == WM_RBUTTONDOWN || wParam == WM_NCRBUTTONDOWN || wParam == WM_MBUTTONDOWN || wParam == WM_NCMBUTTONDOWN )) { MOUSEHOOKSTRUCT* mhs = (MOUSEHOOKSTRUCT*) lParam; clickEvent(wParam, *mhs); } return ::CallNextHookEx(hook, nCode, wParam, lParam); } static HHOOK hook; };
The difference is in the behavior when the callback gets called. If you're using the lowlevel version you don't incur in the limitations posed by lpfn because of the way the call to your hook function is performed. Please read below for more information. Quoting from MSDN's doc for SetWindowsHookEx: lpfn [in] Pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a thread created by a different process, the lpfn parameter must point to a hook procedure in a DLL. Otherwise, lpfn can point to a hook procedure in the code associated with the current process. and from LowLevelKeyboardProc: the WH_KEYBOARD_LL hook is not injected into another process. Instead, the context switches back to the process that installed the hook and it is called in its original context. Then the context switches back to the application that generated the event.
872,846
872,869
Can this cause undefined behaviour?
I've been having big problems in reproducing and finding the cause of a bug. The occurence seems entirely random, so I suspected an uninitialized variable somewhere. But then I found this piece of code: CMyClass obj; // A obj.DoStuff(); if ( somebool ) { CMyClass obj; // B obj.DoStuff(); } obj.DoOtherStuff(); It seems as though DoOtherStuff() is either done on "B", or that B.DoStuff() sometimes actually works on A - i.e. i DoStuff() is actually called on the first obj. Could this happen? I don't think I got a compiler warning (I've fixed the code now in hoping that it might help). It seems very likely that this piece of the actual code is where the bug I'm trying to find is, but there could of course be other reasons I haven't discovered yet.
The code, as written, should work. The first call to DoStuff() and the last call to DoOtherStuff() can only be sent to A. The call to DoStuff() inside the if(somebool) { } block can only be sent to B. From the standard: 3.3.2 Local scope A name declared in a block (6.3) is local to that block. Its potential scope begins at its point of declaration (3.3.1) and ends at the end of its declarative region. And: 3.3.7 Name hiding A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class (10.2). That being said, perhaps this is not what was intended by the author of that code. If the variables have the same name, perhaps the intent is to have only one instance of that variable, and the B instance created inside the loop is a mistake. Have you gone through the logic to see if a second instance makes sense?
872,996
873,003
Immediate exit of 'while' loop in C++
How do I exit a while loop immediately without going to the end of the block? For example, while (choice != 99) { cin >> choice; if (choice == 99) //Exit here and don't get additional input cin>>gNum; } Any ideas?
Use break? while(choice!=99) { cin>>choice; if (choice==99) break; cin>>gNum; }
873,090
873,092
Do DeleteFile() Or CopyFile() throw exceptions?
I use the DeleteFile and CopyFile methods. Do these functions throw exceptions or just set errno and lastError? Do I need to surround this code with try and catch?
If you're referring to the Win32 API functions, the answer is no. No Win32 functions throw, because it is a C API.
873,101
873,177
C++ class - Increment and decrement attribute every N milliseconds
This must be an easy question but I can't find a properly answer to it. I'm coding on VS-C++. I've a custom class 'Person' with attribute 'height'. I want to call class method Grow() that starts a timer that will increment 'height' attribute every 0.5 seconds. I'll have a StopGrow() that stops the timer and Shrink() that decrements instead of increment. I really need a little push on which timer to use and how to use it within Grow() method. Other methods must be straight forward after knowing that. That's my first question here so please be kind (and warn me if I'm doing it wrong :) Forgive my English, not my first language.
Do you really need to call the code every half second to recalculate a value? For most scenarios, there is another much simpler, faster, effective way. Don't expose a height member, but use a method such as GetHeight(), which will calculate the height at the exact moment you need it. Your Grow() method would set a base height value and start time and nothing else. Then, your GetHeight() method would subtract the starting time from the current time to calculate the height "right now", when you need it. No timers needed!
873,210
873,289
Symbols (pdb) for native dll are not loaded due to post build step
I have a native release dll that is built with symbols. There is a post build step that modifies the dll. The post build step does some compression and probably appends some data. The pdb file is still valid however neither WinDbg nor Visual Studio 2008 will load the symbols for the dll after the post build step. What bits in either the pdb file or the dll do we need to modify to get either WinDbg or Visual Studio to load the symbols when it loads a dump in which our release dll is referenced? Is it filesize that matters? A checksum or hash? A timestamp? Modify the dump? or modify the pdb? modify the dll before it is shipped? (We know the pdb is valid because we are able to use it to manually get symbol names for addresses in dump callstacks that reference the released dll. It's just a total pain in the *ss do it by hand for every address in a callstack in all the threads.)
This post led me to chkmatch. On the processed dll, chkmatch shows this info: Executable: TimeDateStamp: 4a086937 Debug info: 2 ( CodeView ) TimeStamp: 4a086937 Characteristics: 0 MajorVer: 0 MinorVer: 0 Size: 123 RVA: 00380460 FileOffset: 00380460 CodeView signature: sUar Debug information file: Format: PDB 7.00 Result: unmatched (reason: incompatible debug information formats) With the same pdb against the pre-processed dll, it reports this: Executable: TimeDateStamp: 4a086937 Debug info: 2 ( CodeView ) TimeStamp: 4a086937 Characteristics: 0 MajorVer: 0 MinorVer: 0 Size: 123 RVA: 00380460 FileOffset: 00380460 CodeView format: RSDS Signature: (my guid) Age: 19 PdbFile: (my path) Debug information file: Format: PDB 7.00 Signature: (my matching guid) Age: 19 I opened up both versions of the dll and went to offset 00380460. In the original version, clear enough I see the name of the pdb, but in the post-processed version there is no pdb info at that offset. I searched for the pdb path and found the exact same block - just at a different offset. Then I did bin search for the bytes "38 00 60 04" in the original dll. Looking at the same offset in the processed dll, I found the same bytes. So I adjusted the RVA and the offset (located by matching the bytes). Bingo! Now chkmatch reports the exact same results for the processed dll as the original (aside from the RVA and FileOffset that I changed). Edit: Confirmed, now Visual Studio loads the symbols for dumps that reference the processed dll.
873,214
873,256
unistd.h read() is reading more data then being written
I'm reading/writing data off of a named pipe. On the writing side it says that it's writing a constant 110 bytes. On the Reading side for the majority of time it says that it's reading 110 bytes which is correct, but other times it says its reading 220 bytes or 330 bytes. Which is right in the fact that when I print it out it's printing out the same message two or three times in a row within the same read(). In the code below for reading am I doing something wrong with the memset to clear the char? I can't think of any other way it's reading more then is being written unless something is left over in the buffer. int fd1, numread; char bufpipe[5000]; while(1) { fd1 = open("/tmp/testPipe", O_RDONLY); numread = read(fd1,bufpipe, 5000);//->this should always be 110 if(numread > 1) { printf("READ: %i", numread); bufpipe[numread+1] = '\0'; memset(bufpipe,'\0',5001); close(fd1); } }
This: memset(bufpipe,'\0',5001); is overwriting by one byte, because you have only 5000 bytes. But the main "problem" is that read(..., 5000) will always read as much as it can up to 5000 bytes - you seem to be assuming that it will read only as much as was written in one go by the writer, which is not true. If the writer writes two packets of 110 bytes between two reads, then it's quite correct that the reader reads 220 bytes. If you need to read only a single packet at a time, you have to make your packets self-describing. So for instance, the first four bytes contain the number of bytes to follow. Then you can read a single packet by reading four bytes, converting that to an integer, then reading that number of data bytes.
873,216
873,264
Canonical form of += operator for classes
I know that it's a good idea to make as much of the interface of a class non-member non-friend as possible, and I've just realised that for my 3D vector class, 'Vector3', I can move the +=, -= and so on operators out of the class, leaving just constructors and the copy assignment operator. The question is: what should this operator look like? I've seen canonical forms of plenty of other operators and have followed their advice, but I haven't seen canonical forms of these operators. I've given what I think it should be below. The secondary question is: what are these operators even called? Arithmetic assignment operators? The (relevant) code before: class Vector3 { public: Vector3& operator+=(const Vector3& rhs); float x, y, z; }; Vector3& Vector3::operator+=(const Vector3 &rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } What I've changed it to so far: class Vector3 { public: float x, y, z; }; Vector3& operator+=(Vector3& lhs, const Vector3& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; lhs.z += rhs.z; return lhs; }
What you have looks good to me. By the way, when you come to the operator+, it is common to implement that in terms of +=. (create a copy of lhs, and then call lhs += rhs and return the result) Don't know if you're already aware of this trick, but since you're concerned about canonical ways to implement these operators, it can't hurt to mention it. :)
873,473
873,479
Is there any situation in which it would be useful or necessary to "double link" header files? (C++)
I use the term "double link" because I don't know what the actual phrase is, or if there is one, but assuming you have two headers, head1.h and head2.h, with these contents: In head1.h: #include"head2.h" //do stuff In head2.h: #include"head1.h" //do stuff I visualise it as two mirrors placed opposite each other, as it's not really an infinite loop, but some other form of getting infinity into a finite computer (but I digress). The point is, is there any situation where it would be useful or necessary to use this concept, or a variation of this concept? (ie: I suppose goto could be used as an improv break).
That's a "cyclic include" and no, it's not a desirable thing to do. your goto wouldn't help, because gotos are part of the program execution, while the #includes are interpreted during the preprocessing phase of compiling. The usual thing is to make your header files have a structure like #ifndef FOO_H #define FOO_H ... rest of the include file here #endif so they don't attempt to define the same stuff twice. Should you try it, here's what happens: bash $ gcc crecursive.c In file included from bh.h:1, from ah.h:1, from bh.h:1, from ah.h:1, ... many lines omitted from ah.h:1, from crecursive.c:2: ah.h:1:16: error: #include nested too deeply bash $
873,615
873,727
Giving C++ Application a HTTP Web Server Functionality
I have a C++ app and looking for a library that would make it a HTTP Server that's able to serve static files as well as perform very simple tasks. The only constraint is that it must be Cross-platform. What are my options. Clarify: I need a web interface for my application. This application is a background program that does other tasks. I want to provide a way so you can access http://localhost:9999/performtask or http://localhost:9999/viewstatus clarification2: something like this http://www.gnu.org/software/libmicrohttpd/
In a question which has since been deleted, I asked: I'm looking for a well-written, flexible library written in C or C++ (I'm writing my apps in C++) that can be used to embed an relatively simple HTTP server into my applications. Ultimately I will use this for application monitoring and control. There are a number of great client-side libraries (e.g. libwww, neon, curl) but I'm struggling to find a good solution for the server-side. I'm sure other folks have done this before, so I'd love to hear what folks have done and what has worked and what hasn't. I ended up choosing Mongoose.
873,658
873,659
How can I hook Windows functions in C/C++?
If I have a function foo() that windows has implemented in kernel32.dll and it always returns true, can I have my program: "bar.exe" hook/detour that Windows function and make it return false for all processes instead? So, if my svchost, for example, calls foo(), it will return false instead of true. The same action should be expected for all other processes currently running. If so, how? I guess I'm looking for a system-wide hook or something.
Take a look at Detours, it's perfect for this sort of stuff. For system-wide hooking, read this article from MSDN. First, create a DLL which handles hooking the functions. This example below hooks the socket send and receive functions. #include <windows.h> #include <detours.h> #pragma comment( lib, "Ws2_32.lib" ) #pragma comment( lib, "detours.lib" ) #pragma comment( lib, "detoured.lib" ) int ( WINAPI *Real_Send )( SOCKET s, const char *buf, int len, int flags ) = send; int ( WINAPI *Real_Recv )( SOCKET s, char *buf, int len, int flags ) = recv; int WINAPI Mine_Send( SOCKET s, const char* buf, int len, int flags ); int WINAPI Mine_Recv( SOCKET s, char *buf, int len, int flags ); int WINAPI Mine_Send( SOCKET s, const char *buf, int len, int flags ) { // .. do stuff .. return Real_Send( s, buf, len, flags ); } int WINAPI Mine_Recv( SOCKET s, char *buf, int len, int flags ) { // .. do stuff .. return Real_Recv( s, buf, len, flags ); } BOOL WINAPI DllMain( HINSTANCE, DWORD dwReason, LPVOID ) { switch ( dwReason ) { case DLL_PROCESS_ATTACH: DetourTransactionBegin(); DetourUpdateThread( GetCurrentThread() ); DetourAttach( &(PVOID &)Real_Send, Mine_Send ); DetourAttach( &(PVOID &)Real_Recv, Mine_Recv ); DetourTransactionCommit(); break; case DLL_PROCESS_DETACH: DetourTransactionBegin(); DetourUpdateThread( GetCurrentThread() ); DetourDetach( &(PVOID &)Real_Send, Mine_Send ); DetourDetach( &(PVOID &)Real_Recv, Mine_Recv ); DetourTransactionCommit(); break; } return TRUE; } Then, create a program to inject the DLL into the target application. #include <cstdio> #include <windows.h> #include <tlhelp32.h> void EnableDebugPriv() { HANDLE hToken; LUID luid; TOKEN_PRIVILEGES tkp; OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ); LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &luid ); tkp.PrivilegeCount = 1; tkp.Privileges[0].Luid = luid; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken, false, &tkp, sizeof( tkp ), NULL, NULL ); CloseHandle( hToken ); } int main( int, char *[] ) { PROCESSENTRY32 entry; entry.dwSize = sizeof( PROCESSENTRY32 ); HANDLE snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, NULL ); if ( Process32First( snapshot, &entry ) == TRUE ) { while ( Process32Next( snapshot, &entry ) == TRUE ) { if ( stricmp( entry.szExeFile, "target.exe" ) == 0 ) { EnableDebugPriv(); char dirPath[MAX_PATH]; char fullPath[MAX_PATH]; GetCurrentDirectory( MAX_PATH, dirPath ); sprintf_s( fullPath, MAX_PATH, "%s\\DllToInject.dll", dirPath ); HANDLE hProcess = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, FALSE, entry.th32ProcessID ); LPVOID libAddr = (LPVOID)GetProcAddress( GetModuleHandle( "kernel32.dll" ), "LoadLibraryA" ); LPVOID llParam = (LPVOID)VirtualAllocEx( hProcess, NULL, strlen( fullPath ), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE ); WriteProcessMemory( hProcess, llParam, fullPath, strlen( fullPath ), NULL ); CreateRemoteThread( hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)libAddr, llParam, NULL, NULL ); CloseHandle( hProcess ); } } } CloseHandle( snapshot ); return 0; } This should be more than enough to get you started!
873,676
873,695
disable folder virtualization in windows
I currently have a c++ application that gets built on xp and windows vista/7 virtualize some of the paths which i dont want it to do. Some sites says to add this to manifest file: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly> How ever that is for .net applications. How can i do this under c++ for visual studio 2005? . Edit: I needed to download the vista sdk and include its bin path in visual studio before this would work.
Exactly the same. Create a file with the given context and add that file in your project settings: Manifest Tool > Input and Output > Additional Manifest Files Done!
873,715
873,725
c++ sort with structs
I am having a hard time with this problem which requires a sort of customer names, customer ids, and finally amount due. I have the whole program figured, but cannot figure out the last prototype needed to do the sorting. i have a struct called Customers, and i will provide the int main() part also. I just need any help to gt started on the prototype SortData(). struct Customers { string Name; string Id; float OrderAmount; float Tax; float AmountDue; }; const int MAX_CUSTOMERS = 1000; bool MoreCustomers(int); Customers GetCustomerData(); void OutputResults(Customers [], int); void SortData(const int, const int, Customers []); int main() { Customers c[MAX_CUSTOMERS]; int Count = 0; do { c[Count++] = GetCustomerData(); } while (MoreCustomers(Count)); for (int i = 0; i < Count; i++) { c[i].Tax = 0.05f * c[i].OrderAmount; c[i].AmountDue = c[i].OrderAmount + c[i].Tax; } SortData(0, Count, c); //0:Sorts by customer name OutputResults(c, Count); GeneralSort(1, Count, c); //1:Sorts by ID OutputResults(c, Count); GeneralSort(2, Count, c); //2: Sorts by amount due OutputResults(c, Count); return 0; } void SortData(const int SortItem, const int count, CustomerProfile c[]) { //0: Sort by name //1: Sort by ID //3: Sort by amount due }
You should use C++'s standard sort function, std::sort, declared in the <algorithm> header. When you sort using a custom sorting function, you have to provide a predicate function that says whether the left-hand value is less than the right-hand value. So if you want to sort by name first, then by ID, then by amount due, all in ascending order, you could do: bool customer_sorter(Customer const& lhs, Customer const& rhs) { if (lhs.Name != rhs.Name) return lhs.Name < rhs.Name; if (lhs.Id != rhs.Id) return lhs.Id < rhs.Id; return lhs.AmountDue < rhs.AmountDue; } Now, pass that function to your sort call: std::sort(customers.begin(), customers.end(), &customer_sorter); This assumes you have an STL container (and not an array, like you have in your sample code) called customers containing customers.
873,729
873,742
Watching Global Events created by a native process in a .NET process
I have a global event created and set/reset in a native C++ process that are created like this: HANDLE hGlobalEvent = CreateEvent(NULL, TRUE, FALSE, _T("Global\\MyEvent")); Is there any way (even if it's with a library not written by MS) to register for one of these events in a .NET (C#) process so that I standard .NET events handlers are fired off when the global event changed? And I don't really just want to wait on the event and loop, as is the way in C++ with WaitForSingleObject...I really would like it to be a completely asynchronous event handler. I've got to imagine there's an easy way to do this...just can't find it.
ThreadPool.RegisterWaitForSingleObject can be used to execute a callback when the event is signalled. Obtain a WaitHandle for the named event object by using the EventWaitHandle constructor that takes a string name. bool createdNew; WaitHandle waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, @"Global\MyEvent", out createdNew); // createdNew should be 'false' because event already exists ThreadPool.RegisterWaitForSingleObject(waitHandle, MyCallback, null, -1, true); void MyCallback(object state, bool timedOut) { /* ... */ }
873,731
873,804
Object Registration in Static Library
I have implemented a very basic "plug-in system" as part of a static library. Each "plug-in" implements the support for a specific image format, e.g. GIF, JPEG, etc.. Furthermore, I have a Singleton (a class called PluginManager) that keeps a list of all available plug-ins. The tricky part is that I want to disable/enable the plug-ins by adding or removing their source files from the project file. To achieve this, each plug-in creates a global variable (with different names) and registers the plug-in in the constructor of that class to PluginManager. Something like this for the JPEG format... struct JPEGPlugin { // constructor will register plugin JPEGPlugin() { PluginManager::Singleton().RegisterPlugin(this); } // plenty of other code ... }; JPEGPlugin jpeg_instance; // instantiate in global scope However, while this works perfectly in theory, it fails when linking this static library to other code to build an executable. As long as this executable does not access the plugin globals (like jpeg_instance), the linker does not see a connection (he completely ignores the side-effects of the constructor) and does not include the code in the final executable. In other words, the JPEG plug-in is not available in the final app. I ran into the problems a couple of times over the years, and I always searched the net for solutions. Each time, I just found pages that basically say that it's a known problem and that I have to live with it. But maybe someone on SO knows how to make this working?
I don't know if this a solution for the way you solved this problem, but we had a similar problem with static registration of an object factory and in Visual Studio we solved it by declaring the classes involved with __declspec(dllexport) this was necessary even though the libraries involved were not dlls. But without this the linker would omit the not referenced classes. The registry solution we worked a little bit different and did not involve Stack allocated objects. I lifted parts from CPP-unit, that is also where i discovered the __declspec approach iirc. [edit] We also had to #include the declaration for the registered class from some part of the code.
873,745
873,759
Why put a class declaration and definition in two separate files in C++?
I'm just wondering, what is the whole point of separating classes into an .h and a .cpp file? It makes it harder to edit, and if your class won't be compiled into a .lib or .dll for outside use, what's the point? Edit: The reason I'm asking is that the Boost libraries put everything in an .hpp file, (most of the libraries anyways), and I wanted to know why it is separated in most of the other code that I see.
C++ has something called the One Definition Rule. It means that (excluding inline functions), definitions can only appear in one compilation unit. Since C++ header files are just "copy and pasted" at every include file, now you are putting definitions in multiple places if you just put the definitions in header files. Of course, you may say, why not make everything inline. Well, if the compiler respects your inline suggestion, code for long functions will be replicated at every call site, making your code excessively large, and possibly causing thrashing, cache issues, and all sorts of unfun stuff. On the other hand, if the compiler does not listen to you, and doesn't inline anything, now you have 2 problems: 1) you don't know which translation unit got your classes definitions, and 2) the compiler still has to wade through your definitions every time you #include them. Moreover, there's no easy way to make sure you haven't accidentally defined the same method twice, in 2 different headers, differently. You also get a circular dependency issue. For a class to invoke another class's method, that class needs to be declared first. So if 2 classes need to invoke each other's methods, each must be declared before either can be defined. There is no way to do this with declarations and definitions in one file. Really, it's how the language and parser were built. It's a pain, but you just have to deal with it.
873,758
873,785
C++ string value as another strings name
How can i convert a vartiables value int anothers name in C++? like in this php snippet. $string = 'testVar'; ${$string} = 'test'; echo $testVar; // test
How about using a map? #include <iostream> #include <map> #include <string> using namespace std; map<string, string> hitters; hitters["leadoff"] = "Jeter"; hitters["second"] = "Damon"; hitters["third"] = "Teixiera"; hitters["cleanup"] = "Matsui"; string hitter = "cleanup"; cout << hitters[hitter] << endl;
873,976
874,051
Fastest C/C++ image resizing library
I am writing a application that needs to resize massive amounts of images... and these are my requirements: C/C++ Support jpeg/png at least Fast Cross-Platform So far my options are: OpenCV CImg ImageMagick GraphicsMagick (it's said to be fast) DevIL GIL from Boost CxImage Imlib2 (it's said to be fast) Any others? All of these would get the job done, but I am looking for the fastest here, and I was not able to find any benchmarks on their performance.
Take a look at Intel IPP (Integrated Performance Primitives) (Wiki link is better then the Intel one...) it works also on AMD and has functions to resize images (bilinear, nearest neighbor, etc) and works on Linux and Windows. It is not free (but it won't break the bank), but its the fastest that you can find.