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
848,144
848,268
How to hide the exporting functions in DLL
I don't want user to see all the exporting functions through Dependence in my DLL, is there a way to do it? I complie my DLL with C++ and MS Visual Studio.
Use a *.def file and use the NONAME attribute to prevent the name's being exported: see Exporting Functions from a DLL by Ordinal Rather Than by Name ... there's an an example here.
848,360
848,384
application couldn't be initialized error (manifest file problem)
I am trying to use a library (.dll) in my project. Everything seems to be set up fine. It all works in release mode. When I go debug on it, I get this darn error on startup: ldr: ... application couldn't be initialized error (or similar, I translated it) I learned that this has to do with manifest files. I fumbled around a bit, in the project settings, but nothing really worked / I couldn't get my head around it. The error persists. Does anyone know a quick solution to this? I don't care if it is dirty. I think I liked dll-Hell better than manifest-Hell!! The solution: The wrong version of the .dlls got loaded. I didn't know that they were still lying around on the system. Depedency Walker is a great tool and set me on the right track. So I will accept this answer. Thanks a lot!
I always use Dependency Walker for debugging this sort of thing. It will tell you which dependencies your dll is missing.
848,551
848,582
String->Structure CMap
My requirement is that given a string as key to the map, I should be able to retrieve a structure. Can anyone please post sample code for this? Ex: struct { int a; int b; int c; }struct_sample; string1 -> strcut_sample
CMap<CString,LPCTSTR, struct_sample,struct_sample> myMap; struct_sample aTest; aTest.a = 1; aTest.b = 2; aTest.c = 3; myMap.SetAt("test",aTest); ... struct_sample aLookupTest; BOOL bExists = myMap.Lookup("test",aLookupTest); //Retrieves the //struct_sample corresponding to "test". Example from MDSN for further details of CMap.
849,042
849,303
Implementing "app.exe -instruction file" notation in C++
I have a project for my Data Structures class, which is a file compressor that works using Binary Trees and other stuff. We are required to "zip" and "unzip" any given file by using the following instructions in the command line: For compressing: compressor.exe -zip file.whatever For uncompressing: compressor.exe -unzip file.zip We are programming in C++. I use the IDE Code::Blocks and compile using GCC in Windows. My question is: How do you even implement that??!! How can you make your .exe receive those parameters in command line, and then execute them the way you want? Also, anything special to have in mind if I want that implementation to compile in Linux? Thanks for your help
Lo logré, I gotz it!! I now have a basic understanding on how to use the argc and argv[ ] parameters on the main() function (I always wondered what they were good for...). For example, if I put in the command line: compressor.exe -unzip file.zip Then: argc initializes in '3' (number of arguments in line) argv[0] == "compressor.exe" (name of app.) argv[1] == "-unzip" argv[2] == "file.zip" Greg (not 'Creg', sorry =P) and Bemrose, thank you guys for your help!! ^^
849,168
849,190
Are std::vector elements guaranteed to be contiguous?
My question is simple: are std::vector elements guaranteed to be contiguous? In other words, can I use the pointer to the first element of a std::vector as a C-array? If my memory serves me well, the C++ standard did not make such guarantee. However, the std::vector requirements were such that it was virtually impossible to meet them if the elements were not contiguous. Can somebody clarify this? Example: std::vector<int> values; // ... fill up values if( !values.empty() ) { int *array = &values[0]; for( int i = 0; i < values.size(); ++i ) { int v = array[i]; // do something with 'v' } }
This was missed from C++98 standard proper but later added as part of a TR. The forthcoming C++0x standard will of course contain this as a requirement. From n2798 (draft of C++0x): 23.2.6 Class template vector [vector] 1 A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().
849,238
854,480
How can I resolve "error LNK2019: unresolved external symbol"?
I've got this MFC application I'm working on that needs to have an embedded database. So I went hunting for a slick, fast "embeddable" database for it and stumbled accross SQLite. I created a DB with it, and I created a static library project with Visual Studio 2008. the library project will be used in another main project. In the library project, I created a class DBClass with a method AddFeedToDB(CFeed f). The library project uses the .lib file from codeproject (cppsqlite3.lib). When compiling the static library, no error is detected, but when I try to use the library project file in the main project, I get these type of errors: error LNK2019: unresolved external symbol "public:void __thiscall CppSQLite3DB::close(void)" (?close@CppSQLite3DB@@QAEXXZ referenced in function "public: int __thiscall CTalkingFeedsDB::AddFeedToDB(class CFeed,char const*)" (? AddFeedToDB@CTalkingFeedsDB@@QAEHVCFeed@@PDB@Z What am I missing?
It happened to me more than once that I thought symbol XXX (i.e. ?close@CppSQLite3DB@@QAEXXZ) was in the import lib, while the actual symbol was __impXXX (i.e. __imp?close@CppSQLite3DB@@QAEXXZ). The reason for the linker error is then to be found in the compilation step: the compiler will generate the ?close@CppSQLite3DB@@QAEXXZ symbol to be imported, where it should generate __imp?close@CppSQLite3DB@@QAEXXZ. This often means that the function declaration itself didn't have __declspec( dllimport ). Which may be caused by some preprocessor symbol not being defined. Or the __declspec not being there at all...
849,309
849,322
Passing ofstream object from main program to a class
Here is what I am trying to do: 1) Open an ofstream object in my main body. I can do this no problem. 2) Associate this object with a filename. No problem. 3) Pass this object to a class and send output within this class. I can't do this. Here is my code. I would appreciate any help. Thanks! #include <fstream> #include <iostream> using namespace std; typedef class Object { public: Object(ofstream filein); } Object; Object::Object(ofstream filein) { filein << "Success"; } int main (int argc, char * const argv[]) { ofstream outfile; outfile.open("../../out.txt"); Object o(outfile); outfile.close(); return 0; }
You must pass stream objects by reference: Object::Object( ofstream & filein ) { filein << "Success"; } And why are you using a typedef on the class? It should look like this: class Object { public: Object(ofstream & filein); };
849,375
849,398
Determine network interface bandwidth/type without transferring data
Is there any way in Win32 to programmatically determine the bandwidth of a given network interface without actually transferring any data? I only want to distinguish between different types of interface (e.g. dialup vs DSL vs LAN), so a rough order of magnitude is fine, I don't need to actually measure the bandwidth. Background to the problem is that my application is very bandwidth-hungry, and I want to display a warning to the user if they try and run it over a low-bandwidth interface, e.g. dialup modem or GPRS modem. I've looked at some other related questions but if possible I'd like to avoid measuring throughput. GPRS modems in particular may have usage caps and I don't want to eat into a user's allowance - I'd rather detect the poor connection some other way and not actually send any data at all. I'm most interested in Win32/C++ answers, but any ideas would be gratefully received.
You can use InternetGetConnectedState to determine the type of connection (LAN/Modem/etc). This will tell you if they have a somewhat decent (non-modem) connection without bandwidth transfer. Unfortunately, you can't really go much beyond that without connecting and transferring data. There is no way for the system to know the bandwidth limitations outside of it's LAN connection - ie: you could connect to your gateway on a LAN directly, and it may have a crappy connection to the outside world. As far as your computer would be concerned, though, it's on a full speed lan connection...
849,483
849,504
How do you add conditional breaking based on another breakpoint being hit? Visual C++
I have a bunch of generic code that is used a lot, which i'd like to poke into in order to deal with a bug in a certain specific case. So I'd like to break on a set of breakpoints only if some other breakpoint has been hit. Is there a way to do this in Visual 2005? I'm using C++ code. Thanks!
If the trigger logic is complex enough, sometimes I find it easier to just add a DebugBreak(); call into the source.
849,656
850,251
Launch a URL in a NEW window using C++ (Windows)
How can I launch a URL in a NEW window using C++ (Windows only)? The straight-forward approach seems to open a new tab in an existing browser window. (Or, if tabbed browsing is disabled, the new URL hijacks the existing browser window). This is for a (large) desktop app, using MFC and Qt.
I've used this for showing locally generated html in the default browser, in my case filename is something like "c:\temp\page.html", perhaps replacing filename with the URL might work?? ShellExecute(NULL,"open",filename,NULL,NULL,SW_SHOWNORMAL); Updated: http://support.microsoft.com/kb/224816 How ShellExecute Determines Whether to Start a New Instance When ShellExecute looks through the registry, it looks for the shell\open subkey. If the shell\open\ddeexec key is defined, then a Dynamic Data Exchange (DDE) message with the specified application IExplore and the topic WWW_OpenURL is broadcast to all top-level windows on the desktop. The first application to respond to this message is the application that goes to the requested URL. If no application responds to this DDE message, then ShellExecute uses the information that is contained in the shell\open\command subkey to start the application. It then re-broadcasts the DDE message to go to the requested URL. So it looks like you have no control over opening a new window. Whatever browser currently running can handle opening it in whatever way they want.
849,711
849,765
TextBox let '\n' be the carriage return
TextBoxes created by "CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", ES_MULTILINE.." require \r\n for a new line. im redirecting my stdoutput into that textbox, which uses just '\n' to indicate a new line. and im not willing to replace all '\n' with '\r\n' isn't there a way to let '\n' beeing a newline in textboxes? thx
I'm pretty sure what you're asking is impossible (i.e. there's no magic setting to make Windows edit controls accept Unix-style newlines).
849,728
863,319
Determining the network connection link speed
How do I programmatically determine the network connection link speed for an active network connection - like Task Manager shows you in the Networking tab? I'm not really after the bandwidth available, just a figure for the current connection, e.g. 54Mbps, 100Mbps etc.
In the end I found the Win32_PerfRawData_Tcpip_NetworkInterface WMI class, as I need to support legacy platforms which, unfortunately, the Win32_NetworkAdapter doesn't do. Win32_PerfRawData_Tcpip_NetworkInterface has a CurrentBandwidth property which gives me what I need on all required platforms (I realise I said I didn't need "bandwidth" but its acceptable and appears to return the "nominal bandwidth" of the adapter anyway). Thanks to all those who posted, pointing me in the right direction.
849,812
849,839
C++ - construction of an object inside a class
I'm fairly new to C++, and I'm not sure about this one. Have a look at the following example which sums up my current problem. class Foo { //stuff }; class Bar { Foo foo; }; So Bar constains a full Foo object, not just a reference or pointer. Is this object initialized by its default constructor ? Do I need to explicitly call its constructor, and if so, how and where ? Thanks.
It will be initialized by its default constructor. If you want to use a different constructor, you might have something like this: class Foo { public: Foo(int val) { } //stuff }; class Bar { public: Bar() : foo(2) { } Foo foo; };
850,062
7,366,855
Debugging C# to Intel C++ in different projects
Similar to this problem here: Old Question about C# debugging I'm trying to debug a library that's used in multiple projects and is compiled using Intel's C++ v 11 compiler (ie, not the standard compiler) in Visual Studio 2008. The current platform I'm using to debug is a C# program that calls the C++ method through a p/invoke. Is there a way to debug into the C++ code (which has been compiled in debug mode) short of doing something like starting some huge loop in the C++ code and attaching a debugger to the process? Right now, the C# code just steps right over the C++ call. I've set it so that I can debug managed and unmanaged/native code, as well as debug 'not my code', but those settings don't seem to matter. I really, really want to avoid adding the C++ project to the C# project; as I said, it's a library that's called by multiple programs, so doing so would have serious consequences to those other programs and maintenance.
The answer: Set the debugging executable and running directory for the dll, and then try to debug from the dll as a separate project. That is, load the intel project in one sln file, and then have the C# project in a different sln file. Then, when you try to debug the dll via f5/the debug button, the executable will start, and the code will execute, up to whatever breakpoints you've set. Make sure to have a post-build step to put the dll into the same directory as your C# executable; otherwise, the dll will be out of sync with the code that's actually run, and the results will be strange (ie, breakpoints not lining up, etc). Also, with this approach, you will lose edit and continue (or, if there's a way to keep it, I don't know of it), but at least you get to debug in. (answer posted for @Dmitri Nesteruk)
850,142
850,150
Need help creating an array of objects
I am trying to create an array of class objects taking an integer argument. I cannot see what is wrong with this simple little code. Could someone help? #include <fstream> #include <iostream> using namespace std; typedef class Object { int var; public: Object(const int& varin) : var(varin) {} } Object; int main (int argc, char * const argv[]) { for(int i = 0; i < 10; i++) { Object o(i)[100]; } return 0; }
In C++ you don't need typedefs for classes and structs. So: class Object { int var; public: Object(const int& varin) : var(varin) {} }; Also, descriptive names are always preferrable, Object is much abused. int main (int argc, char * const argv[]) { int var = 1; Object obj_array[10]; // would work if Object has a trivial ctor return 0; } Otherwise, in your case: int main (int argc, char * const argv[]) { int var = 1; Object init(var); Object obj_array[10] = { var, ..., var }; // initialize manually return 0; } Though, really you should look for vector #include <vector> int main (int argc, char * const argv[]) { int var = 1; vector<Object> obj_vector(10, var); // initialize 10 objects with var value return 0; }
850,436
850,469
Problem passing a list of objects to another class, C++
Below I have written a sample program that I have written to learn about passing a list of objects to another class. I talk about the problems I am having below. #include <iostream> #include <vector> using namespace std; class Integer_Class { int var; public: Integer_Class(const int& varin) : var(varin) {} int get_var() { return var; } }; class Contains_List { typedef Integer_Class* Integer_Class_Star; Integer_Class_Star list; public: Contains_List(const Integer_Class_Star& listin) : list(listin) {} Integer_Class* get_list() { return list; } }; int main (int argc, char * const argv[]) { // Create a vector to contain a list of integers. vector<Integer_Class> list; for(int i = 0; i < 10; i++) { Integer_Class temp_int(i); list.push_back(temp_int); } This is where the errors start occuring. Could someone please look at the second class definition and the code below and shed some light on what I'm doing wrong. Thank you so much, as always! // Import this list as an object into another object. Contains_List final(list); // Output the elements of the list by accessing it through the secondary object. for(int i = 0; i < 10; i++) { cout << final.get_list()[i].get_var(); } return 0; }
You don't mention what sort of errors you are getting, but one very obvious problem with your code is that the constructor for Contains_List expects a pointer to Integer_Class while the parameter you are sending it (list) is of type vector<Integer_Class>. A vector is not the same as an array, so you cannot pass it as pointer to the type it contains. Either change your constructor to accept a vector or pointer/reference to vector, or change the code that is causing you problems so that it sends it a pointer to an array.
850,575
850,745
start service with out invoking uac
I have noticed some applications (like steam) are able to start/stop services as a normal user with out invoking the uac control. Does any one know how to do it? OS: Vista/Win 7 Visual Studio 2005 C++ . Edit: I was playing around with the steam service last night trying to work out how it is different. If i put my service exe where the steam one is it launched it fine with out uac (using sc.exe) but if i used the steam exe where mine is it didnt work. Looking around in the registry at the service information i found the steam one had an extra permissions part to it. What does this mean and how do you set it? . Edit 2: You need to change the user access rights of the service: http://msdn.microsoft.com/en-us/library/ms684215(VS.85).aspx
The ability to start (or stop) a service is controlled by the ACL on the service. If you grant interactive users the right to start your service, they can start your service. It's all in how you set your service up when you installed it. Obviously you'll have to use the Windows service APIs (OpenSCManager/OpenService/StartService) to start the service.
850,617
850,640
How to extract debugging information from a crash
If my C++ app crashes on Windows I want to send useful debugging information to our server. On Linux I would use the GNU backtrace() function - is there an equivalent for Windows? Is there a way to extract useful debugging information after a program has crashed? Or only from within the process? (Advice along the lines of "test you app so it doesn't crash" is not helpful! - all non-trivial programs will have bugs)
The function Stackwalk64 can be used to snap a stack trace on Windows. If you intend to use this function, you should be sure to compile your code with FPO disabled - without symbols, StackWalk64 won't be able to properly walk FPO'd frames. You can get some code running in process at the time of the crash via a top-level __try/__except block by calling SetUnhandledExceptionFilter. This is a bit unreliable since it requires you to have code running inside a crashed process. Alternatively, you can just the built-in Windows Error Reporting to collect crash data. This is more reliable, since it doesn't require you to add code running inside the compromised, crashed process. The only cost is to get a code-signing certificate, since you must submit a signed binary to the service. https://sysdev.microsoft.com/en-US/Hardware/signup/ has more details.
850,626
850,627
c++ char array out of scope or not?
I have a method that requires a const char pointer as input (not null terminated). This is a requirement of a library (TinyXML) I'm using in my project. I get the input for this method from a string.c_str() method call. Does this char pointer need to be deleted? The string goes out of scope immediately after the call completes; so the string should delete it with its destructor call, correct?
The char array returned by string.c_str() is null terminated. If tinyXML's function takes a not null terminated char* buffer, then your probably gonna get some unexpected behaviour. const char* c_str ( ) const; Get C string equivalent Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters. A terminating null character is automatically appended. No, it does not need to be released. String's destructor does that for you. The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only granted to remain unchanged until the next call to a non-constant member function of the string object. Source
850,724
850,728
Why doesn't my change to clog stick?
I think I'm failing to understand some finer point of C++. I want to set up a log of what my program does, and discovered std::clog, which seems to do what I want in theory, but in practice it doesn't. If I do the following, clog works as expected and writes "Test 1" to the screen, and "Test 2" shows up in a file: int main () { clog << "Test 1" << endl; streambuf* original_buffer = clog.rdbuf (ofstream ("test.log").rdbuf ())); clog << "test 2" << endl; clog.rdbuf (original_buffer); return 0; } But if I put all that into a class as such, then "Test 1" is written to the screen, test.log is created, but there's nothing inside and "Test 2" is no where to be found!: class IerrLog { std::streambuf * original_buffer; public: IerrLog () { std::ofstream logFile ("test.log"); original_buffer = std::clog.rdbuf (logFile.rdbuf ()); } ~IerrLog () { std::clog.rdbuf (original_buffer); } }; int main () { clog << "Test 1" << endl; IerrLog someLog (); clog << "Test 2" << endl; return 0; } What am I missing? EDIT: If I run the latter in valgrind, I get errors like this (the former runs clean): Invalid read of size 8 at 0x39598993E5: std::ostream::flush() (in /usr/lib/libstdc++.so.6.0.10) by 0x395989B5F2: std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&) (in /usr/lib/libstdc++.so.6.0.10) by 0x400F8E: main (main.cc:23) Address 0x7ff0006c8 is just below the stack ptr. To suppress, use: --workaround-gcc296-bugs=yes I'm not obnoxious enough to think that I (a lowly common programmer) found a compiler bug with such a simple program, but this makes me even more confused and valgrind obviously finds that the latter is somehow wrong, even though I tried to make them functionally identical.
I assume you want to create a stack variable of IerrLog. You need to change IerrLog someLog (); to IerrLog someLog; Your original statement will be interpreted by the compiler as a declaration of function someLog() which takes no arguments and returns an IerrLog. You should also create your file as a member variable and not on the stack.
850,796
850,850
What is the point of pointers?
What is the point of pointers in C++ when I can just declare variables? When is it appropriate to use them?
Pointers are best understood by C & C++'s differences in variable passing to functions. Yes, you can pass either an entire variable or just a pointer to it (jargon is by value or reference, respectively). But what if the variable is 20 meg array of bytes, like you decided to read an entire file in to one array? Passing it by value would be foolish: why would you copy 20 megs for this operation, and if you end up modifying it (i.e. it's an out-parameter) you have to copy that 20 megs BACK? Better is to just "point" to it. You say, "here's a pointer to a big blob of memory". And that little indirection saves a ton of time. Once you understand that, everything else is basically the same. Rearranging items in a list becomes just swapping pointers rather than copying every item around, you don't need to know how big things are when you start out, etc
851,031
853,864
In Qt, how do you properly implement delegates?
I followed the model/view/controller paradigm. I am pretty sure that the model and view are right, but I think I'm doing some things wrong in my delegate. Everything "works", except the first click to a control just "lights up the control" and the second one interacts with it. Is this how delegates are usually implemented? My implementation requires a lot of construction and destruction (hidden by scoped_ptr) so any tips on that are also helpful. QWidget *ParmDelegate::createWidget(const QModelIndex &index) const { if (!index.isValid()) return NULL; const Parm *p = static_cast<const Parm*>(index.internalPointer()); QWidget *w = p->createControl(); w->setAutoFillBackground(true); w->setBackgroundRole(QPalette::Base); // white background instead of grey return w; } QWidget* ParmDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { QWidget *retval = createWidget(index); if (dynamic_cast<QComboBox*>(retval)) connect(retval, SIGNAL(activated(int)), this, SLOT(commitAndCloseEditor())); else if (dynamic_cast<QSlider*>(retval)) connect(retval, SIGNAL(sliderReleased()), this, SLOT(commitAndCloseEditor())); else if (dynamic_cast<QAbstractButton*>(retval)) connect(retval, SIGNAL(clicked()), this, SLOT(commitAndCloseEditor())); else connect(retval, SIGNAL(editingFinished()), this, SLOT(commitAndCloseEditor())); retval->setFocusPolicy(Qt::StrongFocus); retval->setParent(parent); return retval; } void ParmDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { const Parm *p = static_cast<const Parm*>(index.internalPointer()); p->setEditorData(editor); } void ParmDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { ParmControl::Base* base = dynamic_cast<ParmControl::Base*>(editor); model->setData(index, base->toQVariant()); } void ParmDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { editor->setGeometry(option.rect); } void ParmDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { scoped_ptr<QWidget> w(createWidget(index)); if (!w) return; const Parm *p = static_cast<const Parm*>(index.internalPointer()); setEditorData(w.get(), index); w->setGeometry(option.rect); w->render(painter, option.rect.topLeft()); } QSize ParmDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { scoped_ptr<QWidget> w(createWidget(index)); if (!w) return QSize(0,0); return w->sizeHint(); } void ParmDelegate::commitAndCloseEditor() { QWidget *editor = static_cast<QWidget *>(sender()); ParmControl::Base* base = dynamic_cast<ParmControl::Base*>(editor); emit commitData(editor); emit closeEditor(editor, QAbstractItemDelegate::EditNextItem); }
If you are interested in changing the conditions that your custom editor is shown, use QAbstractItemView::setEditTriggers(). Although your delegate is responsible for passing information to and from the custom editor, the view determines when the editor is launched. Documentation reference: http://doc.qt.digia.com/4.5/qabstractitemview.html#editTriggers-prop.
851,041
851,051
How to access a data class's private member variable from another derived class whose parent class is a friend class of the data class?
I have three classes: A data holder class CDataHolder, which uses a Pimpl pattern class CDataHolder { public: // ... private: friend class CBase; struct PImpl; PImpl* iPimpl; }; A base class CBase, which need to access the iPImpl member in CDataHolder, so it is a friend class of CDataHolder class CBase: { protected: CDataHolder::Pimpl* getDataHolderPimpl(); }; A derived class CDerived from CBase, which need to access the same iPimpl member also. Here occurs a problem. The derived class cannot use the iPimpl member although its parent class is a friend class. like this: class CDerived : public CBase { public: void doSth() { CDataHolder::Pimpl *pImpl = getDataHolderPimpl(); // this line raises an error: // "illegal access from CDataHolder to protected/private member CDataHolder::PImpl" } }; There are plenty of derived classes, so it's not a good way for each derived class to put a "friend class CDerivedXXX" line in CDataHolder class. How to overcome this issue? Is there a better way to do this? Thanks in advance.
Since you have declared struct PImpl in the private part of CDataHolder class, only friends of CDataHolder can access the same. Why don't you put a forward declaration struct PImpl in the public section or even better before the CDataHolder class?
851,286
855,071
how to use movntdqa to avoid cache pollution?
i am trying to write a memcpy function that does not load the source memory to the cpu cache. The purpose is to avoid cache pollution. The memcpy function below works, but pollutes the cache like the standard memcpy does. i am using P8700 proccesoor with visual C++ 2008 express. i see the cpu cache usage with intel vtune. void memcpy(char *dst,char*src,unsigned size){ char *dst_end=dst+size; while(dst!=dst_end){ __m128i res = _mm_stream_load_si128((__m128i *)src); *((__m128i *)dst)=res; src+=16; dst+=16; } } i have another version, that have the same results - works but pollutes the cache. void memcpy(char *dst,char*src,unsigned size){ char *dst_end = dst+size; __asm{ mov edi, dst mov edx, dst_end mov esi,src inner_start: LFENCE MOVNTDQA xmm0, [esi ] MOVNTDQA xmm1, [esi+16] MOVNTDQA xmm2, [esi+32] MOVNTDQA xmm3, [esi+48] //19. ; Copy data to buffer MOVDQA [edi], xmm0 MOVDQA [edi+16], xmm1 MOVDQA [edi+32], xmm2 MOVDQA [edi+48], xmm3 // 25. ; Increment pointers by cache line size and test for end of loop add esi, 040h add edi, 040h cmp edi, edx jne inner_start } } update: this is the test program void test(int table_size,int num_iter,int item_size){ char *src_table=alloc_aligned(table_size*item_size);//return value is aligned on 64 bytes char *dst=alloc_aligned(item_size); //destination is always the same buffer for (int i=0;i<num_iter;i++){ int location=my_rand()%table_size; char *src=src_table+location*item_size;//selecting a different src every time memcpy(dst,src,item_size); } } main(){ test(1024*32,1024*1024,1024*32) }
Quoting from Intel: "The streaming load instruction is intended to accelerate data transfers from the USWC memory type. For other memory types such as cacheable (WB) or Uncacheable (UC), the instruction behaves as a typical 16-byte MOVDQA load instruction. However, future processors may use the streaming load instruction for other memory types (such as WB) as a hint that the intended cache line should be streamed from memory directly to the core while minimizing cache pollution." That explains why the code does not work — the memory is of type WB.
851,321
851,398
How to check that system is in Log off state?
I want to check that whether the system is in log off state or not in VC++, any ideas?
You can get logon/logoff notifications using various mechanisms (SENS, SCM Notifications if your program is a service, Winlogon notification if you're on XP) You can use WMI to enumerate active sessions. You can use the WTS API to enumerate sessions and query session information.
851,391
851,403
Reading line X until line Y from file in C++
I have a relatively simple question. Say I have a file but I only want to access line X of the file until line Y, whats the easiest way of doing that? I know I can read in the lines one by one keeping count, until I reach the lines that I actually need, but is there a better more elegant solution? Thanks.
In C++, no, not really (well, not in any language I'm familiar with, really). You have to start at the start of the file so you can figure where line X starts (unless it's a fixed-record-length file but that's unlikely for text). Similarly, you have to do that until you find the last line you're interested in. You can read characters instead of lines if you're scared of buffer overflow exploits, or you can read in fixed-size block and count the newlines for speed but it all boils down to reading and checking every character (by your code explicitly or the language libraries implicitly) to count the newlines.
851,654
851,808
How can I check is a socket is still open?
I have a C++ app that uses standard socket calls and I want to know if I can tell if a socket is still open without sending or receiving any data. Is there a reliable select or ioctlsocket call I can make?
If you try to recieve one byte, you can receieve several errors, if you were to have a non-blocking socket, and try to receieve on a valid connection, you will get the error WSAEWOULDBLOCK. Knowing this we can check a non blocking socket like so bool connected(SOCKET sock) { char buf; int err = recv(sock, &buf, 1, MSG_PEEK); if(err == SOCKET_ERROR) { if(WSAGetLastError() != WSAEWOULDBLOCK) {return false;} } return true; } as you can see from the return value of recv recv may return a timeout or several other errors for disconnect, i belive WSAEWOULDBLOCK is the only value it may return if there was an error but still connected, but you may want to double check that list of return values. Also the flag used in recv (MSG_PEEK) means that the data is still read-able when you go to look later after the check, so you don't need to worry about losing one byte of data. I believe this will only work well with non-blocking sockets, as it may block until it receives data. If you want to use blocking socket you may want to set it non-block with ioctlsocket before this check, then return it to how it was.
851,732
851,823
Problem with boost::bind and member function returning auto_ptr
Why does this code fail to compile with VS 2005: #include <boost/bind.hpp> #include <boost/function.hpp> struct X { typedef std::auto_ptr<int> IntType; // typedef int IntType; // this works IntType memfunc () const { return IntType (); } X () { boost::bind (&X::memfunc, this); } }; with this warning & error: 1>j:\libraries\boost\boost_1_37_0\boost\bind.hpp(1643) : warning C4180: qualifier applied to function type has no meaning; ignored 1> j:\libraries\boost\boost_1_37_0\boost\bind.hpp(1677) : see reference to class template instantiation 'boost::_bi::add_cref<Pm,I>' being compiled 1> with 1> [ 1> Pm=std::auto_ptr<int> (__thiscall X::* )(void), 1> I=1 1> ] 1> j:\dev\test\test\listtest.cpp(16) : see reference to class template instantiation 'boost::_bi::dm_result<Pm,A1>' being compiled 1> with 1> [ 1> Pm=X::IntType (__thiscall X::* )(void), 1> A1=X * 1> ] ? Changing the IntType typedef to just an int allows it to compile.
It seems, that, despite the documentation claiming they are equivalent, the following alternative works: boost::bind<IntType> (boost::mem_fn (&X::memfunc), this); Go figure...
852,002
890,430
LLVM what is it and how can i use it to cross platform compilations
I was reading here and there about llvm that can be used to ease the pain of cross platform compilations in c++ , i was trying to read the documents but i didn't understand how can i use it in real life development problems can someone please explain me in simple words how can i use it ?
The key concept of LLVM is a low-level "intermediate" representation (IR) of your program. This IR is at about the level of assembler code, but it contains more information to facilitate optimization. The power of LLVM comes from its ability to defer compilation of this intermediate representation to a specific target machine until just before the code needs to run. A just-in-time (JIT) compilation approach can be used for an application to produce the code it needs just before it needs it. In many cases, you have more information at the time the program is running that you do back at head office, so the program can be much optimized. To get started, you could compile a C++ program to a single intermediate representation, then compile it to multiple platforms from that IR. You can also try the Kaleidoscope demo, which walks you through creating a new language without having to actually write a compiler, just write the IR. In performance-critical applications, the application can essentially write its own code that it needs to run, just before it needs to run it.
852,070
852,109
Multiply defined symbols
If I declare a global variable in a header file and include it in two .cpp files, the linker gives an error saying the symbol is multiply defined. My question is, why does this happen for only certain types of object (eg. int) and not others (eg. enum)? The test code I used is given below: test.h #ifndef TEST_HEADER #define TEST_HEADER namespace test { int i_Test1 = -1; int i_Test2 = -1; }; #endif // TEST_HEADER class1.h #ifndef CLASS_1_HEADER #define CLASS_1_HEADER class class1 { public: void count(); }; #endif //CLASS_1_HEADER class1.cpp #include <iostream> #include "class1.h" #include "test.h" void class1::count() { std::cout << test::i_Test1 << std::endl; } class2.h #ifndef CLASS_2_HEADER #define CLASS_2_HEADER class class2 { public: void count(); }; #endif //CLASS_2_HEADER class2.cpp #include "class2.h" #include <iostream> #include "test.h" void class2::count() { std::cout << test::i_Test2 << std::endl; } main.cpp #include "class1.h" #include "class2.h" int main(int argc, char** argv) { class1 c1; class2 c2; c1.count(); c2.count(); return -1; } Building this code with: g++ main.cpp class1.cpp class2.cpp -o a produces the following output: ld: fatal: symbol test::i_Test1' is multiply-defined: (file /var/tmp//ccwWLyrM.o type=OBJT; file /var/tmp//ccOemftz.o type=OBJT); ld: fatal: symbol test::i_Test2' is multiply-defined: (file /var/tmp//ccwWLyrM.o type=OBJT; file /var/tmp//ccOemftz.o type=OBJT); ld: fatal: File processing errors. No output written to a collect2: ld returned 1 exit status If I change the test.h file as given below: test.h (with enum) #ifndef TEST_HEADER #define TEST_HEADER namespace test { enum val { i_Test1 = 5, i_Test2 }; //int i_Test1 = -1; //int i_Test2 = -1; }; #endif // TEST_HEADER I don't get the "multiply defined" error and the program gives the desired output: 5 6
That's because enumerations are not objects - they are types. Class types (class,struct,union) and enumerations can be defined multiple times throughout the program, provided all definitions satisfy some restrictions (summed up by the so-called One Definition Rule (ODR)). The two most important ones are All definitions have the same token sequence (textual identical) Names used must have the same meaning (resolve to the same things) in all definitions. (this is a requirement on the context of the definition) Your enumeration definition satisfies all conditions of the ODR. Therefor, that is valid and no reason for the linker / compiler to moan (actually, for a violation of the ODR the compiler is not required to issue a message either - most of it falls under the so-called no diagnostic required rule, some violations also result in undefined behavior). However, for every non-inline function and object, these must be only defined one time. Multiply defining those result in spurious errors, like in your case. To solve it, put only a declaration into the header file (using "extern" without an initializer) and put one definition into one of those .cpp files (omitting the "extern" then, or putting an initializer. If it is a const object, you still need the "extern", since per default const variables have internal linkage, and the symbol would not be exported otherwise).
852,162
852,208
dynamic structures in static memory?
GIVEN that you have a fixed area of memory already allocated that you would like to use, what C or C++ libraries will allow you to store a dynamic structure (e.g. a hash) in that memory? i.e. the hash library must not contain any calls to malloc or new, but must take a parameter that tells it the location and size of the memory it is permitted to use. (bonus if the library uses offsets rather than pointers internally, in case the shared memory is mapped to different address spaces in each process that uses it)
You can write your own custom allocators for STL containers. Dr.Dobb's: What Are Allocators Good For? SO: Compelling examples of custom C++ STL allocators?
852,334
854,692
How to interpret binary data in C++?
I am sending and receiving binary data to/from a device in packets (64 byte). The data has a specific format, parts of which vary with different request / response. Now I am designing an interpreter for the received data. Simply reading the data by positions is OK, but doesn't look that cool when I have a dozen different response formats. I am currently thinking about creating a few structs for that purpose, but I don't know how will it go with padding. Maybe there's a better way? Related: Safe, efficient way to access unaligned data in a network packet from C
I've done this innumerable times before: it's a very common scenario. There's a number of things which I virtually always do. Don't worry too much about making it the most efficient thing available. If we do wind up spending a lot of time packing and unpacking packets, then we can always change it to be more efficient. Whilst I've not encountered a case where I've had to as yet, I've not been implementing network routers! Whilst using structs/unions is the most efficient approach in term of runtime, it comes with a number of complications: convincing your compiler to pack the structs/unions to match the octet structure of the packets you need, work to avoid alignment and endianness issues, and a lack of safety since there is no or little opportunity to do sanity checks on debug builds. I often wind up with an architecture including the following kinds of things: A packet base class. Any common data fields are accessible (but not modifiable). If the data isn't stored in a packed format, then there's a virtual function which will produce a packed packet. A number of presentation classes for specific packet types, derived from common packet type. If we're using a packing function, then each presentation class must implement it. Anything which can be inferred from the specific type of the presentation class (i.e. a packet type id from a common data field), is dealt with as part of initialisation and is otherwise unmodifiable. Each presentation class can be constructed from an unpacked packet, or will gracefully fail if the packet data is invalid for the that type. This can then be wrapped up in a factory for convenience. If we don't have RTTI available, we can get "poor-man's RTTI" using the packet id to determine which specific presentation class an object really is. In all of this, it's possible (even if just for debug builds) to verify that each field which is modifiable is being set to a sane value. Whilst it might seem like a lot of work, it makes it very difficult to have an invalidly formatted packet, a pre-packed packets contents can be easilly checked by eye using a debugger (since it's all in normal platform-native format variables). If we do have to implement a more efficient storage scheme, that too can be wrapped in this abstraction with little additional performance cost.
852,377
852,426
How to ask for a small addition? (syntax of pure virtual functions)
In the current C++0x draft I've noticed they introduced some new explicit keywords to highlight expected behaviors (great move!). Examples: defaulted/deleted functions (= default and = delete), the new nullptr constant, the explicit keyword usable also for conversion operators, ... So I expected to see also a = pure syntax for pure virtual functions. Instead the ugly (IMHO, of course) = 0 thing still exists. Ok, I can use a #define pure 0 (and sometimes I do that), but I think coherency/consistency should be definitely a goal for a standard. Moreover I know it's just a sort of ultra-pedantic request, but = 0 was indeed one of my least favorite part of C++ (euphemism)... My questions: I know, the new standard is feature-complete, but is it still possible to ask for this small pedantic addition, even just as a "required macro" thing? if the answer is positive, how? (any committee member around?) am I just a bit too pedantic (or wrong) for asking this addition? what do you think about the current syntax of pure virtual functions?
That's not a small pedantic change. Introducing a new keyword is one of the biggest changes you can ask for. It is something they try to avoid almost at any cost. Think of all the code that uses the word "pure", which would break. In general, their guideline is to only add things to the language that could not be done before. A pure keyword wouldn't enable anything new (unlike the nullptr keyword, which enables better type checking, for example), so expect it to have a very low priority. Keep in mind that anything they do is basically maintenance work. The #1 goal is to avoid breaking the language (or existing code that uses it). Any features that are added on are only added if it can be done without breaking backward compatibility. However, the committee is more or less an open forum. Browse around their website, and you should be able to find a few email addresses. OR use the comp.std.c++ newsgroup. I believe their meetings are open as well, so you could just gatecrash the next one. ;)
852,568
29,309,756
Version resource in DLL not visible with right-click
I'm trying to do something which is very easy to do in the regular MSVC, but not supported easily in VC++ Express. There is no resource editor in VC++ Express. So I added a file named version.rc into my DLL project. The file has the below content, which is compiled by the resource compiler and added to the final DLL. This resource is viewable in the DLL using reshacker, though not when right-clicking the DLL in Windows Explorer. What is missing from my RC file to make it appear when right-clicking? VS_VERSION_INFO VERSIONINFO FILEVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1 FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x4L FILETYPE 0x1L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "something Application" VALUE "FileVersion", "1, 0, 0, 1" VALUE "InternalName", "something" VALUE "LegalCopyright", "Copyright (C) 2008 Somebody" VALUE "OriginalFilename", "something.exe" VALUE "ProductName", "something Application" VALUE "ProductVersion", "1, 0, 0, 1" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END
The correct solution is to add to the top of your .rc file: #include <windows.h>
852,676
852,688
Is "boolean short circuiting" dictated by standard or just mostly used as optimization?
Consider this Class* p = NULL; if( p != NULL && p->Method() == OK ){ // stuff } On all compilers I've worked with, this is quite safe. I.e. the first part of the boolean expression will evaluate to false, and the call to Method() will thus not be attempted since evaluating the second part is redundant. Is this because most compilers will optimize away the evaluation of the second part, or is it a dictated behavior from the C/C++ standards?
This is called boolean short circuiting and is defined into many languages. Here is a wikipedia article that describes which languages have this feature. Now that you know the correct name for the feature, there are other SO articles about it as well.
852,752
853,420
How to know when a new USB storage device is connected in Qt?
I want to know when a USB device is connected to the computer that my Qt application is running on (in Windows). In my main QWidget, I've reimplemented winEventFilter like this: bool winEventFilter ( MSG * msg, long * result ) { qDebug() << msg; return false; } I'd expect qDebug to send at least something when I connect a USB device, but I don't get anything. I'm guessing that I'm fundamentally misunderstanding the process here - this is my first Qt app!
I believe what you may be missing is the call to register for device notification. Here is code that I use to do the same thing, though I override the winEvent() method of the QWidget class and not the winEventFilter. // Register for device connect notification DEV_BROADCAST_DEVICEINTERFACE devInt; ZeroMemory( &devInt, sizeof(devInt) ); devInt.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); devInt.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devInt.dbcc_classguid = GUID_DEVINTERFACE_VOLUME; m_hDeviceNotify = RegisterDeviceNotification( winId(), &devInt, DEVICE_NOTIFY_WINDOW_HANDLE ); if(m_hDeviceNotify == NULL) { qDebug() << "Failed to register device notification"; } // end if NOTE: You will most likely need to change the values of the DEV_BROADCAST_DEVICEINTERFACE to fit your needs. EDIT: To use this code you will need to include the proper header files and perform the proper setup. DEV_BROADCAST_DEVICEINTERFACE requires the Dbt.h header to be included. Also, the focal point of this code is on the RegisterDeviceNotification function. Info is available on MSDN
852,856
852,893
Win32, C++: Creating a popup window without stealing focus
I am creating a program that displays a popup at certain times (just like some chat clients for example) on which the user can click. However, I do not want to take away the focus from the current application. The way I'm doing it now is by using a HWND with WS_POPUPWINDOW and minimizing and then restoring the window. However, this steals the focus from the current application. Setting foreground or hiding and showing a window did not make it appear on the foreground. I would like to be able to keep using a HWND so I can use other elements in this window, but I have no idea how to give it foreground without stealing focus. I use win32 and c++.
To show without activating: ShowWindow(hwnd, SW_SHOWNOACTIVATE); To raise without activating: SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
853,007
853,040
Find the elements of an array based on minimum sum
I've written a loop in C++ to give me 6 random numbers and store them in an array. What I would like to do is to sum the elements of the array until I get a value larger than a number, "x", but I would like to do this without necessarily adding all the elements. The objective is to find the first elements which sum to the value of x. For example, array is [1,2,3,4,5,6], and x = 6, so what I would be looking for are the elements [1,2,3]. I've looked at the standard library and have tried using the sum function from "valarray" but this just gives the sum of all the elements. Any ideas on how to code this successfully would be greatly appreciated.
Write a functor that does the addition. #include <algorithm> struct SumToo { SumToo(int val):m_val(val),m_sum(0) {} int m_val; int m_sum; bool operator()(int next) { m_sum += next; return m_sum >= m_val; } }; int main() { int data[] = {1,2,3,4,5,6}; int* find = std::find_if(data,data+6,SumToo(6)); }
853,304
859,853
Windows volume device detect failed until reboot. Never failed before
I have code to detect the connection of USB Flash Drives as volumes. The code has been working very well for awhile, but recently a fellow engineer's machine started to fail and didn't work right again until it was restarted. The project uses Qt 4.5.0, but that shouldn't be very relevant to this question. I register for the notification as follows // Register for device connect notification DEV_BROADCAST_DEVICEINTERFACE devInt; ZeroMemory( &devInt, sizeof(devInt) ); devInt.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); devInt.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devInt.dbcc_classguid = GUID_DEVINTERFACE_VOLUME; m_hDeviceNotify = RegisterDeviceNotification( winId(), &devInt, DEVICE_NOTIFY_WINDOW_HANDLE ); The handler then filters for the WM_DEVICECHANGE messages. if (message->message == WM_DEVICECHANGE) { switch (message->wParam) { case DBT_DEVICEARRIVAL: HandleVolumeArrival( message ); break; case DBT_DEVICEREMOVECOMPLETE: HandleVolumeRemoval( message ); break; default: break; } *result = TRUE; } // end if The arrival message handler then handles the message as such: void HandleVolumeArrival( MSG *message ) { if(message->lParam == 0) { qDebug() << "lParam is 0 on Device Arrival"; return; } // end if PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR) message->lParam; if(pHdr->dbch_devicetype == DBT_DEVTYP_VOLUME) { PDEV_BROADCAST_VOLUME pVol = (PDEV_BROADCAST_VOLUME) pHdr; // Handling of the volume is performed here } // end if } // end HandleVolumeArrival The problem came when checking the device type for a volume type: pHdr->dbch_devicetype == DBT_DEVTYP_VOLUME When it was failing, the device type was being reported as DBT_DEVTYP_DEVICEINTERFACE. Multiple USB drives were tried and all had the same problem. Has anyone seen anything like this before? Do you know what could cause it or why the problem would go away on a system restart?
My guess would be that you would see the DBT_DEVTYP_DEVICEINTERFACE normally anyway. USB devices are self-describing. A USB device can have any "interfaces" where each interface is a feature of the device. My guess is that when a USB is connected you get a "DBT_DEVTYP_DEVICEINTERFACE" per USB device interface so that a USB device driver can say that they can handle that USB interface. I would assume that the USB device driver for USB mass storage driver would would handle this messages by mounting the volume and then you would get the DBT_DEVTYP_VOLUME message. I would guess that the mass storage interface driver is not working correctly (or has crashed) and is not handling the DBT_DEVTYP_DEVICEINTERFACE. Unless you starting seeing it a lot I don't think it is a situation that you should bother to handle.
853,316
853,606
Is Critical Section always faster?
I was debugging a multi-threaded application and found the internal structure of CRITICAL_SECTION. I found data member LockSemaphore of CRITICAL_SECTION an interesting one. It looks like LockSemaphore is an auto-reset event (not a semaphore as the name suggests) and operating system creates this event silently when first time a thread waits on Critcal Section which is locked by some other thread. Now, I am wondering is Critical Section always faster? Event is a kernel object and each Critical section object is associated with event object then how Critical Section can be faster compared to other kernel objects like Mutex? Also, how does internal event object actually affects the performance of Critical section ? Here is the structure of the CRITICAL_SECTION: struct RTL_CRITICAL_SECTION { PRTL_CRITICAL_SECTION_DEBUG DebugInfo; LONG LockCount; LONG RecursionCount; HANDLE OwningThread; HANDLE LockSemaphore; ULONG_PTR SpinCount; };
When they say that a critical section is "fast", they mean "it's cheap to acquire one when it isn't already locked by another thread". [Note that if it is already locked by another thread, then it doesn't matter nearly so much how fast it is.] The reason why it's fast is because, before going into the kernel, it uses the equivalent of InterlockedIncrement on one of those LONG field (perhaps on the the LockCount field) and if it succeeds then it considers the lock aquired without having gone into the kernel. The InterlockedIncrement API is I think implemented in user mode as a "LOCK INC" opcode ... in other words you can acquire an uncontested critical section without doing any ring transition into the kernel at all.
853,368
853,646
Underlying type of a C++ enum in C++0x
I've been trying to read a bit of the C++ standard to figure out how enum's work. There's actually more there than I originally thought. For a scoped enumeration, it's clear that the underlying type is int unless otherwise specified with an enum-base clause (it can be any integral type). enum class color { red, green, blue}; // these are int For unscoped enumerations, it seems like the underlying type can be any integral type that will work and that it won't be bigger than an int, unless it needs to be. enum color { red, green, blue}; // underlying type may vary Since the underlying type of unscoped enumarations are not standardized, what's the best way of dealing with serializing instances of one? So far, I've been converting to int when writing then serializing into an int and setting my enum variable in a switch when reading, but it seems a bit clunky. Is there a better way? enum color { red, green, blue }; color c = red; // to serialize archive << (int)c; // to deserialize int i; archive >> i; switch(i) { case 0: c = red; break; case 1: c = green; break; case 2: c = blue; break; }
I haven't read any C++0x stuff so I couldn't comment on that. As for serializing, you don't need the switch when reading the enum back in - just cast it to the enum type. However, I don't cast when writing to the stream. This is because I often like to write an operator<< for the enum so I can catch bad values being written, or I can then decide to write out a string instead. enum color { red, green, blue }; color c = red; // to serialize archive << c; // Removed cast // to deserialize int i; archive >> i; c = (color)i; // Removed switch
853,559
853,704
What memory management do I need to cleanup when using TinyXml for C++?
I'm doing the following with TinyXml: TiXmlDocument doc; TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" ); TiXmlElement* main = new TiXmlElement("main"); TiXmlElement* header = new TiXmlElement("header"); header->SetAttribute("attribute","somevalue"); main->LinkEndChild(header); // ... Add many more TiXmlElment* to other elements all within "main" element doc.LinkEndChild(decl); doc.LinkEndChild(main); // ... do stuff with doc // Now I am done with my doc. What memory management happens here? At the end of my program's execution, will all of the TiXmlElement* be cleaned up when the doc goes out of scope? Do I need to walk the doc tree and free up all of the memory myself?
The documentation for LinkEndChild says this: NOTE: the node to be added is passed by pointer, and will be henceforth owned (and deleted) by tinyXml. This method is efficient and avoids an extra copy, but should be used with care as it uses a different memory model than the other insert functions.
854,541
854,594
Layout of Pixel-data in Memory?
I'm writing a C++ library for an image format that is based on PNG. One stopping point for me is that I'm unsure as to how I ought to lay out the pixel data in memory; as far as I'm aware, there are two practical approaches: An array of size (width * height); each pixel can be accessed by array[y*width + x]. An array of size (height), containing pointers to arrays of size (width). The standard reference implementation for PNG (libpng) uses method 2 of the above, while I've seen others use method 1. Is one better than the other, or is each a method with its own pros and cons, to where a compromise must be made? Further, which format do most graphical display systems use (perhaps for ease of using the output of my library into other APIs)?
Off the top of my head: The one thing that would make me choose #2 is the fact that your memory requirements are a little relaxed. If you were to go for #1, the system will need to be able to allocate height * width amount of contiguous memory. Whereas, in case of #2, it has the freedom to allocate smaller chunks of contiguous memory of size width (could as well be height) off of areas that are free. (When you factor in the channels per pixel, the #1 may fail for even moderately sized images.) Further, it may be slightly better when swapping rows (or columns) if required for image manipulation purposes (pointer swap suffices). The downside for #2 is of course an extra level of indirection that seeps in for every access and the array of pointers to be maintained. But this is hardly a matter given todays processor speed and memory. The second downside for #2 is that the data isn't necessarily next to each other, which makes it harder for the processor the load the right memory pages into the cache.
854,681
855,246
C++ compiler error in netbeans
I've tried everything from reading the Netbeans help to browsing Google. This code works fine in Dev-Cpp but not Netbeans 6.5.1. Netveans also places and exclamation mark next to #include <iostream> which i checked and is in the include path of netbeans and is in the include folder: #include <iostream> int main() { std::cout << "Test" << "\n"; return (0); } My build tools are set to: Family: MinGW Base Directory: C:\Dev-Cpp\bin C Compiler: C:\Dev-Cpp\bin\gcc.exe C++ Compiler: C:\Dev-Cpp\bin\g++.exe Fortran Compiler: C:\Dev-Cpp\bin\g77.exe Make Command: C:\Dev-Cpp\bin\make.exe Debugger Command: C:\Dev-Cpp\bin\gdb.exe I get error: Running "C:\Dev-Cpp\bin\make.exe -f Makefile CONF=Debug" in C:\Documents and Settings\Babiker\Desktop\Temp\Test ! was unexpected at this time. C:\Dev-Cpp\bin\make.exe: *** [.validate-impl] Error 255 Build failed. Exit value 2.
The cause of the error is that Netbeans is incompatible with MinGW's make. You have a choice of supported make versions: Cygwin's make. Cygwin is a blessing. It brings as much Unix to Windows as you'd like. MinGW's own MSYS, which "is a collection of GNU utilities such as bash, make, gawk and grep to allow building of applications and programs which depend on traditionally UNIX tools to be present". It is also a much smaller download than Cygwin.
854,864
854,957
When and why is an std::__non_rtti_object exception generated?
I'm using Visual Studio and performing a valid dynamic cast. RTTI is enabled. Edit : Updated the code to be more realistic struct base { virtual base* Clone() { base* ptr = new base; CopyValuesTo( ptr ); return ptr; } virtual void CopyValuesTo( base* ptr ) { ... } virtual ~base() { } } struct derived : public base { virtual base* Clone() { derived* ptr = new derived; CopyValuesTo( ptr ); return ptr; } virtual void CopyValuesTo( base* ptr ) { ... } virtual ~derived() { } } void Class1::UseNewSpec( base* in_ptr ) //part of a totally unrelated class { derived* ptr = dynamic_cast<derived *>(in_ptr); if( !ptr ) return; delete m_ptr; m_ptr = ptr->Clone(); //m_ptr is a member of Class1 of type base* } //usage : Class1 obj; derived new_spec; obj.UseNewSpec( &new_spec ); My debugger says that in_ptr is of the correct type when the exception is thrown. Google seems particularly unhelpful. Any ideas? Cheers.
I ran a test based on your pseudo-code and it works. So if RTTI is truly enabled in your build configuration, then it must be another problem that isn't captured in what you posted.
855,021
855,039
How do I access internal members of a union?
I have a union that is defined like this: typedef union { enum { REVISION = 0, CURRENT_VERSION = REVISION }; enum FLAGS{ FLAG_DEFAULT = 0x00000000, FLAG_EOD = 0x00000001, FLAG_OUTOFORDER = 0x00000002 }; CHAR _filler[32]; struct INTERNAL_STRUCTURE { UINT16 type; UINT16 flags; }; }CORRHDR How do I access the member's of INTERNAL_STRUCTURE from my code? I've thought I could just do this: CORRHDR hdr; hdr.INTERNAL_STRUCTURE.type = 1; I'm wrong. I can see the enums in the union, but nothing else. Could someone explain the structure (or benefit) of this type to me?
You have declared the type called INTERNAL_STRUCTURE, but not an actual instance of that type. Try this: typedef union { //... CHAR _filler[32]; struct { UINT16 type; UINT16 flags; } INTERNAL_STRUCTURE; }CORRHDR; Then to access the field: CORRHDR ch; printf("%u\n", ch.INTERNAL_STRUCTURE.type);
855,110
855,131
Why is the use of tuples in C++ not more common?
Why does nobody seem to use tuples in C++, either the Boost Tuple Library or the standard library for TR1? I have read a lot of C++ code, and very rarely do I see the use of tuples, but I often see lots of places where tuples would solve many problems (usually returning multiple values from functions). Tuples allow you to do all kinds of cool things like this: tie(a,b) = make_tuple(b,a); //swap a and b That is certainly better than this: temp=a; a=b; b=temp; Of course you could always do this: swap(a,b); But what if you want to rotate three values? You can do this with tuples: tie(a,b,c) = make_tuple(b,c,a); Tuples also make it much easier to return multiple variable from a function, which is probably a much more common case than swapping values. Using references to return values is certainly not very elegant. Are there any big drawbacks to tuples that I'm not thinking of? If not, why are they rarely used? Are they slower? Or is it just that people are not used to them? Is it a good idea to use tuples?
Because it's not yet standard. Anything non-standard has a much higher hurdle. Pieces of Boost have become popular because programmers were clamoring for them. (hash_map leaps to mind). But while tuple is handy, it's not such an overwhelming and clear win that people bother with it.
855,121
855,291
C++ Custom Enum Struct for INI file reader
I'm trying to create an Enum that has a string label and a value and I plan to use this to read stuff from an ini file. For example in the ini file I might have some double, int or string type values preceded by the tag/name of the value: SomeFloat = 0.5 SomeInteger = 5 FileName = ../Data/xor.csv When I read the tag from a file it comes in as a string, so I'd just like to have std::set that keeps all of my values... when I read the tag I can just compare it against the EnumType and if matches the label then I will check the type and do the proper conversion (atoi or just use the string, etc.) For example: EnumType<int> someInteger; someInteger.label = "SomeInteger"; someInteger.type = INT; std::set<EnumType> myValues; // // populate the set myValues.insert(someInteger); // void ProcessTagAndValue(const std::string &tag, const std::string &value) { switch(myValues[tag].type) { case INT: myValues[tag].value = atoi(value); break; case DOUBLE: // break; case STRING: myValues[tag].value = value; break; default: break; } } enum ValueType{INT,DOUBLE,STRING]; template <class T> struct EnumType{ std::string label; ValueType type; T value; bool operator==(const EnumType &other) const { return this->label == other.label; } bool operator==(const T& other ) const { return this->value == other; } T& operator=(const T& p) { value = p; return value; } EnumType& operator=(const EnumType& p) { if (this != &p) { // make sure not same object this->label = p.label; this->value = p.value; } return *this; } }; I have several questions: Can you guys tell me any better solutions? I'm not sure if I'm trying to be too clever for my own good, or if this is really a viable solution. If my solution is acceptable, then can anybody tell me how I can declare a set of std::set<EnumType<...>> so that it can accept any type (int, double, string) without me actually knowing which type the enum is going to be using for the value? If you have any code, then it would be GREAT! :)
If you have limited and very stable set of types, then Boost.Variant may be used. If you going to add support for new types later, then better forget about this method. In this situation solution, based on Boost.Any, or pair of strings will be better. typedef boost::variant<int, double, std::string> ValueType; struct EnumType { std::string label; ValueType value; }; Another question is: "How these values will be used later?" If you are going to pass "SomeInteger" to function, accepting int, you still have to run code similar to: acceptInt( get<int>( v.value ) ); // get may throw This approach works better when you have uniform processing of fixed set of types: class processValue : public boost::static_visitor<> { public: void operator()(int i) const { acceptInt( i ); } void operator()(double d) const { acceptDouble( d ); } void operator()(const std::string & str) const { acceptString( str ); } }; boost::apply_visitor( processValue(), v.value );
855,123
855,227
Is it possible to make a factory in C++ that complies with the open/closed principle?
In a project I'm working on in C++, I need to create objects for messages as they come in over the wire. I'm currently using the factory method pattern to hide the creation of objects: // very psuedo-codey Message* MessageFactory::CreateMessage(InputStream& stream) { char header = stream.ReadByte(); switch (header) { case MessageOne::Header: return new MessageOne(stream); case MessageTwo::Header: return new MessageTwo(stream); // etc. } } The problem I have with this is that I'm lazy and don't like writing the names of the classes in two places! In C# I would do this with some reflection on first use of the factory (bonus question: that's an OK use of reflection, right?) but since C++ lacks reflection, this is off the table. I thought about using a registry of some sort so that the messages would register themselves with the factory at startup, but this is hampered by the non-deterministic (or at least implementation-specific) static initialization order problem. So the question is, is it possible to implement this type of factory in C++ while respecting the open/closed principle, and how? EDIT: Apparently I'm overthinking this. I intended this question to be a "how would you do this in C++" since it's really easy to do with reflection in other languages.
I think that the open/closed approach and DRY are good principles. But they are not sacred. The goal should be making the code reliable and maintainable. If you have to perform unnatural acts to adhere to O/C or DRY, then you may simply be making your code needlessly more complex with no material benefit. Here is something I wrote a few years ago on how I make these judgment calls.
855,417
855,444
Mapping from character id to a class name in c++ via templates?
Duplicate: Is there a way to instantiate objects from a string holding their class name? Is there a (better) way in C++ to map string id to a class name. I suspect there might be a way via templates but I wasn't able to figure out the correct way. For example if I have multiple messages, each storing in the first byte a character id. So message A12345 would instantiate class A() message B12345 would map to class B(). I have a group of message parsers where each class can parse give message. The issue is that I have to manually generate mapping between class that parses given message (e.g. class A()) and the message id (e.g. the 'A'). This is what I'm doing in the code now, and I'm thinking if there's a nice way to eliminate the switch in c++ (templates magic?): Msg * msg; switch(data[0]) { case 'A': msg = new A(); break; case 'B': msg = new B(); break; ... } msg->parse(data); On the side note, most of the time the id's are actually 2 character long so 'A1' 'B1' and so on. And I'm using the class names the same to keep track of the classes, e.g. 'A1' can be parsed by class A1() and so on. NOTE: This seems like duplicate of C++: Is there a way to instantiate objects from a string holdig their class name? so I suggest to close this question.
As someone else said, it can't be done using templates (templates are computed at compile time. But your character id is compute at runtime). You can use a map from id to constructor function. It boils down to this question: Instantiate objects from a String holding their class name I recommend you to keep it simple. If a plain switch will do it, keep it that way. If you later really need to have it extensible, you can still introduce some automatic look-up of character ids and so on.
855,996
856,026
C++ Equivalent to Designated Initializers?
Recently I've been working on some embedded devices, where we have some structs and unions that need to be initialized at compile time so that we can keep certain things in flash or ROM that don't need to be modified, and save a little flash or SRAM at a bit of a performance cost. Currently the code compiles as valid C99, but without this adjustment it used to compile as C++ code as well, and it would be great to support things being compiled that way as well. One of the key things that prevents this is that we're using C99 designated initializers which do not work within the C subset of C++. I'm not much of a C++ buff, so I'm wondering what simple ways there might be to make this happen in either C++ compatible C, or in C++ that still allow initialization at compile time so that the structs and unions not need be initialized after program startup in SRAM. One additional point of note: a key reason for designated initializer usage is initalizing as NOT the first member of a union. Also, sticking with standard C++ or ANSI C is a plus in order to maintain compatibility with other compilers (I know about the GNU extensions that provide something like designated initializers without C99).
I'm not sure you can do it in C++. For the stuff that you need to initialize using designated initializers, you can put those separately in a .c file compiled as C99, e.g.: // In common header file typedef union my_union { int i; float f; } my_union; extern const my_union g_var; // In file compiled as C99 const my_union g_var = { .f = 3.14159f }; // Now any file that #include's the header can access g_var, and it will be // properly initialized at load time
856,200
856,277
C++: First element of vector "corrupting"
I have a class (foo) that contains a vector. If i try iterating over the elements in the vector like so: for(vector<random>::iterator it = foo.getVector().begin(); it != foo.getVector().end(); ++it) { cout << (*it) << endl; } The first element is always corrupted and returns garbage data. However, if do something like: vector<random> v = foo.getVector(); for(vector<random>::iterator it = v.begin(); it != v.end(); ++it) { cout << (*it) << endl; } Everything appears to be working fine. Is there a "gotcha" that I do not know about? I've also tried doing cout << foo.getVector()[0] << endl; outside of the loop but that appears to be working ok. Thanks. Edit: Here's my header file: #ifndef HITS #define HITS #include <vector> #include "wrappers.h" class Hits { public: Hits(); std::vector<word_idx_value> getVector() {return speech_hits;} const std::vector<word_idx_value> getVector() const {return speech_hits;} void add(const word_idx_value&); Hits &operator+=(const Hits&); private: std::vector<word_idx_value> speech_hits; }; #endif
for(vector<random>::iterator it = foo.getVector().begin(); The temporary vector is returned when you do foo.getVector() and it gets destroyed the moment ; is encountered after foo.getVector().begin(); Hence iterator becomes invalid inside the loop. If you store the value of foo.getVector(); in vector v ( v = foo.getVector();) and then use the vector v, it works fine. It is because the vector v is valid throughout the loop.
856,321
856,478
Why is it necessary to add new events to the *end* of an IDL interface?
I have found that when I add new events to an existing COM/IDL interface, I sometimes run into strange issues unless they are added to the end of the interface. For example, say I have the following interface: interface IMyEvents { HRESULT FooCallback( [in] long MyParam1, [in] long MyParam2, [in] long MyParam3); HRESULT BarCallback( [in] long MyParam1, [in] BSTR MyParam2, [in] BSTR MyParam3); }; Now let's say I want to add a new callback event, NewCallback. If I add it like this, I tend not to have any problems when the event is fired across COM: interface IMyEvents { HRESULT FooCallback( [in] long MyParam1, [in] long MyParam2, [in] long MyParam3); HRESULT BarCallback( [in] long MyParam1, [in] BSTR MyParam2, [in] BSTR MyParam3); /* New event added to the end */ HRESULT NewCallback( [in] BSTR MyParam1, [in] BSTR MyParam2, [in] BSTR MyParam3); }; But if I add it like this, I can run into all sorts of problems (e.g. buffer overruns) when the event is fired. interface IMyEvents { HRESULT FooCallback( [in] long MyParam1, [in] long MyParam2, [in] long MyParam3); /* New event added to the middle */ HRESULT NewCallback( [in] BSTR MyParam1, [in] BSTR MyParam2, [in] BSTR MyParam3); HRESULT BarCallback( [in] long MyParam1, [in] BSTR MyParam2, [in] BSTR MyParam3); }; I'm guessing it has something to do with DLL entry points, address offsets, or something similar. Or maybe it's because I haven't re-built something properly, and adding it to the end allows it to work by sheer luck. Can anyone explain this behaviour?
You are not supposed to modify an existing COM interface. Clients that were not compiled with the change are not aware of it and will continue calling as they had done before the change. The result is that existing clients call BarCallback with a long integer, but instead get NewCallback that thinks this long integer is a BSTR. The results are often unpleasent. You'll get similar problems with adding new functions at the end. Older COM object do not have the new function implemented and will likely just crash when you try to call it. However, if you do not have existing clients in the wild using the old interface, just make sure you unregister everything and replace the object, clients and proxies and stubs you generated.
856,463
856,486
How to remove/delete executable files (aka files without extension) only
I have a directory src/ that contain many .cc files and its binary. For example: src/ |_ foo.cc |_ bar.cc |_ qux.cc |_ thehead.hh |_ foo (executable/binary) |_ bar (executable/binary) |_ qux (executable/binary) |_ makefile In reality there are many .cc and executable files. I need to remove those binaries in a global way without having to list all the files. Is there a fast and compact way to do it? I tried: $ rm * but it removes all the files include .cc and .hh files. I am aware of this command: $ rm foo bar qux .... but then we still have to list all the files one by one.
you can run find . -perm +100 -type f -delete
856,466
856,517
Very strange visual studio behaviour with excessive lines of whitespace
yesterday we updated to a new version of some middleware we are using, and had a very bizarre merge problem with perforce... it had created approximately 10-20 thousand lines of white space in one of my functions, this all compiled fine, upon running the program it crashed indicating some memory issue, tracing back through the call stack I discovered visual studio was pointing the debugger right into the middle of the function that had the thousands of lines of white space in it, deleting the excess lines and recompiling fixed this issue, I was just wondering how this is so?, there was no difference in the code and the compiler is supposed to ignore all white space, is this some kind of bug in visual studio? thanks
Are you sure it's white space and not Whitespace?
856,542
856,839
Elegant solution to duplicate, const and non-const, getters?
Don't you hate it when you have class Foobar { public: Something& getSomething(int index) { // big, non-trivial chunk of code... return something; } const Something& getSomething(int index) const { // big, non-trivial chunk of code... return something; } } We can't implement either of this methods with the other one, because you can't call the non-const version from the const version (compiler error). A cast will be required to call the const version from the non-const one. Is there a real elegant solution to this, if not, what is the closest to one?
I recall from one of the Effective C++ books that the way to do it is to implement the non-const version by casting away the const from the other function. It's not particularly pretty, but it is safe. Since the member function calling it is non-const, the object itself is non-const, and casting away the const is allowed. class Foo { public: const int& get() const { //non-trivial work return foo; } int& get() { return const_cast<int&>(const_cast<const Foo*>(this)->get()); } };
856,545
856,594
C++ Library requires LibCurl - will users of the app need libcurl?
I'm normally a Java developer, but I'm writing a C++ library right now they will use LibCurl. And I'm very un-aware in the C++ world! What I'm writing is infact a library for use by other developers (its a client code used to access our API). Will end users be required to have libcurl installed, or can the developers somehow include this in the EXE or package it somehow? Actually the same goes, I might use QT in the library, will they be required to have this installed? I'm guessing the way it works is that developers of course will need it, but once its compiled to binary its not required? Unlike java where you need the Jar files all along... Cheers for any help, Alan
If you link libcurl statically then the end-user does not require libcurl, as it will be linked into to the executable directly at compile time. If you link libcurl dynamically, then the end-user does require libcurl to be installed on their system and available as a shared object library. However, you're in a different spot. You're writing a library for use by other developers. Thus, your end-user is in fact not really an end-user. In such scenarios it is "better" to provide to link dynamically against libcurl. If you linked statically then your library would encapsulate in its code a copy of the libcurl library. Now imagine a developer using your library is also using 10 other libraries, all statically linked against libcurl. That developer is basically going to be including 10 copies of libcurl in his/her end product. This is not very efficient and hence dynamic linking against dependencies is preferred when developing a library. However... If a developer is using 10 different libraries which require libcurl but some of those libraries require a specific older/newer version than others then static linking will be useful. Hope that helps...
856,551
856,587
C++ Converting a Datetime String to Epoch Cleanly
Is there a C/C++/STL/Boost clean method to convert a date time string to epoch time (in seconds)? yyyy:mm:dd hh:mm:ss
See: Date/time conversion: string representation to time_t And: [Boost-users] [date_time] So how come there isn't a to_time_t helper func? So, apparently something like this should work: #include <boost/date_time/posix_time/posix_time.hpp> using namespace boost::posix_time; std::string ts("2002-01-20 23:59:59"); ptime t(time_from_string(ts)); ptime start(gregorian::date(1970,1,1)); time_duration dur = t - start; time_t epoch = dur.total_seconds(); But I don't think it's much cleaner than Rob's suggestion: use sscanf to parse the data into a struct tm and then call mktime.
856,617
857,505
xcode gives syntax error on cpp code
I am trying to reuse Apple's Speak Here sample code in my own iPhone app. I downloaded and compiled the project with no problems, so I then added some of the files to my own application. When I try to compile my own application, the compiler gives me MeterTable.h:54: error: syntax error before 'MeterTable' The relevant code is: #include <stdlib.h> #include <stdio.h> #include <math.h> class MeterTable // line 54 { public: It looks kind of like xcode isn't recognizing MeterTable.h and MeterTable.mm as C++ files. I've checked File>>GetInfo for MeterTable.mm, though, and it lists filetype as sourcecode.cpp.cpp. Why won't this compile?
You're including "MeterTable.h" in a non C++ file other than MasterTable.mm. The error is not in 'MeterTable.h' but in the header included before it. Note that <stdlib.h>... can be a noop if they are included before. If you want to make sure your file is compiled with C++, you can add this code to the begining of MasterTable.mm: #ifdef __cplusplus #error "compiled as C++" #else #error "compiled as C" #endif
856,653
1,222,030
C++ namespace problem with ARM RealViewICE
I'm using ARM RealView debug 3.1 and I'm unable to watch variables inside functions defined in a C++ namespace, the code works well and is compiled with armcc. Do any of you know a solution for this?
Well, arm confirmed this bug.
857,072
857,104
Can I iterate over the elements that are in one range of iterators but not in another?
Let's say I have a sequential container, and a range (pair of iterators) within that container of elements that are currently 'active'. At some point, I calculate a new range of elements that should be active, which may overlap the previous range. I want to then iterate over the elements that were in the old active range but that are not in the new active range to 'deactivate' them (and similarly iterate over the elements that are in the new range but not the old range to 'activate' them). Is this possible? Does it become easier if I know that the start of the new active range will always be later in the container than the start of the old active range? For the purposes of the question, assume the container is a vector.
You can use two sets for the last active range and another for the current active range. Use the set_difference algorithm to get the objects to be activated/deactivated.
857,085
857,285
What is the most correct way to hide an autocomplete popup?
I'm developing a custom autocomplete control in pure WinApi, and the problem that I've encountered is that I don't know how to hide the popup window when clicked outside of the control (e.g. emulate the combobox dropdown behavior). How is it usually implemented? Should I use mouse capture? Thanks. UPD: Tracking keyboard focus doesn't fit the bill since dragging the parent window around should also hide the dropdown. UPD: Mouse capture doesn't work because it "captures mouse input either when the mouse is over the capturing window, or when the mouse button was pressed while the mouse was over the capturing window and the button is still down".
After reading this article I now believe that using SetWindowsHookEx and a WH_MOUSE hook is the way to go. But maybe there is a simpler solution?
857,113
857,132
Calling overridden function from the overriding function
Suppose I have virtual function foo() in class B, and I need slightly different behavior in one of B's derived classes, class D. Is it OK to create an overriding function D::foo(), and call B::foo() from there, after the special case treatment? Like this: void D::foo() { if (/*something*/) // do something else B::foo(); } I am not asking whether that would work, I know it will. I want to know, whether it is right in terms of a good OOD.
This is perfectly good. In fact, the canonical way of performing some operations is calling the base class method, then do whatever (or the other way around). I am thinking of operator= here. Constructors usually work that way, too, even if this is a bit disguised in the initialization list.
857,135
859,447
How to handle messages from dynamically created controls in an MFC app?
Imagine I have a CDialog which creates controls dynamically when the user clicks a button. It could be like this: // We don't know which is the first id for the new buttons until runtime (!) MyDialog::MyDialog(/*whatever parameters needed*/, first_id) : next_id_(first_id) { /*...*/ } BOOL MyDialog::OnSomeButtonClicked() { CButton* new_button = new CButton; new_button->Create("Caption", WS_CHILD | WS_VISIBLE, this->new_button_rect_, this, this->next_id_++); } Then my question would be: How could I handle messages from this button? Is it possible to use the MFC message map facility? The solution should work in both vs6 and vs2005. Thank you!
These are the solutions I've found so far in order of relevance: Use ON_COMMAND_RANGE if you can define the range of the control IDs you want to handle. Overload CWnd::PreTranslateMessage() and do whatever stuff you want with the messages received. NOTE: When dealing with buttons, take into account that the BN_CLICKED event is NOT sent to PreTranslateMessage but directly sent to the window procedure. Overload CWnd::WindowProc() and do whatever stuff you want with the messages received. NOTE that when dealing with buttons this is the ONLY WAY I've found to handle the BN_CLICKED event. Interesting links: Please help with PreTranslateMessage and user defined messages handling. TN006: Message Maps I hope this helps... thank you all for your contributions.
857,258
857,280
c++ constant in library; does not work
anyone knows why this does not work when I try to include a library with the following declarations: namespace wincabase { const char* SOMESTRING = "xx"; } While this is perfectly fine: namespace wincabase { const int X = 30; } I get a "multiple definitions" error with gcc for the first case when I link the lib. Thanks!
const char* means pointer to const char. This means the pointer itself is not constant. Hence it's a normal variable, so you'd need to use extern const char* SOMESTRING; in the header file, and const char* SOMESTRING = "xx"; in one compilation unit of the library. Alternatively, if it's meant to be a const pointer to a const char, then you should use: const char* const SOMESTRING = "xx";
857,347
858,153
Call COM exe API from NSIS script
Is it possible to call an api exposed in COM exe server from NSIS script? I am not able to find any documentation for that. If anyone knows , please reply.
The basic syntax looks like: System::Call "$0->2()" where $0 is the COM object and 2 is the 0 based index of the method in the vtable (2 is Release) http://nsis.sourceforge.net/System_plug-in_readme#Usage_Examples_2
857,395
858,128
Alternatives to preprocessor directives
I am engaged in developing a C++ mobile phone application on the Symbian platforms. One of the requirement is it has to work on all the Symbian phones right from 2nd edition phones to 5th edition phones. Now across editions there are differences in the Symbian SDKs. I have to use preprocessor directives to conditionally compile code that are relevant to the SDK for which the application is being built like below: #ifdef S60_2nd_ED Code #elif S60_3rd_ED Code #else Code Now since the application I am developing is not trivial it will soon grow to tens of thousands of lines of code and preprocessor directives like above would be spread all over. I want to know is there any alternative to this or may be a better way to use these preprocessor directives in this case. Please help.
I've been exactly where you are. One trick is, even if you're going to have conditions in code, don't switch on Symbian versions. It makes it difficult to add support for new versions in future, or to customise for handsets which are unusual in some way. Instead, identify what the actual properties are that you're relying on, write the code around those, and then include a header file which does: #if S60_3rd_ED #define CAF_AGENT 1 #define HTTP_FILE_UPLOAD 1 #elif S60_2nd_ED #define CAF_AGENT 0 #if S60_2nd_ED_FP2 #define HTTP_FILE_UPLOAD 1 #else #define HTTP_FILE_UPLOAD 0 #endif #endif and so on. Obviously you can group the defines by feature rather than by version if you prefer, have completely different headers per configuration, or whatever scheme suits you. We had defines for the UI classes you inherit from, too, so that there was some UI code in common between S60 and UIQ. In fact because of what the product was, we didn't have much UI-related code, so a decent proportion of it was common. As others say, though, it's even better to herd the variable behaviour into classes and functions where possible, and link different versions. [Edit in response to comment: We tried quite hard to avoid doing anything dependent on resolution - fortunately the particular app didn't make this too difficult, so our limited UI was pretty generic. The main thing where we switched on screen resolution was for splash/background images and the like. We had a script to preprocess the build files, which substituted the width and height into a file name, splash_240x320.bmp or whatever. We actually hand-generated the images, since there weren't all that many different sizes and the images didn't change often. The same script generated a .h file containing #defines of most of the values used in the build file generation. This is for per-device builds: we also had more generic SIS files which just resized images on the fly, but we often had requirements on installed size (ROM was sometimes quite limited, which matters if your app is part of the base device image), and resizing images was one way to keep it down a bit. To support screen rotation on N92, Z8, etc, we still needed portrait and landscape versions of some images, since flipping aspect ratio doesn't give as good results as resizing to the same or similar ratio...]
857,786
858,022
Call member functions of members of elements of a container with for_each?
Confusing title, hopefully some code will clarify: struct MyNestedType { void func(); }; struct MyType { MyNestedType* nested; } std::vector<MyType> vec; // ... populate vec // I want something approximating this line, but that doesn't use made-up C++! std::for_each(vec.begin(), vec.end(), std::mem_fun_ref(&MyType::nested->func)); So basically I want to call a method on each element of the container, but it's not actually a method of the type, it's some method on a contained type... I know I could write a function object to 'pass on' the call but there are a few methods I'd like to call and that will get messy. Any ideas?
You can use such functor template <typename T, T* MyType::* TMember, void (T::* TNestedMember)() > struct Caller { Caller() { } template <typename TObject> void operator()(TObject object) { (object.*TMember->*TNestedMember)(); } }; To solve your problem struct MyNestedType { MyNestedType(int a): a_(a){ } void func() { std::cout << "MyNestedType::func " << a_ << std::endl; } void foo() { std::cout << "MyNestedType::foo " << a_ << std::endl; } int a_; }; struct MyType { MyNestedType* nested; }; int main() { std::vector<MyType> vec; std::auto_ptr<MyNestedType> nt1(new MyNestedType(2)); std::auto_ptr<MyNestedType> nt2(new MyNestedType(5)); MyType t1 = {nt1.get()}; MyType t2 = {nt2.get()}; vec.push_back(t1); vec.push_back(t2); std::for_each(vec.begin(), vec.end(), Caller<MyNestedType, &MyType::nested, &MyNestedType::func>()); std::for_each(vec.begin(), vec.end(), Caller<MyNestedType, &MyType::nested, &MyNestedType::foo>()); }
857,962
858,013
Qt QImage pixel manipulation problems
I'm currently in the process of writing a steganography application with Qt. I am trying to hide my message bits in the least significant bit of the blue colour of the pixel. From debugging I can tell that this section is working as it should. However after hiding my bits in the message I then save the image and then reopen it. This is where the problem develops. When I read in the (reopened) image the scanLines that I read in are not the same as the ones I wrote previously, and I can't figure out why. Maybe it's just me being stupid, or maybe I'm missing something. Any help would be much appreciated. The code I have so far is as follows void MainWindow::Encrypt(QImage image, QString message) { if(image.isNull()) { qDebug() << "PROBLEM"; } image = image.convertToFormat(QImage::Format_ARGB32); QVector<bool> bvec; QByteArray bytes = message.toAscii(); char mask; QRgb tempPix; for(int i = 0; i < bytes.size(); i++) { for(int j = 0; j < 8; j++) { mask = (0x01 << j); bvec.push_back((bytes[i] & mask) == mask); } } if(image.height() < bvec.size()) { qDebug() << "Not enough space in image"; } for(int j = 0; j < bvec.size(); j++) { QRgb *pixel = (QRgb *)image.scanLine(j); tempPix = *pixel; int blue = qBlue(tempPix); blue &= 0xFE; blue |= (bvec[j] == 1) ? 0x01 : 0x00; *pixel = qRgba(qRed(tempPix), qGreen(tempPix), blue, qAlpha(tempPix)); } if(image.save(filename) != true) { emit addToStatusLog("Did not save. Error"); } } void MainWindow::Decrypt(QImage image) { char temp = 0x00; qint8 mask = 0x01; QVector<bool> bvec; QRgb *pixel; int blue; image = image.convertToFormat(QImage::Format_ARGB32); for(int i = 0; i < image.height(); i++) { pixel = (QRgb *)image.scanLine(i); blue = qBlue(*pixel); bvec.push_back((blue & mask) == mask); } for(int j = 0; j < bvec.size(); j++) { if(j % 8 == 0 && j != 0) { qDebug() << temp; temp = 0x00; } temp |= (bvec[j]) ? (0x01 << (j%8)) : 0x00; } qDebug() << temp; } Thanks
Make sure you're not saving using a lossy format, such as JPEG.
858,035
858,057
Union – useless anachronism or useful old school trick?
I recently came across a great data structures book,"Data Structures Using C" (c) 1991, at a local Library book sale for only $2. As the book's title implies, the book covers data structures using the C programming language. I got the book knowing it would be out-dated but would probably contain lots of advanced C topics that I wouldn't encounter elsewhere. Sure enough within 5 minutes I found something I didn't know about C. I came across a section talking about the union keyword and I realized that I had never used it, nor ever seen any code that does. I was grateful for learning something interesting and quickly bought the book. For those of you not knowledgeable about what a union is, the book uses a good metaphor to explain: To fully understand the concept of a union, it is necessary to examine its implementation. A Structure may be regarded as a road map to an area of memory. It defines how the memory is to be interpreted. A union provides several different road maps for the same area of memory, and it is the responsibility of the programmer to determine which road map is in current use. In practice, the compiler allocates sufficient storage to contain the largest member of the union. It is the road map, however, that determines how that storage is to be interpreted. I could easily come up with contrived situations or hacks where I would use a Union. (But I am not interested in contrived situations or hacks...) Have you used or seen an implementation where using Union solved the problem **more elegantly** than not using a Union? Added bonus if you include a quick explanation of why using union was better/easier than not using a union.
UNIONs implement some sort of polymorphism in a non-OOP world. Usually, you have a part which is common and depending on that part, you use the rest of the UNIONs. Therefore, in such cases where you do not have an OOP language and you want to avoid excessive pointer arithmetic, unions can be more elegant in some cases.
858,252
858,322
Alternatives to MS strncpy_s
What are some alternatives to the Microsoft security enhanced functions such as strncpy_s or _itoa_s? Although developing in MS environment the goal is to write code that could be ported easily to other platforms.
Rageous is correct, there is no complex logic behind it. I would just use Microsoft's version for now and if you decide to port to another OS later, THEN implement it yourself for the target platform and use preprocessor commands to specify your implementation on the non-Windows platform(s).
858,338
858,436
what could be wrong with: char* param= new char[200];
I'm writing a program in C++ and for some reason I'm getting a segmentation error at the following line: char* param= new char[200]; I've tried different variations and even tried putting before it int* param= new int;//for no reason and the same error occurs. What might I have done to cause this problem? What could possibly cause a simple memory allocation like this to give problems. I would include the rest of the program, but it's over 1000 lines. But feel free to ask for more info.
I'd say Neil's on the right track - it's probably something you trampled earlier on that's only being caught there. Have you made sure that: All previous allocations succeeded. You've not written past the end or beginnings of any arrays (there's a plethora of information and tools for bounds checking out there). [Edit] In response to your comment about having 4GB of RAM, suppose you code effectively does the following: unsigned int amountToAllocate = 0; amountToAllocate -= 1; int* someStorage = new int[amountToAllocate]; someStorage[0] = 5; ...because amountToAllocate is an unsigned int, it will wrap round to it's maximum value (4294967295 if unsigned ints are 32 bit on your hardware). So you'd be trying to allocate 4294967295*4 bytes (again, assuming ints are 32 bit for you)... which is ~4*4GB and will fail and die a nasty death.
858,977
859,086
C enum different compilers
I'm building an application that needs to compile on both Windows and Linux. The application is written in C, almost everything works except the MinGW compiler refuses this typedef struct somestruct{ ...snip... enum {NODE, REAL} type; }; somestruct* something; switch (something->type){ case NODE: ...stuff...; break; case REAL: ...otherstuff...; break; } It says NODE and REAL are not defined, But if I supply a scope resolution case somestruct::NODE This compiles with MinGW 3.4.1, but fails to compile with gcc 4.1.2 on linux. Is this simply a compiler issue that needs to be resolved with preprocessors or is there some other explanation?
If you get rid of the nesting, it should work portably: typedef enum somestruct_type { somestruct_type_NODE, somestruct_type_REAL } somestruct_type; typedef struct somestruct { ...snip... somestruct_type type; } somestruct; I have seen code very similar to this be ported to a large number of C and C++ compilers. (I'm not saying this is the only way to do it; I'm just saying that this way works).
859,267
859,393
Stange seg fault when using += with strings
There must be something obvious I don't realize about C++ with this one. load(string & filename){ string command; char delimiter = '/'; size_t delimiterPos = filename.rfind(delimiter); string directory = string(filename.c_str(),delimiterPos); command = "import path "; //want to add directory to end of command string temp = command + "hello!"; // This works command.append(directory); //This works! command += directory; //This seg faults! ... } in GDB when I "print" filename at the beginning of the function I get: (const string &) @0x9505f08: {static npos = 4294967295, _M_dataplus = {> = {<__gnu_cxx::new_allocator> = {}, }, _M_p = 0x950a8e4 "../config/pythonFile.py"}} What the heck, how is filename formatted incorrectly, such that .append() works and += doesn't?! Something strange in the overloaded function += in C++? g++ version 3.4.6
Maybe it has to do with how you are constructing "directory" here size_t delimiterPos = filename.rfind(delimiter); string directory = string(filename.c_str(),delimiterPos); Is rfind somehow failing? If rfind failed, it would return std::npos as specified here. I'm not sure what the behavior would be if you passed npos into the string constructor. It may be platform dependent. This doesn't answer why "append" would work and "+=" would crash. You may also have some kind of heap corruption (maybe caused by the npos and C string passed into the constructor above) and maybe when += is called new memory needs to be allocated. Append for whatever reason may not need to allocate new memory. In any case, it would be wise to add a check for npos.
859,304
859,841
Convert CString to const char*
How do I convert from CString to const char* in my Unicode MFC application?
To convert a TCHAR CString to ASCII, use the CT2A macro - this will also allow you to convert the string to UTF8 (or any other Windows code page): // Convert using the local code page CString str(_T("Hello, world!")); CT2A ascii(str); TRACE(_T("ASCII: %S\n"), ascii.m_psz); // Convert to UTF8 CString str(_T("Some Unicode goodness")); CT2A ascii(str, CP_UTF8); TRACE(_T("UTF8: %S\n"), ascii.m_psz); // Convert to Thai code page CString str(_T("Some Thai text")); CT2A ascii(str, 874); TRACE(_T("Thai: %S\n"), ascii.m_psz); There is also a macro to convert from ASCII -> Unicode (CA2T) and you can use these in ATL/WTL apps as long as you have VS2003 or greater. See the MSDN for more info.
859,433
864,504
Which issues have you encountered due to sequence points in C and C++?
Below are two common issues resulting in undefined behavior due to the sequence point rules: a[i] = i++; //has a read and write between sequence points i = i++; //2 writes between sequence points What are other things you have encountered with respect to sequence points? It is really difficult to find out these issues when the compiler is not able to warn us.
Here is a simple rule from Programming principles and practices using c++ by Bjarne Stroustup "if you change the value of a variable in an expression.Don't read or write twice in the same expression" a[i] = i++; //i's value is changed once but read twice i = i++; //i's value is changed once but written twice
859,501
1,988,688
Learning OpenGL in Ubuntu
I'm trying to learn OpenGL and improve my C++ skills by going through the Nehe guides, but all of the examples are for Windows and I'm currently on Linux. I don't really have any idea how to get things to work under Linux, and the code on the site that has been ported for Linux has way more code in it that's not explained (so far, the only one I've gotten to work is the SDL example: http://nehe.gamedev.net/data/lessons/linuxsdl/lesson01.tar.gz). Is there any other resource out there that's a bit more specific towards OpenGL under Linux?
The first thing to do is install the OpenGL libraries. I recommend: freeglut3 freeglut3-dev libglew1.5 libglew1.5-dev libglu1-mesa libglu1-mesa-dev libgl1-mesa-glx libgl1-mesa-dev Once you have them installed, link to them when you compile: g++ -lglut -lGL -lGLU -lGLEW example.cpp -o example In example.cpp, include the OpenGL libraries like so: #include <GL/glew.h> #include <GL/glut.h> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glext.h> Then, to enable the more advanced opengl options like shaders, place this after your glutCreateWindow Call: GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "Error %s\n", glewGetErrorString(err)); exit(1); } fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); if (GLEW_ARB_vertex_program) fprintf(stdout, "Status: ARB vertex programs available.\n"); if (glewGetExtension("GL_ARB_fragment_program")) fprintf(stdout, "Status: ARB fragment programs available.\n"); if (glewIsSupported("GL_VERSION_1_4 GL_ARB_point_sprite")) fprintf(stdout, "Status: ARB point sprites available.\n"); That should enable all OpenGL functionality, and if it doesn't, then it should tell you the problems.
859,517
859,529
OSX equivalent of ShellExecute?
I've got a C++ app that I'm porting from Win32 to OSX. I'd like to be able to launch arbitrary files as if the user opened them. This is easy on windows using ShellExecute. How do I accomplish the same thing on the Mac? Thanks!
You can call system(); in any C++ application. On OSX, you can use the open command to launch things as if they were clicked on. From the documentation for open: The open command opens a file (or a directory or URL), just as if you had double-clicked the file's icon. If no application name is specified, the default application as determined via LaunchServices is used to open the specified files. All together, it would look like: string command = "open " + filePath; system(command.c_str());
859,535
859,586
How do I convert a big-endian struct to a little endian-struct?
I have a binary file that was created on a unix machine. It's just a bunch of records written one after another. The record is defined something like this: struct RECORD { UINT32 foo; UINT32 bar; CHAR fooword[11]; CHAR barword[11]; UNIT16 baz; } I am trying to figure out how I would read and interpret this data on a Windows machine. I have something like this: fstream f; f.open("file.bin", ios::in | ios::binary); RECORD r; f.read((char*)&detail, sizeof(RECORD)); cout << "fooword = " << r.fooword << endl; I get a bunch of data, but it's not the data I expect. I'm suspect that my problem has to do with the endian difference of the machines, so I've come to ask about that. I understand that multiple bytes will be stored in little-endian on windows and big-endian in a unix environment, and I get that. For two bytes, 0x1234 on windows will be 0x3412 on a unix system. Does endianness affect the byte order of the struct as a whole, or of each individual member of the struct? What approaches would I take to convert a struct created on a unix system to one that has the same data on a windows system? Any links that are more in depth than the byte order of a couple bytes would be great, too!
As well as the endian, you need to be aware of padding differences between the two platforms. Particularly if you have odd length char arrays and 16 bit values, you may well find different numbers of pad bytes between some elements. Edit: if the structure was written out with no packing, then it should be fairly straightforward. Something like this (untested) code should do the job: // Functions to swap the endian of 16 and 32 bit values inline void SwapEndian(UINT16 &val) { val = (val<<8) | (val>>8); } inline void SwapEndian(UINT32 &val) { val = (val<<24) | ((val<<8) & 0x00ff0000) | ((val>>8) & 0x0000ff00) | (val>>24); } Then, once you've loaded the struct, just swap each element: SwapEndian(r.foo); SwapEndian(r.bar); SwapEndian(r.baz);
859,963
859,974
What does the | operator mean in a function call? [C++]
I usually see this when looking at Win32 gui code. My assumption is that it is a standard bitwise or, but I also occasionaly see it in C#, and it seems like there would be a better (well higher level) way to do the same thing there. Anyway, here's an example: MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); Thanks, Seamus
The | is a bitwise OR. MB_OK and MB_ICONEXCLAMATION are defined constants which are a power of 2 (such as 32 or 128), so that the bitwise OR can combine them (128 | 32 would be 160, which has two bits set). This is normal when the bits are used as flags.
860,339
860,353
What is the difference between public, private, and protected inheritance in C++?
What is the difference between public, private, and protected inheritance in C++? All of the questions I've found on SO deal with specific cases.
To answer that question, I'd like to describe member's accessors first in my own words. If you already know this, skip to the heading "next:". There are three accessors that I'm aware of: public, protected and private. Let: class Base { public: int publicMember; protected: int protectedMember; private: int privateMember; }; Everything that is aware of Base is also aware that Base contains publicMember. Only the children (and their children) are aware that Base contains protectedMember. No one but Base is aware of privateMember. By "is aware of", I mean "acknowledge the existence of, and thus be able to access". next: The same happens with public, private and protected inheritance. Let's consider a class Base and a class Child that inherits from Base. If the inheritance is public, everything that is aware of Base and Child is also aware that Child inherits from Base. If the inheritance is protected, only Child, and its children, are aware that they inherit from Base. If the inheritance is private, no one other than Child is aware of the inheritance.
860,447
860,452
What is the array form of 'delete'?
When I compiled a code using the array name as a pointer, and I deleted the array name using delete, I got a warning about deleting an array without using the array form (I don't remember the exact wording). The basic code was: int data[5]; delete data; So, what's the array form of delete?
The array form of delete is: delete [] data; Edit: But as others have pointed out, you shouldn't be calling delete for data defined like this: int data[5]; You should only call it when you allocate the memory using new like this: int *data = new int[5];
860,468
860,484
Including */ in a C-style block comment
Is there any way to include */ in a C-style block comment? Changing the block comment to a series of line comments (//) is not an option in this case. Here's an example of the sort of comment causing a problem: /** * perl -pe 's/(?<=.{6}).*//g' : Limit to PID */
Usually comments don't need to be literal, so this doesn't come up too often. You can wrap it all in a #if block: #if 0 whatever you want can go here, comments or not #endif
860,602
860,617
Recommended Open Source Profilers
I'm trying to find open source profilers rather than using one of the commercial profilers which I have to pay $$$ for. When I performed a search on SourceForge, I have come across these four C++ profilers that I thought were quite promising: Shiny: C++ Profiler Low Fat Profiler Luke Stackwalker FreeProfiler I'm not sure which one of the profilers would be the best one to use in terms of learning about the performance of my program. It would be great to hear some suggestions.
You could try Windows Performance Toolkit. Completely free to use. This blog entry has an example of how to do sample-based profiling.
860,673
879,992
Programmatically disable/enable network interface
I'm trying to come up with a solution to programmatically enable/disable the network card - I've done a ton of research and nothing seems to be a workable solution in both XP and Vista environments. What I'm talking about is if you went into the Control Panel 'Network Connections', right clicked on one and picked either enable or disable. Ideally I'd like to use a library, but if worse comes to worse I supposed I could call out to a commandline app, but that's absolute worst case. Here's what I've tried so far and where/why they failed: This previous post: How to programmatically enable/disable network interfaces? (Windows XP) Lists a couple of methods - the first is using netsh, which appears to be the same as using the IPHelper function SetIfEntry(). The problem with this is that it sets the interface as Administratively enabled or disable, not the normal enabled/disabled so it doesn't actually shut down the NIC. Another solution proposed is using WMI and in particular Win32_NetworkAdapter class, which has an Enable and Disable method: http://msdn.microsoft.com/en-us/library/aa394216(VS.85).aspx Great right? Works fine in Vista, those methods don't exist in a normal XP install... Another suggestion is to use DevCon, which really uses the SetupAPI, in particular SetupDiSetClassInstallParams() with the DICS_ENABLE. After spending countless hours with this wonderful class, and trying to disable/enable the device both at the global level as well as the specific configuration level (and every combination), it doesn't consistently work either - sometimes working fine, but other times disabling the device in the Device Manager, but still leaving it up and operational in the Network Connections. I then tried using the INetConnection interface, specifically INetConnection->Connect/Disconnect: http://msdn.microsoft.com/en-us/library/aa365084(VS.85).aspx But I was never able to get this to have any effect on the connections on either my Vista or XP test boxes. Finally, I found this C# script called ToggleNic: http://channel9.msdn.com/playground/Sandbox/154712/ Which looks like it's going through the Shell somehow to effectively cause the right-click behavior. The limitation (at least of this implementation) is that it doesn't work (without modification) on non-English systems, which I need mine to work with. To be fair, this solution looks like the most viable, but my familiarity with C# is low and I couldn't find if the API it's using is available in C++. Any help or insights would be greatly appreciated - or ideas on how to accomplish what the togglenic script does in C++. Thanks!
After testing on more platforms and more approaches, I've basically given up on this functionality (at least for my purposes). The problem for me is that I want to have something that works in 90%+ of the situations, and the reality is that with everything I could come up with, it's closer to 70%. The ironic thing is that it's actually just as flaky through the normal Windows method. For those who still want to go down this perilous path, here's what I found: Of the API direct methods described above, the one which worked the most consistently was using the SetupAPI (SetupDiSetClassInstallParams) - the biggest problem I ran into with this is that sometimes it would get in a state where it would require a reboot and no changes would work until that happened. The only other thing to be aware of when using this is that there are two profiles for devices, so you need to toggle them both in some cases. The DDK contains the source to the devcon tool, which shows you exactly how to do everything. This ultimately looked like it was the closest to right-clicking, but it still exhibited some strange behavior that Network Connections didn't. This approach seemed to work about 70% of the time (in both tests and on test systems). From the total hack approach, the best I found was not using the technique that ToggleNIC did, but instead use the IShellFolder stuff - this allows you to use GetCommandString which is language-independent. The problem with this is that under XP GetCommandString doesn't return anything (oh joy), but it did appear that the menu ID's for 'enable' and 'disable' were consistent (16 and 17 respectively), so if I failed to GetCommandString, I just fell back to the menu ID's. To Toggle, just call InvokeCommand with either the string if it returned one, or the menu ID if it didn't. The problem with this was that just like the normal Windows way, sometimes it doesn't work, nor does it give you any indication of what's going on or why it failed. This approach seemed to work about 70% of the time as well, but was much harder to tell if something went wrong, plus the normal "Enabling interface..." text would pop up. Hopefully this helps anyone else - and if anyone manages to find another way that works in more situations, I'd love to hear it!
860,685
860,788
Reading from file using fgets() causes "Access Violation reading from address..." c++
I'm Using FILE * F opened in _sfopen () I'm reading from the file in while(!feof(f)) and then fgets(str,1024,f) when running reaches the last line it still goes in the while but then when trying to fgets it flies out with an access violation arror (menwhile I just put a try and catch(...) but I know It's not a good solution ) what shoul I change for fixing the problem? Plus- if I want to read line by line is it correct just to give the size of 1024 or it might fail -- I had a file where due to the size it read each time from the middle of a line till the middle of next line - is there a better way to read a line because I have no idea how my files will look like (if the have \n at the end etc...) thanks!
You specified C++ as tag, maybe use a filestream (std::ifstream for input from file) and the global getline() function to get it line by line and put it in a std::string for further analysis/manipulation. For an example look here (2nd example in the "Text files" paragraph)
860,779
860,934
Collision problems with OSlib for psp in C++
Im using oslib with the pspsdk toolchain and for some reason this doesnt work the way I think it would 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; //Bush 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 == 0) { sprite->y += 4; sprite_position = DOWN; SpriteAnimate(); } else { sprite->y -= 6; bushcol = 0; } } if (osl_keys->held.up) { if (bushcol == 0) { sprite->y -= 4; sprite_position = UP; SpriteAnimate(); } else { sprite->y += 6; bushcol = 0; } } if (osl_keys->held.right) { if (bushcol == 0) { sprite->x += 4; sprite_position = RIGHT; SpriteAnimate(); } else { sprite->x -= 6; bushcol = 0; } } if (osl_keys->held.left) { if (bushcol == 0) { sprite->x -= 4; sprite_position = LEFT; SpriteAnimate(); } else { sprite->x += 6; bushcol = 0; } } The sprite starts moving in the opposite direction from the bush when I try to move away but does fall free eventually any better collision methods or suggestions I even tried this for each button and still no luck if (osl_keys->held.down) { if ( (sprite->x + spritewidth > bush->x) && (sprite->x < bush->x + bushwidth) && (sprite->y + spriteheight > bush->y) && (sprite->y < bush->y + bushheight) ) { sprite->y -= 4; } else { sprite->y += 2; sprite_position = DOWN; SpriteAnimate(); } }
One thing you can do, is instead of having the character "move backwards" when he hits the bush, you can have his position changed. What I mean is something like this: (Using only up for the example). if (osl_keys->held.up) { if (bushcol == 0) { sprite->y -= 4; sprite_position = UP; SpriteAnimate(); } else { sprite->y = bush->y + 2; bushcol = 0; } } That way, whenever the sprite collides, it just sets the position instead getting it to move backwards. There are other methods for doing collision detection, but I'm way too tired right now to pull off an intelligent, much less readable, answer right now... A search on google will turn up many results.
860,863
860,883
Why does a compiler dislike implicitly casting to uint's?
I have run into a couple of similar quirks regarding uint usage in both C++ and C#, and now I'm wondering on the reasoning (which may be completely different for each example). For both of these examples, note that I am compiling with the warning levels set to maximum. (1) gcc complains about comparing an int to a uint in the following, whereas vc++ does not: uint foo = <somevalue>; if( foo == ~0 ) //right here ... Comparing to 0 is just fine without any casting on both gcc and vc++. (2) In C# 3.5, I just ran into a similiar issue. The following works fine: uint foo = 1; uint bar = 2; But this gives a uint/int warning: bool condition = <somevalue>; uint foo = condition ? 1 : 2; //right here What gives, why is the compiler so sensitive about signed-ness of immediate values? I completely understand the issue when assigning from variables, but this just doesn't make sense to me for immediate values; is there some hidden difficulty in the parsing that prevents this behavior from being allowed? Or what? Edit: Yes, I know I can suffix my numbers with 'u', but that sidesteps my question, which is about implicitly casting to the left-hand-side, not explicitly casting the right-hand-side.
I can't speak for gcc but as for the C# 3 compiler you need to explicitly tell it that these ints ought to be unsigned: uint foo = condition ? 1U : 2U; The C# compiler loves ints and assumes all integral values within range are ints. Since your expression is using a conditional operator the compiler is too eager to assume your literal values are ints and then the assignment fails. Edit: Note that I said integral values that are within range of a System.Int32. Consider this example: using System; class Program { static void Main() { Console.WriteLine(1.GetType()); Console.WriteLine(2147483648.GetType()); } } Output: System.Int32 System.UInt32
860,877
860,980
Using typedefs (or #defines) on built in types - any sensible reason?
Well I'm doing some Java - C integration, and throught C library werid type mappings are used (theres more of them;)): #define CHAR char /* 8 bit signed int */ #define SHORT short /* 16 bit signed int */ #define INT int /* "natural" length signed int */ #define LONG long /* 32 bit signed int */ typedef unsigned char BYTE; /* 8 bit unsigned int */ typedef unsigned char UCHAR; /* 8 bit unsigned int */ typedef unsigned short USHORT; /* 16 bit unsigned int */ typedef unsigned int UINT; /* "natural" length unsigned int*/ Is there any legitimate reason not to use them? It's not like char is going to be redefined anytime soon. I can think of: Writing platform/compiler portable code (size of type is underspecified in C/C++) Saving space and time on embedded systems - if you loop over array shorter than 255 on 8bit microprocessor writing: for(uint8_t ii = 0; ii < len; ii++) will give meaureable speedup.
The C standard doesn't specify the size of a number of the integer types; it depends on the compiler, and the processor on which the code will run. Therefore, for maximum portability, it's best to have a header which uses standard names which indicate how big each type is for that particular target. MISRA-C and others use uint16_t, sint32_t, etc. A shorter form, e.g. u16, s32 is also in use. Regarding #define v typedef: use typedef, to enforce type checking by the compiler.
860,880
863,093
Why would I get a GPF in DLLMain when run as a restricted user?
Why is this code crashing when run as a restricted user, but not when run as an admin of the machine? extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { hInstance; m_hInstance=hInstance; return _AtlModule.DllMain(dwReason, lpReserved); } The code is crashing on the return... and I don't know why. I am getting: The instruction at "0x7c90100b" referenced memory at "0x00000034". The memory could not be "read". Furthermore, _AtlModule.DLLMain looks like this: inline BOOL WINAPI CAtlDllModuleT<T>::DllMain(DWORD dwReason, LPVOID lpReserved) throw() { #if !defined(_ATL_NATIVE_INITIALIZATION) dwReason; lpReserved; #pragma warning(push) #pragma warning(disable:4483) using namespace __identifier("<AtlImplementationDetails>"); #pragma warning(pop) if (dwReason == DLL_PROCESS_ATTACH) { ATLASSERT(DllModuleInitialized == false); } return TRUE; #else return _DllMain(dwReason, lpReserved); #endif } We are importing the ATL DLL, and tried linking statically as well... no luck. UPDATE Using ProcMon, I get a buffer overflow here: RegQueryValue HKU\S-1-5-21-448539723-854245398-1957994488-1005\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Cache BUFFER OVERFLOW Length: 144 What does this mean?
When you get an error saying you can't reference a memory at some 0x0000... location, it usually means your code is trying to reference a member variable of some object, but the object pointer points to NULL. In this case, the member variable is 0x34 bytes into the object. Further guessing, given that it only fails when running under a restricted user, I'd say some operation that is supposed to return a pointer to an object fails due to insufficient rights. If the returned pointer is not tested for being null, the code will continue running until someone tries to read one of its member variables, at which point you get the crash. what I would do is thoroughly debug the code and look for suspicious NULLs. Also, you might want to run your app under AppVerifier with the LuaPriv test on. If my guess is correct, some API calls failures would be reported, manifested in your code as returned NULLs. AppVerifier should also provide you the stack trace, so you'll be able to easily find the root of the problem.
860,923
863,606
Unit testing with -fno-access-control
I have seen many crazy methods to get access to private variables when unit testing. The most mind-blowing I've seen is #define private public. However, I've never seen anyone suggest turning off private variables at the compiler level. I had always just assumed that you couldn't. I've complained to many a developer that unit testing would be a lot easier if you could just tell the compiler to back off for this one file. Then I stumble across the -fno-access-control GCC compiler option. It's so obviously the perfect way to unit test. Your original source files are unmodified, no injected friends just for the unit test, no recompiling with bizarre preprocessor magic. Just flick the 'no access control' switch when compiling your unit tests. Am I missing something? Is this the unit testing silver bullet I hope it is? The only disadvantage I see is the GCC-specific nature of the technique. However, I assume MSVS has a similar flag.
I would argue that unit tests should not need access to private members. In general, unit tests are meant to test the interface to your classes, not the internal implementation. That way, changes to the internals will only break the tests if the interface has been compromised. Have a look at my answer to a similar question, and the ensuing discussion. It is a controversial topic, to be sure, but that's my $0.02.
861,007
861,032
How do I bounce a point off of a line?
I'm working on writing a Pong game and I've run across a problem. I'm trying to figure out how to bounce a point off of a line. The best method I can figure out to do this with is Calculate the current and future position of the Ball. Line Segment: {Ball.location, Ball.location + Ball.direction} (Ball.location and Ball.direction use a custom vector/coordinate class) Calculate if the generated line segment intersects with any of the walls or paddles. ??? Don't know how to do this yet (Will ask in a separate question) At the first intersection found Bounce the ball off of the line Create a triangle formed with a = Ball's current position b = Intersection point of the line. c = Closest point to the Ball's current position on the line. Find the angle that the ball hits the line angle = cos(distance(b, c) / distance(a, b)) Find the angle to rotate the ball's direction (90 - angle)*2 Rotate Ball's direction and move it to it's new position ignoring distance traveled to hit the line for now, doesn't need to be exactly on the line Else if there is no intersection Move the ball to it's new position. Is this an acceptable method or am I missing something?
You just need to check if the center of the ball is within its radius of the paddle to tell whether or not its time to bounce. There was an older question asked that has several answers on calculating bounce angle.
861,133
861,497
Accessing a template base classes function pointer type
I have a class that I've been provided that I really don't want to change, but I do want to extend. I'm a pattern and template newbie experimenting with a Decorator pattern applied to a template class. Template class contains a pointer-to-member (if I understand the semantics correctly) in yet another class. The pointer-to-member is the deserializer of an XML istream. The type 'T' is the type of XML document to be deserialized. 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 ); private: MYFUN *fptr; std::string aString1; std::string aString2; }; The typedef looks odd to me after reading http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.5, and yet this class seems to work fine as-is. There aren't any additional #defines in the provided header file, so this is a little mysterious to me. Now I try to extend it, as Decorator because I want to do a bit more work on the auto_ptr object returned by MYFUN: template <typename T> class D : public class B<T> { D( B<T>::MYFUN *fPtr, B<T> *providedBase ); //compiler complaint //Looks like B private: B* base_; }; template <typename T> D<T>::D( B<T>::MYFUN *p, B<T> *base ) //compiler complaint : B<T>::B( p ), base_(providedBase) { } When trying to compile this, I get a syntax complaint at the two lines shown. Error is something like "expected ')' at *". There is no complaint about MYFUN being undefined. When I re-define the pointer-to-member in D with the same signature as in D, i.e. //change MYFUN to NEWFUN in D) typedef std::auto_ptr<T> MYNEWFUN( std::istream&, const std::string&, const std::string& ); This works. I prefer not to have to do this for every D/Decorator I might make of B. I tried to perform the typedef more globally, but couldn't get the syntax right due to the template parameter being undefined.
The compile error is due to the fact that the compiler can't tell you are talking about a type. Try: D( typename B<T>::MYFUN *fPtr, B<T> *providedBase ); and template <typename T> D<T>::D( typename B<T>::MYFUN *p, B<T> *base ) See: the templates section of the C++ FAQ Lite for more details on why this is necessary, but the summary is that because of the possibility of template specialization, there is no way for the compiler to be sure that B<T>::MYFUN is actually referring to a type.
861,154
863,583
Winsock error code 10014
string SendRequestToServer(std::string url) { struct sockaddr_in addr = { 0 }; struct hostent *host = NULL; // If the URL begins with http://, remove it. if(url.find("http://") == 0) url.erase(0, 7); // Get the host name. string hst = url.substr(0, url.find('/', 0)); url.erase(0, url.find("/", 0)); // Connect to the host. host = gethostbyname(hst.c_str()); if(!host) { Print("%s", "Could not resolve the hostname."); int error = WSAGetLastError(); return "failed"; } } It seems I'm returning "failed" quite frequently. Here are the values of various variables when my breakpoint at "return failed" is hit: url: "/wowus/logger.cgi?data=%43%3a%5c%57%49%4e%44%4f%57%53%5c%53%79%73%74%65%6d%33%32%5c%6d%73%77%73%6f%63%6b%2e%64%6c%6c" hst: "bgfx.net" host: NULL error: 10014 What's going on here? More importantly, how can I fix it? NOTE: The original parameter to SendRequestToServer is "bgfx.net/wowus/logger.cgi?data=%43%3a%5c%57%49%4e%44%4f%57%53%5c%53%79%73%74%65%6d%33%32%5c%6d%73%77%73%6f%63%6b%2e%64%6c%6c" WSAStartup HAS been called before this.
Some people report that WS can fail with this error if got pointer inside application stack memory. It looks like you are using VS2005 or newer where std::string has internal 16 chars long buffer - and exactly this buffer address was passed into gethostbyname(). Try to copy your string to heap before passing it to WS: char *hstSZ = new char[hst.size() + 1]; strcpy(hstSZ, hst.c_str(); host = gethostbyname(hstSZ); delete[] hstSZ; And let us know, if it helped :)
861,517
861,556
What issues can I expect compiling C code with a C++ compiler?
If you take an existing C code base and compile it with a C++ compiler, what sort of issues can you expect to crop up? For example, I think that assigning an integer to an value with an enumerated type will fail in C++, whereas it's legal (if a bit nasty) in C. If I don't wrap all my C files in extern C { ... }, am I going to get name-mangling where I least expect it? Is there some reason why I really shouldn't do this? For background, we have a very large code-base written in C. For a few years we've been jumping through hoops to do things that would come naturally via C++ ( homebrewe inheritance, for example). We'd like to start moving towards C++, but in a gradual fashion; getting our CORBA-like framework to support it, and refactoring modules as we go along to take advantage of the more natural approach C++ would provide.
I've done something like this once. The main source of problems was that C++ is more strict about types, as you suspected. You'll have to add casts where void* are mixed with pointers of other types. Like allocating memory: Foo *foo; foo = malloc(sizeof(*foo)); The above is typical C code, but it'll need a cast in C++: Foo *foo; foo = (Foo*)malloc(sizeof(*foo)); There are new reserved words in C++, such as "class", "and", "bool", "catch", "delete", "explicit", "mutable", "namespace", "new", "operator", "or", "private", "protected", "friend", etc. These cannot be used as variable names, for example. The above are probably the most common problems when you compile old C code with a C++ compiler. For a complete list of incompatibilities, see Incompatibilities Between ISO C and ISO C++. You also ask about name mangling. In absence of extern "C" wrappers, the C++ compiler will mangle the symbols. It's not a problem as long as you use only a C++ compiler, and don't rely on dlsym() or something like that to pull symbols from libraries.
861,532
861,649
Making all variables in a program modifiable at runtime by the programmer, smart idea?
I was thinking of doing this with C++, basically from an external editor or something the programmer can say: MyClass::dude = "hello" where 'dude' is a static integer in 'MyClass'. What the program does at runtime is it partitions the input to MyClass :: dude = "hello" and finds the class called 'MyClass' and assigns the dude variable in it as "hello". The idea behind it is for it to act as a sort of a runtime debugger. Is this safe/sane?
Yes, this is a typical tool used during development to help fine-tune games. It's not so often something you type in as much as a screen where you can adjust variables on the fly with a controller (that changes some class variable under the hood), but for pc games, there isn't a reason why you couldn't type in something, especially if it's text. You would, of course, need to program your own system where a class notifies some part of your engine of it's name and how to get at some of its variables.
861,707
861,959
Is reducing number of cpp translation units a good idea?
I find that if there are a lot of classes the compilation time is dramatically increased when I use one *.h and one *.cpp file per class. I already use precompiled headers and incremental linking, but still the compile time is very long (yes I use boost ;) So I came up with the following trick: defined *.cpp files as non-compilable defined *.cxx files as compilable added one *.cxx file per application module, and #included all the *.cpp files of this module in it. So instead of 100+ translation units I ended up with only 8 translation units. The compile time became 4-5 times shorter. The downsides are that you have to manually include all the *.cpp files (but it's not really a maintenance nightmare since if you forget to include something the linker will remind you), and that some VS IDE conveniences are not working with this scheme, e.g. Go To/ Move to Implementation etc. So the question is, is having lots of cpp translation units really the only true way? Is my trick a known pattern, or maybe I'm missing something? Thanks!
The concept is called unity build
861,832
861,848
validating CEdit without subclassing
Is there any way to validate the contents of a CEdit box without subclassing? I want to check for invalid filename characters in a CEdit box and not allow the user to input it at all (keypress should not be recorded, if pasted in the box, the invalid characters should just not make it to the edit box).. Is there any easy way to do this? On a side note, how do I make a variable that is tied to this box? If I add a variable that is not a control one, would this variable always contain what is in the edit control? Thanks..
Per http://msdn.microsoft.com/en-us/library/f7yhsd2b(VS.80).aspx , "If you want to handle Windows notification messages sent by an edit control to its parent (usually a class derived from CDialog), add a message-map entry and message-handler member function to the parent class for each message." and "ON_EN_UPDATE The edit control is about to display altered text. Sent after the control has formatted the text but before it screens the text so that the window size can be altered, if necessary." -- so, without subclassing CEdit, you can vet and possibly block updates via the windows message-map/message-handler in the parent.
861,997
862,901
How to place a .net UserControl on a c++ cdialog in visual studio 6
My task is pretty simple create a .net usercontrol and use it in a old visual studio 6 proejct. I have createt the usercontrol (its just a user control with a label), I then followed this guide (http://support.microsoft.com/kb/828736) and it seems to work fine. But how can I display the usercontrol? Do I have to use CreateControl, and how should I do that? The .net looks like tihs: namespace dotnetcotrol { public interface dotnetcontrol { void setText(string str); } public partial class dontnetcontrolClass : UserControl, dotnetcontrol { public dontnetcontrolClass() { InitializeComponent(); } public void setText(string str) { label1.Text = str; } } } And the c++ code looks almost like the one in the ms example however my project is a a window mfc project.
For something this simple, why not write your own class that inherits CWnd? Is there a reason the control needs to be a .Net UserControl? That said, the route I would take to host a .Net control on a VC++ 6 form would be to reverse-engineer the source of the VC++ 8 (VC++ 2005) CWinFormsUserControl class. If you have Visual Studio 2005 with VC++ installed, you have the source to this class under %PROGRAMFILES%\Microsoft Visual Studio 8\VC\atlmfc\src\mfcm.
862,051
908,186
What is the difference between ImageMagick and GraphicsMagick?
I've found myself evaluating both of these libs. Apart from what the GraphicsMagick comparison says, I see that ImageMagick still got updates and it seems that the two are almost identical. I'm just looking to do basic image manipulation in C++ (i.e. image load, filters, display); are there any differences I should be aware of when choosing between these libraries?
From what I have read GraphicsMagick is more stable and is faster. I did a couple of unscientific tests and found gm to be twice as fast as im (doing a resize).