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
1,442,162
1,442,194
StretchDIBits failed, sometimes it draw nothing,
I am using gdi c++, StretchDIBits function sometimes failed if I draw large Images such as 7000*5000. It draw nothing. GetLastError() says no enough system resource. Can anyone explain why StretchDIBits need resource even The DC is prepared successfully.
It may be that StretchDIBits expands the source image into a temporary bitmap of the same dimensions as the destination bitmap, and then copies the temporary into the destination as the final step. So even if you have enough memory to create the destination bitmap (140 MB) before the StretchDIBits call, your system doesn't have the additional 140 MB to allocate to the temporary bitmap.
1,442,213
1,442,238
CreateDIBSection failed
BITMAPINFO bmi; memset(&bmi,0,sizeof(BITMAPINFO)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth =m_pImg->GetWidth(); bmi.bmiHeader.biHeight =m_pImg->GetHeight(); bmi.bmiHeader.biPlanes = 1; //if( m_pImg->GetInfo()->biBitCount!=16) //{ // bmi.bmiHeader.biBitCount = m_pImg->GetInfo()->biBitCount; //} //else //{ //ASSERT((m_pImg->GetInfo())->bmiHeader->biBitCount == 24); bmi.bmiHeader.biBitCount=24; bmi.bmiHeader.biCompression = BI_RGB; if (bmi.bmiHeader.biSizeImage == 0) bmi.bmiHeader.biSizeImage = WidthBytes(bmi.bmiHeader.biWidth,bmi.bmiHeader.biBitCount) * bmi.bmiHeader.biHeight; if(bmi.bmiHeader.biClrUsed == 0 && bmi.bmiHeader.biBitCount <16) bmi.bmiHeader.biClrUsed=DWORD(1 <<bmi.bmiHeader.biBitCount); m_nNewSize=bmi.bmiHeader.biSizeImage; if(m_hbmCanvasBitmap!=NULL) { DeleteObject(m_hbmCanvasBitmap); m_hbmCanvasBitmap=NULL; m_pCanvasBits=NULL; } // 创建直接与DC相关联的位图 m_hbmCanvasBitmap=CreateDIBSection(m_hDC, &bmi, DIB_RGB_COLORS,(void**)&m_pCanvasBits, NULL, NULL); // after CreateDIBSection I found the error code is 8, no enough resource. How can I avoid this error? I pass width: 3500 height 2500 many thanks!
I think the answer to this is the same as the answer to your earlier question: your bitmaps are way too big. Also, since your dimensions are now half the dimensions of the bitmap in your earlier question, I'm guessing you're trying to break the destination up into quadrants, but now you don't have enough resources to even create the destination bitmap. This may mean that you're also not releasing the bitmap memory from your previous attempts. You may want to reboot and try all this again with much smaller destination images.
1,442,258
1,442,301
How do applications like Google Sidebar reduce the desktop size?
I'm trying to write an application which will sit at the top of the desktop on top of every window. I need this window however to not just sit on top of other windows, but to actually reduce the size of the desktop so when these windows maximise they don't get covered up by my application's bar. So, basically, I want my application's window behaviour to match that of the Windows taskbar. Is that possible?
Yes, it is. These windows are known as Application Desktop Toolbars. MSDN has a reference page on them here.
1,442,436
1,442,754
Script to insert logging into every function in a project?
I have inherited a fairly large codebase, 90% C++, and I need to get up to speed on it quickly. There are hundreds of .cc files in a wide directory tree structure. It's fairly complex, and has no logging. In order to figure out how some major subsystems work, I want to insert a function call into every function. E.g., given a .cc file full of stuff like this: void A::foo(int a, int b) { // ... } void A::bar() { // ... } void B::bleh(const string& in) { // ... } I'd like to get this: void A::foo(int a, int b) { LOG(debug) << "A::foo() called."; // ... } void A::bar() { LOG(debug) << "A::bar() called."; // ... } void B::bleh(const string& in) { LOG(debug) << "B::bleh() called."; // ... } This can be done via python script, CMD script, power shell script, etc. If there is a way to make VS do it, great. Whatever works. Doesn't have to be pretty, I'm not checking any of this in. Also, it doesn't necessarily need to get everything. E.g. nested classes, implementations in header files, etc.
Had something similar for adding profiling code using Macros in VS, here's the code (this also groups everything under a single "undo" command and lists all of the changes in its own output window) Imports System Imports EnvDTE Imports EnvDTE80 Imports System.Diagnostics Public Module Module1 Function GetOutputWindowPane(ByVal Name As String, Optional ByVal show As Boolean = True) As OutputWindowPane Dim window As Window Dim outputWindow As OutputWindow Dim outputWindowPane As OutputWindowPane window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput) If show Then window.Visible = True outputWindow = window.Object Try outputWindowPane = outputWindow.OutputWindowPanes.Item(Name) Catch e As System.Exception outputWindowPane = outputWindow.OutputWindowPanes.Add(Name) End Try outputWindowPane.Activate() Return outputWindowPane End Function Const ToInsert As String = "/* Inserted text :D */" Sub AddProfilingToFunction(ByVal func As CodeFunction2) Dim editPoint As EditPoint2 = func.StartPoint.CreateEditPoint() While editPoint.GetText(1) <> "{" editPoint.CharRight() End While editPoint.CharRight() editPoint.InsertNewLine(1) Dim insertStartLine As Integer = editPoint.Line Dim insertStartChar As Integer = editPoint.LineCharOffset editPoint.Insert(ToInsert) GetOutputWindowPane("Macro Inserted Code").OutputString( _ editPoint.Parent.Parent.FullName & _ "(" & insertStartLine & "," & insertStartChar & _ ") : Inserted Code """ & ToInsert & """" & vbCrLf) End Sub Sub AddProfilingToProject(ByVal proj As Project) If Not proj.CodeModel() Is Nothing Then Dim EventTitle As String = "Add Profiling to project '" & proj.Name & "'" GetOutputWindowPane("Macro Inserted Code").OutputString("Add Profiling to project '" & proj.Name & "'" & vbCrLf) DTE.UndoContext.Open(EventTitle) Try Dim allNames As String = "" For i As Integer = 1 To proj.CodeModel().CodeElements.Count() If proj.CodeModel().CodeElements.Item(i).Kind = vsCMElement.vsCMElementFunction Then AddProfilingToFunction(proj.CodeModel().CodeElements.Item(i)) End If Next Finally DTE.UndoContext.Close() End Try GetOutputWindowPane("Macro Inserted Code").OutputString(vbCrLf) End If End Sub Sub AddProfilingToSolution() GetOutputWindowPane("Macro Inserted Code").Clear() If Not DTE.Solution Is Nothing And DTE.Solution.IsOpen() Then For i As Integer = 1 To DTE.Solution.Projects.Count() AddProfilingToProject(DTE.Solution.Projects.Item(i)) Next End If End Sub End Module P.S Remember to change the "Const ToInsert As String = ..." to the code you actually want to be inserted
1,442,750
1,442,767
The power of .NET without the garbage collection?
I love C# because the powerful features of the .NET framework make it so easy to develop for Windows. However I also love standard C++ primarily because it gives me fine-tuned control over memory management. Is there a way to have the best of both worlds? Are there C++ libraries that can compete with the rich set of libraries in the .NET framework? Or is there a way to manually deallocate memory in one of the .NET languages that I've never used? OR is it possible to use a .NET dll in a standard C++ application? I know, I'm really stretching here, but I believe in magic.
Have you looked at Boost? Alternatively, you can use "C++/CLI" (a.k.a. managed C++, a.k.a. C++.NET); code written in this language can call into .NET APIs and can also manually manage memory via traditional Win32 APIs like HeapAlloc/HeapFree. In my experience, though, this language is most frequently used for writing "glue code", and not for building applications from the ground up.
1,442,762
1,442,835
Challenge working with Visual Studio and VC++?
I have started working with C++ recently and am not comfortable with Visual Studio Development Environment and also I do not have proper understanding of MFC, Win32, ATL, COM Terminologies. From example point of view, I had taken a simple C++ program to see how it works with Visual Studio Environment and I was having some issues to get that code up and running. I would like to request if someone could point me to some online resources/books where I can get more understanding about Visual Studio Development Environment from C++ perspective and get some knowledge about MFC, Win32, ATL, COM Terminologies than it would be really very helpful to me. Note: I have checked MSDN library and some related Microsoft sites but when I see HOW DO I kind of video tutorials they are more from .Net/C#/ASP.Net perspective but I am looking for some online resource for C++/VC++ perspective.
The classic book about Win32 is presumably Petzold's. Petzold's book is I think (I've never read it) mostly about GUI programming; whereas the other classic/recommended Win32 book, which is Richter's, is about 'system' (non-GUI) programming. For learning COM, perhaps Essential COM? Some reviewers praise it, but some others reviews say things like "not for beginners"; but it's how I learned COM, and I found it thorough, low-level, and detailed. It assumes you know C++ (not COM) already. IMO you don't need books about MFC if you already know C++ and the Win32 API, in which case the reference libraries are sufficient. Alternatively, some people recommend an MFC book like Prosise's.
1,443,206
52,044,247
How to determine if 2 paths reference the same file in portable C++
I was wondering if there is a portable way to determine if 2 different paths actually reference the same file. I have read this thread but is Windows-specific. AFAIK, fstream isn't suitable for the job.
Filesystem library Since C++17 you can use the standard <filesystem> library. The function you are looking for is equivalent, under namespace std::filesystem: bool std::filesystem::equivalent(const std::filesystem::path& p1, const filesystem::path& p2 ); To summarize from the documentation: this function takes two paths as parameters and returns true if they reference the same file or directory, false otherwise. There is also a noexcept overload that takes a third parameter: an std::error_code in which to save any possible error. For more information take a look at my answer on the thread you mentioned.
1,443,659
1,443,688
Should I return bool or const bool?
Which is better: bool MyClass::someQuery() const; const bool MyClass::someQuery() const; I've been using 'const bool' since I'm sure I remember hearing it's "what the ints do" (for e.g. comparison operators) but I can't find evidence of that anywhere, mostly due to it being difficult to Google and Intellisense not helping out any ;) Can anyone confirm that? To me returning const values (this isn't just about bools) makes more sense; it'll prevent temporaries being modified, which is almost always going to be a programmer mistake. I just want something to back that up so I can extol returning const values to my colleagues :)
So you know it's right, you're just after the Voice of Authority? Preventing accidental modification of temporaries is very valuable. In general, you should declare as many things as you possibly can const, it protects you from a variety of accidents and gives the optimiser useful hints. D'you have a copy of Scott Meyers' "Effective C++" around? Point them at Item 3 (page 18 in the third edition) ;) It gives the example of class Rational {...}; const Rational operator* (const Rational& lhs, const Rational& rhs ); if( (a * b) = c ) // declaring operator *'s return value const causes error to be caught by compiler
1,443,793
1,443,818
Iterate keys in a C++ map
Is there a way to iterate over the keys, not the pairs of a C++ map?
If you really need to hide the value that the "real" iterator returns (for example because you want to use your key-iterator with standard algorithms, so that they operate on the keys instead of the pairs), then take a look at Boost's transform_iterator. [Tip: when looking at Boost documentation for a new class, read the "examples" at the end first. You then have a sporting chance of figuring out what on earth the rest of it is talking about :-)]
1,443,865
1,443,926
C++ api for understanding tone signals on a phone line
Is there any good c++ source codes or api for handling phone lines like understanding tone signals. For example i like to find out if the person enters 3 (it's likely that this is done using it's tone sound). Do i need a special modem for this purpose or it can be done using only standard modems.
DTMF is the term you are looking for: http://en.wikipedia.org/wiki/Dual-tone_multi-frequency Whether you can process incoming DTMF tones with a particular modem depends on whether the modem supports it. If it does there will be an AT command to manage it, both for issuing outgoing DTMF tones and being notified of incoming DTMF tones. There are some examples here: http://www.tek-tips.com/viewthread.cfm?qid=24275&page=1 The specific AT commands might depend on your particular modem. If your modem can't handle DTMF itself and you're interested in being able to inject DTMF tones into the outgoing audio stream / recognise and extract DTMF tones from the incoming audio then you'll need some DSP support; that's not going to be something you can just do in C++.
1,443,870
1,444,303
C++ difference between automatic type conversion to std::string and char*
As a learning exercise, I have been looking at how automatic type conversion works in C++. I know that automatic type conversion should generally be avoided, but I'd like to increase my knowledge of C++ by understanding how it works anyway. I have created a StdStringConverter class that can be automatically converted to a std::string, but the compiler (g++ 4.3.4 on Debian) seems not to do the conversion when the object is compared against a real std::string (please ignore the lack of passing-by-reference and unnecessary creation of temporary objects): #include <string> class StdStringConverter { public: explicit StdStringConverter(std::string name) : m_name(name) {} operator const std::string () const { return m_name; } private: std::string m_name; }; int main() { StdStringConverter converter(std::string("Me")); const std::string name = "Me"; // Next line causes compiler error: // no match for 'operator==' in 'converter == name' return (converter == name) ? 0 : 1; } On the other hand, if I change it slightly to a CStringConverter class, the automatic conversion does take place, although comparing char pointers probably isn't what I intended: #include <string> class CStringConverter { public: explicit CStringConverter(std::string name) : m_name(name) {} operator const char* () const { return m_name.c_str(); } private: std::string m_name; }; int main() { CStringConverter converter(std::string("Me")); const char* name = "Me"; // Next line compiles fine, but they are not equal because the // pointers don't match. return (converter == name) ? 0 : 1; } Is there something special about the difference between a std::string and a char* in this context that makes the compiler not treat them the same?
The problem is due to the fact std::string is actually an instance of the class template std::basic_string. An operator== that is available in namespace std takes two std::basic_string templates: template<class charT, class traits, class Allocator> bool operator==(const basic_string& lhs, const basic_string& rhs); If this version of operator== was overloaded specifically on std::string, your code would be fine. But that's not the case, which would require the compiler to perform template argument deduction on the template parameters of std::basic_string so it could understand that the return of your conversion operator is a possible match. However, the compiler won't do that. I don't know which part of the standard states this precisely. But the general idea is that such conversions work only for non-template types. One thing I can suggest is for you to place StdStringConverter in a namespace and provide a version of operator== for std::string in that namespace. This way, when your compiler find an expression like that ADL (Argument Dependent Lookup) comes into play and everything works fine. #include <string> namespace n1 { class StdStringConverter { public: explicit StdStringConverter(std::string name) : m_name(name) {} operator std::string () { return m_name; } private: std::string m_name; }; bool operator==(std::string const& a, std::string const& b) { return a == b; //EDIT: See Paul's comment on std::operator== here. } } int main() { using namespace n1; StdStringConverter converter(std::string("Me")); std::string name = "Me"; return (converter == name) ? 0 : 1; }
1,443,982
1,443,997
When do compilers inline C++ code?
In C++, do methods only get inlined if they are explicitly declared inline (or defined in a header file), or are compilers allowed to inline methods as they see fit?
Yes, the compiler can inline code even if it's not explicitly declared as inline. Basically, as long as the semantics are not changed, the compiler can virtually do anything it wants to the generated code. The standard does not force anything special on the generated code.
1,444,025
1,444,066
C++ Overridden method not getting called
Shape.h namespace Graphics { class Shape { public: virtual void Render(Point point) {}; }; } Rect.h namespace Graphics { class Rect : public Shape { public: Rect(float x, float y); Rect(); void setSize(float x, float y); virtual void Render(Point point); private: float sizeX; float sizeY; }; } struct ShapePointPair { Shape shape; Point location; }; Used like this: std::vector<Graphics::ShapePointPair> theShapes = theSurface.getList(); for(int i = 0; i < theShapes.size(); i++) { theShapes[i].shape.Render(theShapes[i].location); } This code ends up calling Shape::Render and not Rect::Render I'm assuming this is because it is casting the Rect to a Shape, but I don't have any idea how to stop it doing this. I'm trying to let each shape control how it is rendered by overriding the Render method. Any ideas on how to achieve this?
Here's your problem: struct ShapePointPair { Shape shape; Point location; }; You are storing a Shape. You should be storing a Shape *, or a shared_ptr<Shape> or something. But not a Shape; C++ is not Java. When you assign a Rect to the Shape, only the Shape part is being copied (this is object slicing).
1,444,112
1,444,186
Why does this work? This is a small example, but it even worked on a much more complex project
#include <cstdio> class baseclass { }; class derclass : public baseclass { public: derclass(char* str) { mystr = str; } char* mystr; }; baseclass* basec; static void dostuff() { basec = (baseclass*)&derclass("wtf"); } int main() { dostuff(); __asm // Added this after the answer found, it makes it fail { push 1 push 1 push 1 push 1 push 1 push 1 push 1 push 1 push 1 push 1 } printf("%s", ((derclass*)basec)->mystr); }
Ugh. This is one of those "don't ever do this" examples. In dostuff, you create a temporary of type derclass, take its address, and manage to pass it outside of dostuff (by assigning it to basec). Once the line creating the temporary is finished, accessing it via that pointer yields undefined behavior. That it works (i.e. your program prints "wtf") is certainly platform dependent. Why does it work in this specific instance? To explain this requires delving deeper than just C++. You create a temporary of type derclass. Where is it stored? Probably it's stored as a very short lived temporary variable on the stack. You take it's address (an address on your stack), and store that. Later, when you go to access it, you still have a pointer to that portion of your stack. Since nobody has since come along and reused that portion of the stack, the object's remnants are still there. Since the object's destructor doesn't do anything to wipe out the contents (which is, after all, just a pointer to "wtf" stored somewhere in your static data), you can still read it. Try interjecting something which uses up a lot of stack between the dostuff and printf calls. Like, say, a call to a function which calculates factorial(10) recursively. I'll bet that the printf no longer works.
1,444,388
1,444,603
What's the point of _MERGE_PROXYSTUB?
I have generated an ATL COM object using VS2008 and the code contains references to a definition called _MERGE_PROXYSTUB (because I chose the 'Merge proxy/stub' option when I initially ran the wizard.) What is the point of a proxy/stub? If I don't select the the merge option then I get a separate MyControlPS.DLL instead - when would this ever be used? FWIW the control seems to register and work fine if I remove all the code surrounded by the _MERGE_PROXYSTUB defines. A debug build doesn't even define _MERGE_PROXYSTUB and it still works OK. So, can I do without a proxy/stub?
You need a proxy/stub if you want your COM object to be called from an application using a different threading model than your COM object. For example, we have a plug in that gets loaded by an application that uses a particular threading model (can't remember which), but our COM object is multithreaded apartment (MTA) - so the the proxy/stub is required to marshall the data between the objects when a function call is made, while still adhering to the rules of the threading model. If these rules are broken, then COM will either throw an exception or return a failure HRESULT such as RPC_E_WRONG_THREAD If you don't check the merge proxy/stub option, then visual studio produces a seperate project for the proxy/stubs which get build into a seperate dll. This makes things more difficult for deployment if they are required, but you can basically just ignore them if you are not affected by threading model issues. So you can do without proxy/stubs if the application calling the COM object is using the same threading model as your object Larry Osterman provides a readable introduction to threading models on his blog.
1,444,528
1,444,568
Why is this code so slow?
So I have this function used to calculate statistics (min/max/std/mean). Now the thing is this runs generally on a 10,000 by 15,000 matrix. The matrix is stored as a vector<vector<int> > inside the class. Now creating and populating said matrix goes very fast, but when it comes down to the statistics part it becomes so incredibly slow. E.g. to read all the pixel values of the geotiff one pixel at a time takes around 30 seconds. (which involves a lot of complex math to properly georeference the pixel values to a corresponding point), to calculate the statistics of the entire matrix it takes around 6 minutes. void CalculateStats() { //OHGOD double new_mean = 0; double new_standard_dev = 0; int new_min = 256; int new_max = 0; size_t cnt = 0; for(size_t row = 0; row < vals.size(); row++) { for(size_t col = 0; col < vals.at(row).size(); col++) { double mean_prev = new_mean; T value = get(row, col); new_mean += (value - new_mean) / (cnt + 1); new_standard_dev += (value - new_mean) * (value - mean_prev); // find new max/min's new_min = value < new_min ? value : new_min; new_max = value > new_max ? value : new_max; cnt++; } } stats_standard_dev = sqrt(new_standard_dev / (vals.size() * vals.at(0).size()) + 1); std::cout << stats_standard_dev << std::endl; } Am I doing something horrible here? EDIT To respond to the comments, T would be an int. EDIT 2 I fixed my std algorithm, and here is the final product: void CalculateStats(const std::vector<double>& ignore_values) { //OHGOD double new_mean = 0; double new_standard_dev = 0; int new_min = 256; int new_max = 0; size_t cnt = 0; int n = 0; double delta = 0.0; double mean2 = 0.0; std::vector<double>::const_iterator ignore_begin = ignore_values.begin(); std::vector<double>::const_iterator ignore_end = ignore_values.end(); for(std::vector<std::vector<T> >::const_iterator row = vals.begin(), row_end = vals.end(); row != row_end; ++row) { for(std::vector<T>::const_iterator col = row->begin(), col_end = row->end(); col != col_end; ++col) { // This method of calculation is based on Knuth's algorithm. T value = *col; if(std::find(ignore_begin, ignore_end, value) != ignore_end) continue; n++; delta = value - new_mean; new_mean = new_mean + (delta / n); mean2 = mean2 + (delta * (value - new_mean)); // Find new max/min's. new_min = value < new_min ? value : new_min; new_max = value > new_max ? value : new_max; } } stats_standard_dev = mean2 / (n - 1); stats_min = new_min; stats_max = new_max; stats_mean = new_mean; This still takes ~120-130 seconds to do this, but it's a huge improvement :)!
Have you tried to profile your code? You don't even need a fancy profiler. Just stick some debug timing statements in there. Anything I tell you would just be an educated guess (and probably wrong) You could be getting lots of cache misses due to the way you're accessing the contents of the vector. You might want to cache some of the results to size() but I don't know if that's the issue.
1,444,837
1,444,911
Automatic creation of constructor, based on parent class' constructor (C++)
Here is a code I would like to get to work: template <class A> class B : public A { public: // for a given constructor in A, create constructor with identical parameters, // call constructor of parent class and do some more stuff B(...) : A(...) { // do some more stuff } }; Is it possible to achieve behavior described by above example?
No this is currently not possible in C++. It's called "perfect forwarding", and is allowed in C++0x. You can simulate it by producing overloads of your constructor up to a fixed maximum (like, say, 8 parameters), both for const and non-const references. This is still not perfect (temporaries won't be forwarded as temporaries), but usually works in practice: template<typename T1> B(T1 &a1):A(a1) { // do some more stuff } template<typename T1> B(T1 const &a1):A(a1) { // do some more stuff } template<typename T1, typename T2> B(T1 &a1, T2 &a2):A(a1, a2) { // do some more stuff } template<typename T1, typename T2> B(T1 const &a1, T2 const &a2):A(a1, a2) { // do some more stuff } template<typename T1, typename T2> B(T1 const &a1, T2 &a2):A(a1, a2) { // do some more stuff } template<typename T1, typename T2> B(T1 &a1, T2 const &a2):A(a1, a2) { // do some more stuff } // ... The generation can be automated using Boost.Preprocessor or some script, but it's not exactly nice, since the amount of overloads grows fast. So in short - no write your constructors yourself until C++0x is available, which supports both perfect forwarding for any function, and special constructor forwarding ("using A::A;").
1,444,843
1,444,892
Can creating a C++ control and using it in C# gain performance?
In reality, I am trying to create a control showing price depths of a stock which needs to accept a large number of messages and summarizing them for display purposes. Will I get a better result if I create it in MFC and use that control in my .Net Winform application than writing the whole thing in .NET?
I would write the whole thing in .NET, profile if it's too slow, then if it is, port only the processing code to C++ and use P/Invoke to get the summarized results for a .NET control. Trying to interface an MFC control with .NET can take a long time and be prone to error, whereas if you write the display logic in .NET and use C++ for any very performance dependent code you'll have a much easier time.
1,444,961
1,445,024
Is there a good Python library that can parse C++?
Google didn't turn up anything that seemed relevant. I have a bunch of existing, working C++ code, and I'd like to use python to crawl through it and figure out relationships between classes, etc. EDIT: Just wanted to point out: I don't think I need or want to parse every bit of C++; I just need something smart enough to pick up on class, function and member variable declarations, and to skip over function definitions.
C++ is notoriously hard to parse. Most people who try to do this properly end up taking apart a compiler. In fact this is (in part) why LLVM started: Apple needed a way they could parse C++ for use in XCode that matched the way the compiler parsed it. That's why there are projects like GCC_XML which you could combine with a python xml library. Some non-compiler projects that seem to do a pretty good job at parsing C++ are: Eclipse CDT OpenGrok Doxygen
1,444,991
1,445,027
how to differentiate if client is using TCP or UDP from server side
I am writing simple client-server program. Client send some messages to server using UDP or TCP. Server must be able to support both UDP and TCP. If client, sends message using UDP, sequence of method calls in client is socket(),bind(),sendto(),recvfrom(),close() and that in server is socket(),bind(),sendto(),recvfrom(),close(). If it uses TCP, sequence of call in server is socket(),bind(),listen(),accept(),send(),recv(),close(). and that in client is socket(),bind(),connect(),send(),recv(),close() In my program, user/client is given choice in the start to select what he want to use UDP or TCP. So, my main problem is how can I know or differentiate in the server side, if the client is sending message using TCP or UDP. If it uses TCP, I must call listen(),accept(),send(),recv() and if it uses UDP, I don't call listen(),accept() but call sendto() and recvfrom(). So, how can I differentiate/know this in the beginning so that I can make appropriate function calls. Thanks.
Before the packet reaches you, you don't know whether it's UDP or TCP. So you want to bind to both UDP and TCP sockets if you expect requests both ways. Once you did, you just know which way it came by the socket you received the packet through.
1,445,084
1,445,178
Pattern for synching object lists among computers (in C++)?
I've got an app that has about 10 types of objects. There will be potentially a few thousand object instances of each type. These lists of objects need to stay synchronized between apps running on different machines. If an object is added, changed or deleted, that needs to propagate to the other machines. This will be a star topology -- there is a central master, and the rest are clients. I DO have the concept of a session, so can store data about each client. Is there a good design pattern to follow for this? Even better, is there a (template based?) library that would handle asking the container what has changed since client X came by and getting that delta to send out? Right now I'm thinking every object-type container has an update counter. When something is added/changed/removed, the update counter is incremented, and the changed object(s) are tagged with that value. Each client will save the value of the update counter when it gets an update. Later it will come back and ask for any changes since it's update counter value. Finally, deletes are kept as tombstone records (although I'm not exactly sure when to clear them out). One thing that makes this harder is clients can come and go without the central server necessarily knowing, although I guess there could be a timeout concept (if the server haven't heard from a client in 5 minutes, it assumes the client is gone) Is this a well-known pattern? Any additional suggestions?
How you implement synchronization very much depends on your needs. Do the changes need to be sent to the clients, or is it sufficient that the clients checks if an object is up to date whenever it uses the objects? How bout using the Proxy pattern? This pattern allows you to create a proxy-implementation of your objects that can check if they are up to date or not, do update if they are not, and then return the result. I would do this by having a lastChanged timestamp on the objects on the master and a lastUpdated timestamp on the client objects. If latency is an issue checking if an object is up-to-date on each call is probably not a good idea. Consider having a separate thread that queries the master for changed objects and marks them "dirty". This could dramatically reduce the network traffic as well. You could also look into the Observer pattern and Publish/Subscribe.
1,445,237
1,445,310
Why does int count jump from 1 to 4 on entering a loop? C++
My "counter" is jumping from 1 to 4 when I enter my loop. Any ideas? Code and output below: static bool harvestLog() { ifstream myFile("LOGS/ex090716.log"); if (myFile.fail()) {cout << "Error opening file";return 1;} else { cout << "File opened... \n"; string line; string field; int cs_uri_stemLocation = 0; int csReferrerLocation = 0; int count = 1; cout << "-" << count << "-"; while( getline(myFile, line) ) { if ( strstr(line.c_str(), "cs-uri-stem") && (strstr(line.c_str(), "cs(Referer)") || strstr(line.c_str(), "cs(Referrer)")) ) { cout << "-" << count << "-"; cout << "Found log format: \n"; istringstream foundField(line); while (!foundField.eof()) { cout << "-" << count << "-"; foundField >> field; if (field == "cs-uri-stem") {cs_uri_stemLocation = count;} if (field == "cs(Referer)" || field == "cs(Referrer)") {csReferrerLocation = count;} cout << "cs-uri-stem: " << cs_uri_stemLocation << ". "; cout << "cs(Referer): " << csReferrerLocation << ". "; cout << "COUNT: " << count << endl; count++; } cout << "Found field cs-uri-stem at position " << cs_uri_stemLocation << "." << endl; cout << "Found field cs(Referer) at position " << csReferrerLocation << "." << endl; count = 1; } else { count = 1; istringstream foundField(line); while (!foundField.eof()) { foundField >> field; //if (count == cs_uri_stemLocation) cout << field << endl; count++; } //cmatch results; //regex rx("(?:p|q)(?:=)([^ %]*)"); //regex_search(line.c_str(), results, rx); //string referringWords = results[1]; //cout << referringWords; } } myFile.close(); return 0; } } -1--4-Found log format: -4-cs-uri-stem: 0. cs(Referer): 0. COUNT: 4 -5-cs-uri-stem: 0. cs(Referer): 0. COUNT: 5 -6-cs-uri-stem: 0. cs(Referer): 0. COUNT: 6 -7-cs-uri-stem: 0. cs(Referer): 0. COUNT: 7 -8-cs-uri-stem: 0. cs(Referer): 0. COUNT: 8 -9-cs-uri-stem: 0. cs(Referer): 0. COUNT: 9 -10-cs-uri-stem: 10. cs(Referer): 0. COUNT: 10 -11-cs-uri-stem: 10. cs(Referer): 0. COUNT: 11 -12-cs-uri-stem: 10. cs(Referer): 0. COUNT: 12 -13-cs-uri-stem: 10. cs(Referer): 0. COUNT: 13 -14-cs-uri-stem: 10. cs(Referer): 0. COUNT: 14 -15-cs-uri-stem: 10. cs(Referer): 0. COUNT: 15 -16-cs-uri-stem: 10. cs(Referer): 16. COUNT: 16 -17-cs-uri-stem: 10. cs(Referer): 16. COUNT: 17 -18-cs-uri-stem: 10. cs(Referer): 16. COUNT: 18 -19-cs-uri-stem: 10. cs(Referer): 16. COUNT: 19 -20-cs-uri-stem: 10. cs(Referer): 16. COUNT: 20 Found field cs-uri-stem at position 10. Found field cs(Referer) at position 16.
I would bet that it's going throught the while (!foundField.eof()) { foundField >> field; //if (count == cs_uri_stemLocation) cout << field << endl; count++; } and you never reset it after this branch
1,445,274
1,445,327
Ternary operator evaluation order
class Foo { public: explicit Foo(double item) : x(item) {} operator double() {return x*2.0;} private: double x; } double TernaryTest(Foo& item) { return some_condition ? item : 0; } Foo abc(3.05); double test = TernaryTest(abc); In the above example, why is test equal to 6 (instead of 6.1) if some_condition is true? Changing the code like below returns value of 6.1 double TernaryTest(Foo& item) { return some_condition ? item : 0.0; // note the change from 0 to 0.0 } It seems that (in the original example) the return value from Foo::operator double is cast to an int and then back to a double. Why?
The conditional operator checks conversions in both directions. In this case, since your constructor is explicit (so the ?: is not ambiguous), the conversion from Foo to int is used, using your conversion function that converts to double: That works, because after applying the conversion function, a standard conversion that converts the double to int (truncation) follows. The result of ?: in your case is int, and has the value 6. In the second case, since the operand has type double, no such trailing conversion to int takes place, and thus the result type of ?: has type double with the expected value. To understand the "unnecessary" conversions, you have to understand that expressions like your ?: are evaluated "context-free": When determining the value and type of it, the compiler doesn't consider that it's the operand of a return for a function returning a double. Edit: What happens if your constructor is implicit? The ?: expression will be ambiguous, because you can convert an int to an rvalue of type Foo (using the constructor), and a Foo to an rvalue of type int (using the conversion function). The Standard says Using this process, it is determined whether the second operand can be converted to match the third operand, and whether the third operand can be converted to match the second operand. If both can be converted, or one can be converted but the conversion is ambiguous, the program is ill-formed. Paragraphs explaining how your Foo is converted to int: 5.16/3 about condition ? E1 : E2: Otherwise, if the second and third operand have different types, and either has (possibly cv-qualified) class type, an attempt is made to convert each of those operands to the type of the other. [...] E1 can be converted to match E2 if E1 can be implicitly converted to the type that expression E2 would have if E2 were converted to an rvalue (or the type it has, if E2 is an rvalue). 4.3 about "implicitly converted": An expression e can be implicitly converted to a type T if and only if the declaration T t = e; is well-formed, for some invented temporary variable t. 8.5/14 about copy initialization ( T t = e; ) If the source type is a (possibly cv-qualified) class type, conversion functions are considered. The applicable conversion functions are enumerated (13.3.1.5), and the best one is chosen through overload resolution (13.3). The user-defined conversion so selected is called to convert the initializer expression into the object being initialized. If the conversion cannot be done or is ambiguous, the initialization is ill-formed. 13.3.1.5 about the conversion function candidates The conversion functions of S and its base classes are considered. Those that are not hidden within S and yield type T or a type that can be converted to type T via a standard conversion sequence (13.3.3.1.1) are candidate functions.
1,445,308
1,445,622
Saving 'global' data as a standard user?
in my application I need to store settings that are 'global' (i.e. not user specific) in a known and predictable location. I want the application to be able to be run from anywhere (as a standard user, NOT administrator), including multiple copies from different locations and be able to read and write the saved config files. The data needs to have read and write access granted for ALL standard users, not just one. With that in mind, the four options noted here are inappropriate: http://msdn.microsoft.com/en-us/library/bb206295(VS.85).aspx#ID0E1BA So what are my alternatives? My application is written in C++ and for Windows only. I need to support Windows XP and above. Thanks. EDIT: To clarify, ignore race conditions caused by multiple instances. This question is solely to do with WHERE TO STORE THE DATA. I can't see anywhere suitable that is: Predictable (e.g. %APPDATA%\Foo is a 'predictable' path, but unfortunately user-specific) Global (e.g. %PROGRAMDATA%\Foo is a global path but unfortunately only the creating user has write-access) Accessible (a standard user needs to be able to create new files in the given directory, this applies to all users on the system)
If you decide that CSIDL_COMMON_APPDATA isn't appropriate (maybe CSIDL_COMMON_APPDATA is a good default, but you want the administrator to be able to change the location) you can have the installer write something to an HKLM\SOFTWARE\<your app subkey> that indicates the desired path for the common directory that will hold the data. An alternative to placing the pointer in the HKLM registry is to have a config file that resides in the program directory which has a pointer to the shared directory. By definition the program directory must writable by the installer, it's writable by administrators (who might be responsible for modifying the configuration), and it's readable by users. So a standard user can read a well-known location (either an HKLM sub-key or a config file in the program directory) to get a pointer to a directory that's writable by all standard users. Whatever sets up the common directory (the install program or the configuration module) will need to make sure the common directory's ACL is set appropriately for standard user writes.
1,445,608
1,445,985
Reading license file from RLM with C# (C++ to C# translation)
I'm using the Reprise RLM license manager researching internet activation. I can't figure out how to get the license file from the webserver into a text file with C# (I'm also very new to C#). RLM comes with an example in C++ but I can't translate it. My code (for the demo) looks like so: int stat = RLM.rlm_act_request(handle, "http://www.reprisesoftware.com", "rlmactdemo", activationKey, "", "", 1, "", new byte[RLM.RLM_MAX_LINE+1]); if (stat == 0||stat == 1){ //Successful connection //Read license file and write to local machine } rlm_act_request establishes and verifies the connection. Once it is established, how do I access the file and write it a local file? The C++ code for whatever goes in that if statement is as follows: char name[100]; char license[100]; int try; FILE *f, *fopen(); stat = 1; for (try=0; try<100; try++) { sprintf(name, "a%d.lic", try); f = fopen(name, "r"); if (f == (FILE *) NULL) { f = fopen(name, "w"); if (f) { fprintf(f, "%s\n", license); fclose(f); break; } else { printf("Error writing license file \"%s\"\n", name); stat = -1; break; } } } What's the C# equivalent?
Well, that was surprisingly easy. It turns out that the 'new byte[]' that gets passes to rml_act_request() holds the contents of the license file. All I had to do was make it a local variable, convert it to string and write it to file using TextWriter.WriteLine(); I wish this had been documented somewhere...
1,445,679
1,446,086
Easiest way to locate a static variable in code?
I have a bug on my plate to locate and rewrite a static variable in one of our libraries that is taking up launch time in our application. I am not familiar with the library code base and am asking for good heuristics/techniques/grep commands/etc. that would ease my task in identifying the location of said static variable? (P.S. I'm already searching the code base for static; needless to say it's a verbose result.) Update: The bug report simply states "library XYZ takes N ms at static initialization"; I do not have any more information about the static variable than that. I don't have the profiling logs but I'll see if I can get them from the bug reporter.
You could try to do a nm -aC <libname> first and grep by the static and global vars (IIRC they should be prefixed with a B/b or a T/t), then look for those vars in the source code. It may narrow down the haystack a little.
1,445,736
1,445,749
How do I iterate through a std::list<MyClass *> and get to the methods in that class from the iterator?
If I have the list, typedef std::list<MyClass *> listMyClass; How do I iterate through them and get to the methods in that class? This is what I’ve tried, but that is not it: (MyClass::PrintMeOut() is a public method) for( listMyClass::iterator listMyClassIter = listMyClass.begin(); listMyClassIter != listMyClass.end(); listMyClassIter ++) { listMyClassIter->PrintMeOut(); }
Use this method: (*listMyClassIter)->PrintMeOut();
1,446,461
4,523,360
Getting started with OpenGL ES 2.0 on Windows
This is a very specific questions about the steps necessary to Build a simple OpenGL ES 2.0 program on the Windows platform. The environment is Visual Studio with unmanaged C++. I go to the Khronos.org site and, frankly, find it a bit opaque because it reads like something written by a standards body. I don't want to download a "reference" or a "specification", etc. All I'm looking for are the links and steps to get me from A to B. In other words, "Download these files or run this setup at this URL. Create a new Visual studio project with references to these libraries. Include this header file." Again, I'm interested in ES 2.0.
After alot of digging around for the same thing. I found an emulator for openGL es 2 from PowerVR: http://www.imgtec.com/powervr/insider/sdkdownloads/index.asp The AMD one linked above is no longer available or supported.
1,446,987
1,448,786
Lightweight Delaunay trianguation library (for c++)
I'd like to play around with some (2D) Delaunay triangulations, and am looking for a reasonably small library to work with. I'm aware of CGAL, but I was wondering if there was something fairly simple and straightforward out there. Things I would like to do: create a triangulation of an arbitrary set of points find triangle an arbitrary point is in, and fetch the vertices create an image of the triangulation (optional) Suggestions?
You should probably detail your goals a bit, so that more relevant answers can be provided, but let me first mention Triangle, a 2D Delaunay generation tool, which is written in C, and can be used both as a standalone program, or called from your own code. Then, about CGAL, here is a typical small example, in case you still consider it: #include <vector> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Delaunay_triangulation_2.h> typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef CGAL::Delaunay_triangulation_2<K> Delaunay; typedef K::Point_2 Point; void load_points(std::vector< Point >& points) { points.push_back(Point(1., 1.)); points.push_back(Point(2., 1.)); points.push_back(Point(2., 2.)); points.push_back(Point(1., 2.)); } int main() { std::vector< Point > points; load_points(points); Delaunay dt; dt.insert(points.begin(), points.end()); std::cout << dt.number_of_vertices() << std::endl; return 0; }
1,446,999
1,447,023
C++ std::system 'system' not a Member of std
I receive an error compiling a C++ program in which of the lines makes a call from "std::system(SomeString)". This program compiled 3 years ago, but when compiling it today, I receive an error that states ‘system’ is not a member of ‘std’. Is there something that I must import to use std::system, has it been abandoned, or has it moved to another header file.
std::system is (and always has been) in <cstdlib>. It is not defined by the C++ standard whether standard headers include each other, and if so which ones. So it's possible that 3 years ago, on a different compiler or a different version of the same compiler, your code worked by accident, because one of the headers you include just so happened to include <cstdlib>. On the compiler/version you're using now, it doesn't.
1,447,053
1,447,088
Why do I get different outputs when encrypting using DPAPI?
I'm using DPAPI in C++ to encrypt some data that I need to store in a file. The thing is that I need to read that file from C#, so I need to be able to: C++ encrypt, C++ decrypt (is working good) C# encrypt, C# decrypt (is working good) C++ encrypt, C# decrypt and vice-versa (not working) In C# I'm using DllImport to pInvoke the methods CryptProtectData and CryptUnprotectData, and I implement them as explained here. I know that in C# I can use the methods contained in the ProtectedData class but I'm doing it in this way (using DllImport ) to make sure that both codes (c++ and c#) look and work pretty much the same. Now the weird thing is that even if both codes looks the same I get different outputs, for example for this text: "plain text" in C++ I get: 01 00 00 00 D0 8C 9D DF 01 15 D1 11 8C 7A 00 C0 4F C2 97 EB 01 00 00 00 2E 6F 88 86 E6 16 9B 4F 9B BF 35 DA 9F C6 EC 12 00 00 00 00 02 00 00 00 00 00 03 66 00 00 A8 00 00 00 10 00 00 00 93 06 68 39 DB 58 FE E9 C4 1F B0 3D 7B 0A B7 48 00 00 00 00 04 80 00 00 A0 00 00 00 10 00 00 00 36 4E 84 05 0D 4A 34 15 97 DC 5B 1F 6C A4 19 D9 10 00 00 00 F5 33 9F 55 49 94 26 54 2B C8 CB 70 7B FE EC 96 14 00 00 00 C5 23 DA BA C8 23 6C 0B B3 88 69 06 00 95 29 AE 76 A7 63 E4 and in C# I get: 01 00 00 00 D0 8C 9D DF 01 15 D1 11 8C 7A 00 C0 4F C2 97 EB 01 00 00 00 2E 6F 88 86 E6 16 9B 4F 9B BF 35 DA 9F C6 EC 12 00 00 00 00 02 00 00 00 00 00 03 66 00 00 A8 00 00 00 10 00 00 00 34 C4 40 CD 91 EC 94 66 E5 E9 23 F7 9E 04 9C 83 00 00 00 00 04 80 00 00 A0 00 00 00 10 00 00 00 12 54 1E 26 72 26 0A D1 11 1D 4D EF 13 1D B2 6F 10 00 00 00 81 9D 46 37 D1 68 5D 17 B8 23 78 48 18 ED 06 ED 14 00 00 00 E4 45 07 1C 08 55 99 80 A4 59 D9 33 BC 0B 71 35 39 05 C4 BB As you can see the first characters are the same but the rest are not, so if anyone has an idea of why this may be happening, I will appreciate the help. Thanks. Code in C++: value = "plain text"; DATA_BLOB DataIn; DATA_BLOB DataOut; BYTE *pbDataInput =(BYTE *)(char*)value.c_str(); DWORD cbDataInput = strlen((char *)pbDataInput)+1; DataIn.pbData = pbDataInput; DataIn.cbData = cbDataInput; CryptProtectData(&DataIn, NULL, NULL, NULL, NULL, 0, &DataOut)) Code in C#: (you can see how my C# code looks here, since is identical to the one in this Microsoft example )
It would help if you could post your C++ and your C# code. Perhaps there are some subtle parameter differences or something like this. For example, you should make sure that the pOptionalEntropy parameter is the same (or set it to NULL to test if this is the error source). Also, make sure to try to encrypt and decrypt on the same PC: [...]decryption usually can only be done on the computer where the data was encrypted (Source: MSDN) EDIT: Some comments on the code you posted and the C# version from MSDN (parts of it following): public byte[] Encrypt(byte[] plainText, byte[] optionalEntropy) { [...] int bytesSize = plainText.Length; plainTextBlob.pbData = Marshal.AllocHGlobal(bytesSize); plainTextBlob.cbData = bytesSize; Marshal.Copy(plainText, 0, plainTextBlob.pbData, bytesSize); [...] dwFlags = CRYPTPROTECT_LOCAL_MACHINE|CRYPTPROTECT_UI_FORBIDDEN; [...] if(null == optionalEntropy) {//Allocate something optionalEntropy = new byte[0]; // Is copied to entropyBlob later } [...] retVal = CryptProtectData(ref plainTextBlob, "", ref entropyBlob, IntPtr.Zero, ref prompt, dwFlags, ref cipherTextBlob); [...] } And here's your C++ code again to have both in view: [...] BYTE *pbDataInput =(BYTE *)(char*)value.c_str(); DWORD cbDataInput = strlen((char *)pbDataInput)+1; [...] CryptProtectData(&DataIn, NULL, NULL, NULL, NULL, 0, &DataOut)) The parameters don't match and I think that's the source of the differences. The first thing is the flags. The C# code uses dwFlags != 0, your C++ code uses dwFlags = 0, so this is clearly a difference. I'm not sure about the entropy. If you didn't pass optionalEntropy = null it is a difference, but if it is null, there's a "new byte[0]" assignment and I'm not sure about what this will create, but I think you should at least try to pass IntPtr.Zero instead of entropyBlob to CryptProtectData to match with the C++ code. Last, but not least, your C++ code includes the trailing NUL that delimits the C string, I don't know how the encryption used here works but there are encryptions that will give you very different outputs if one byte is different (or you have one more byte like in this case), so you should either include a terminating NUL in the C# code or remove it in the C++ code.
1,447,094
1,447,110
Where does Visual Studio search for txt files when conducting file management operations?
I know this is a noob question, but I've worked with Python before and when you wanted to simply access a .txt file for example, all you had to do was make sure the txt file was in the same directory. I have the following C++ code below but it's not finding the Numbers.txt file that I have saved on my desktop. All I have in the file is one line of numbers of type double. All I want to do is to find the average of all of the numbers in the file. The program runs fine, but it doesn't print the output correctly. After checking to see what is printing into output by just printing output[0], I've discovered that the file is not copying it's contents into the array. Could someone clear this little problem up for me or at least point me in the right direction to a good tutorial? int main() { cout << "Getting File Information..." << endl; ifstream file; char output[100]; //int x; file.open("Numbers.txt", ios::in); // open file cout << "Opened File Successfully ****************" << endl; file >> output; // empty file contents into output cout << output; // print out contents of file cout << "Should have printed out results by now" << endl; //file >> x; file.close(); return 0; }
Visual Studio sets the working directory to YourProjectDirectory\Debug\Bin when running in debug mode. If your text file is in YourProjectDirectory, you need to account for that difference. The easiest way to do that is to include your text files in the project and set their build action (in the Properties window) to Content.
1,447,141
1,447,360
How to use a template parameter in another template parameter declared before
a template parameter can be used in another template parameter that follows it this way : template<typename T, T N> struct s { }; But is it possible to reference "T" if it is declared after "N" ? This does not work : template<T N, typename T> struct s { }; Can we help the compiler by pre-declaring "T" or doing anything else ? Thanks by advance. EDIT : as the first two replies were asking "why are you willing to do that ?" I'll explain the goal : I would like to make the compiler infer the type "T" in order to make the use of templated classes easier. For example : template<typename T, T A, T B> struct sum { static T const value = A + B; }; This template can be used this way : sum<int, 1, 2>::value But it would be better if it could be used this way : sum<1, 2>::value Technically it's should be possible because the compiler knows the types of "1" and "2" : "int", and in fact it uses these informations to find the best overload for a function. So by declaring the template this way : template<T A, T B, typename T> struct sum { static T const value = A + B; }; the compiler could use its capability to infer the last parameter from the informations provided by the first and the second one, and then find the best template to instantiate.
Like others say - No this isn't possible, the compiler can't infer the type of T from the non-type template arguments (in the case of functions, it infers types from the function arguments): 14.8.2.4/12: A template type argument cannot be deduced from the type of a non-type template-argument. In any case, no deduction will be made for the arguments of a class template anyway. An example for a function template might be template<int> struct having_int { }; template<typename T, T i> void f(having_int<i>); int main() { having_int<0> h; f(h); } In this case, T won't be deduced as int - you have to explicitly specify it.
1,447,143
1,447,161
Integration testing C++ code from NUnit in managed code
I have a library written in c++ that I want to end-to-end test from C# via interop. Basically this library takes in some parameters and spits out a file at the other end. I want to pass requests to a com interop and then assert that all the data was written correctly to the file. Is it possible to do this? Is there an easier way? Using pinvoke or something? Thanks
I'd use C++/CLI for gluing together .net tests and native C++ code. It works well enough in practise : I had a similar issue some months ago -- wanting to verify that a C++ protocol library I'd written would be interoperable with an existing Java implementation. For that I used a thin C++/CLI shim to the C++ code, built the Java as J#, and wrote tests in C#.
1,447,199
1,447,312
C++ closures and templates
We all know you can simulate closures in C++98 by defining local structs/classes inside a function. But is there some reason that locally defined structs can't be used to instantiate templates outside of the local scope? For example, it would be really useful to be able to do things like this: void work(std::vector<Foo>& foo_array) { struct compareFoo { bool operator()(const Foo& f1, const Foo& f2) const { return f1.bar < f2.bar; } }; std::sort(foo_array.begin(), foo_array.end(), compareFoo()); } This would be especially useful if you know you're not going to need to use compareFoo anywhere else in your code. But, alas, this doesn't compile. Is there some reason that the compiler can't instantiate the std::sort template function using a locally defined struct?
There's no better reason than "it's not allowed by the standard". I believe C++0x is going to lift this restriction, and allow you to use local classes as template parameters freely. But for now, it's not allowed.
1,447,268
1,447,275
Does an arbitrary instruction pointer reside in a specific function?
I have a very difficult problem I'm trying to solve: Let's say I have an arbitrary instruction pointer. I need to find out if that instruction pointer resides in a specific function (let's call it "Foo"). One approach to this would be to try to find the start and ending bounds of the function and see if the IP resides in it. The starting bound is easy to find: void *start = &Foo; The problem is, I don't know how to get the ending address of the function (or how "long" the function is, in bytes of assembly). Does anyone have any ideas how you would get the "length" of a function, or a completely different way of doing this? Let's assume that there is no SEH or C++ exception handling in the function. Also note that I am on a win32 platform, and have full access to the win32 api.
Look at the *.map file which can optionally be generated by the linker when it links the program, or at the program's debug (*.pdb) file.
1,447,423
1,451,586
How to include directories in cmake generated visual studio projects?
I have (roughly) the following CMakeLists.txt project(Test) set(SOURCE 123.cpp 456.cpp ) find_package(Boost COMPONENTS unit_test_framework REQUIRED) include_directories(${Boost_INCLUDE_DIRS}) link_directories(${Boost_LIBRARY_DIRS}) message("${Boost_INCLUDE_DIRS}") add_executable(Tests ${SOURCE}) The message generated by message("${Boost_INCLUDE_DIRS}") is C:\boost_1_40_0 When I generate the visual studio 2008 project files, all is fine... except that the in the project's properties, there is nothing in the "Additional Include Directories" in the C/C++ section. When I build, I get fatal error C1083: Cannot open include file: 'boost/test/unit_test.hpp': No such file or directory However, the file is right there, under C:\boost_1_40_0. Is there something more to do? For now I'm putting boost in the global c++ directories, but I was wondering if there was a reason for this ? Thank you!
ok... the include_directories and link_directories need to be after the add_executable...
1,447,552
1,447,555
Performance penalty for using C++ vector instead of C array
Is there a performance penalty for working with a vector from the standard library in C++ instead of arrays in C?
No, there's not (provided you compile with optimization so inlining can happen), provided you mean dynamically sized C "arrays" obtained with malloc. Fixed-sized arrays in C will have the slight advantage that their address is fixed after linking (if global), or that they live directly on the stack rather than indirectly through a pointer to somewhere on the heap. I do believe there is still no performance difference; constant base addresses aren't faster than variable ones; both get loaded into a CPU register.
1,447,554
1,447,560
Class constructor with non-argument template type
For a normal C++ function, it's possible to have template parameters not appearing in the argument list: template<typename T> T default_construct() { return T(); } and call this with some_type x = default_construct<some_type>(); Even though the type I'm using is not in the argument list, I can still pass it to the function. Now, I want to do this in a class constructor: struct Base; template<typename T> Base* allocate() { return new T; //Assume T derives from Base... } struct factory { template<typename T> factory() : func(allocate<T>) {} std::tr1::function<Base*()> func; }; but I can't find a way to supply the parameter to the constructor when I want to construct an instance of factory. Is there a way to do this without turning the class into a templated class or sending some unused T object to the constructor?
No, there is no way to do that. The note at 14.8.1/5 in the Standard explains why [Note: because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates. ] Of course, it doesn't need to be a T object you send. It can be any object that has T encoded in its type template<typename T> struct type2type { }; struct factory { template<typename T> factory(type2type<T>) : func(allocate<T>) {} std::tr1::function<Base*()> func; }; factory f((type2type<Foo>()));
1,447,701
1,447,711
C++ Template abuse question - Augmenting floats with additional type information
I had an idea motivated by some of the documentation I read in the tutorial of the boost MTL library. The basic premise is that I would like to use templates to give me compile time type checking errors for things that are otherwise the same. Namely, lets say I have two units of measurement, Radians and Degrees. The most obvious way to go about getting type safety is to define 2 classes: struct Radian { float rad; } struct Degree { float deg; } This is all well and good, except I can do something like func() { Radian r; Degree d; r.rad = d.deg; } It would be nice if I could flag an assignment like that as a compile time type error. This lead me to consider the following: struct Degree {}; struct Radian {}; template <class Data, class Unit> struct Quantity { Data val; Quantity<Data,Unit>() : val() {} explicit Quantity<Data,Unit>(Data v) : val(v) {} }; typedef Quantity<float,Radian> Rad; typedef Quantity<float,Degree> Deg; Now, the equivalent code of func() using the types Rad and Deg would flag that assignment as a compile time error (and with explicit set, even doing something as simple as Rad r = 2.0 is considered a compile time error). What I really want is a float that has this additional units property that can be used to catch logic errors at compile time (ie, using degrees in a function that expects radians), but for all intents and purposes, these things are floats. As a general question, what are your thoughts on this approach? I am slightly concerned that this is the wrong way to achieve my goal, but it has a strange appeal. Also, is there a "trait" or something like boost concept check that I can use to determine that Data is "float like". Finally, is there any way I can inherit default implementations of operations such as "<<" so that I don't have to implement all of them manually in the Quantity class?
I believe you are looking for something like Boost.Units. I think that's a place to get started.
1,447,783
1,447,804
Using a struct member in STL algorithms
#include <iostream> #include <vector> #include <iterator> using namespace std; struct Point { int x; int y; Point(int x, int y) : x(x), y(y) {} }; int main() { vector<Point> points; points.push_back(Point(1, 2)); points.push_back(Point(4, 6)); vector<int> xs; for(vector<Point>::iterator it = points.begin(); it != points.end(); ++it) { xs.push_back(it->x); } copy(xs.begin(), xs.end(), ostream_iterator<int>(cout, " ")); cout << endl; return 0; } I'm wondering how I would achieve the same result as the for loop above using an STL algorithm? I've tried a few things using for_each, but wasn't able to get it to work.
You wouldn't use std::for_each, but rather std::transform (you're transforming a point into a single number.) For example: #include <algorithm> // transform resides here #include <iostream> #include <iterator> #include <vector> struct Point { int x; int y; Point(int x, int y) : x(x), y(y) { } }; int point_to_int(const Point& p) { return p.x; } int main() { std::vector<Point> points; points.push_back(Point(1, 2)); points.push_back(Point(4, 6)); std::vector<int> xs; std::transform(points.begin(), points.end(), std::back_inserter(xs), point_to_int); std::copy(xs.begin(), xs.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; return 0; } Because you know the size of the container you'll be transforming, you might get a slight performance improvement from the following. I also find it more readable: std::vector<int> xs; xs.reserve(points.size()); std::transform(points.begin(), points.end(), std::back_inserter(xs), point_to_int); And with boost::lambda along with boost::bind: #include <algorithm> #include <iostream> #include <iterator> #include <vector> #include <boost/bind.hpp> #include <boost/lambda/lambda.hpp> struct Point { int x; int y; Point(int x, int y) : x(x), y(y) { } }; int main() { using namespace boost; std::vector<Point> points; points.push_back(Point(1, 2)); points.push_back(Point(4, 6)); std::vector<int> xs; xs.reserve(points.size()); std::transform(points.begin(), points.end(), std::back_inserter(xs), bind(&Point::x, lambda::_1)); std::copy(xs.begin(), xs.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; return 0; } Removes the need to specify a function elsewhere. This keeps the code close to the calling site, and generally improves readability. In C++0x, it will simply be: std::transform(points.begin(), points.end(), std::back_inserter(xs), [](const Point& p){ return p.x; } ); (To the best of my knowledge, anyway)
1,447,939
1,447,978
Parameter choice for copy constructor
I was recently asked in an interview about the parameter for a copy constructor. [Edited] As a designer of C++ language implementing copy constructor feature, why would you choose constant reference parameter over a const pointer to a const object. I had a few ideas like since a pointer can be assigned to NULL which probably doesn't make sense (semantically) in a copy constructor and the fact that pointer variable is an independent object (which would probably not be good in terms of efficiency) whereas a reference is just an alias to the actual object (therefore a better way to pass the object). Any other ideas?
Because Stroustrup wanted classes to be like primitive-types. When you initialize an int variable: int x = 5; int y = x; // Why would you write int y = &x; ? Passing constant pointer to constant object, is inconsistent with what C++ brought to C. classes in C++ are just User-Defined Types, if they don't work like primitive types then what are they? Another example where programming in C++ would be miserable without references is operators overloading. Imagine you have to write: myclass myobj1, myobj2, myobj3; &myobj3 = &myobj1 + &myobj2;
1,447,989
2,275,189
"Unable to resolve..." in NetBeans 6.7.1, Linux, C++
I am working with a small group on a C++ project in NetBeans. For some reason, NetBeans is reporting things like "string", "endl", "cout" as "Unable to Resolve" even though the correct libraries have been included. The project compiles and runs as expected, so at the end of the day, it is no big deal, it is just that having everything marked as an error makes it quite annoying. I haven't been able to find anything on this bug. Just one vague reference in a blog. Has anyone else experienced it? Obviously it isn't wide-spread, so there must be a setting/configuration that causes it. Does anyone know who to prevent this from happening? EDIT: No, these "errors" are solely in the IDE. The code compiles fine and runs. The developer has used "using namespace std;" so there should be no issues. It appears that the NetBeans IDE is buggy. Sample code: #include <stdlib.h> #include <string> #include <iostream> using namespace std; int main(int argc, char** argv) { string test; test = "Why?"; cout << test << endl; return (EXIT_SUCCESS); } This code compiles and prints out "Why?" but has "string", "cout" and "endl" marked as errors in the IDE. Explicitly using std:: makes no difference Clean up Edit: For anyone interested, a few days later I had 6 updates available for NetBeans. After installing this updates, the problem was rectified, despite the code not changing. So, apparently it was a NetBeans bug.
For anyone interested, a few days later I had 6 updates available for NetBeans. After installing this updates, the problem was rectified, despite the code not changing. So, apparently it was a NetBeans bug.
1,448,119
1,448,169
How to write a function that takes an iterator or collection in a generic way?
I've been a Java programmer almost exclusively for the past 8 years or so, and recently I've been playing with C++ again. Here's an issue that I've come up against with regards to iterators in C++ STL and Java. In Java, you can write a method that takes an iterator like this: void someMethod(Iterator<String> data) { // ... } You pass in an Iterator and the method does not need to know what the underlying collection of that iterator is, which is good. In C++, there is no common base class for iterators (as far as I know). I'd have to write a function like this: void some_function(std::vector<std::string>::const_iterator data) { // ... } In other words, some_function knows that the iterator is an iterator over a vector. That's not good, because I want the function to work regardless of what the underlying collection of the iterator is. How can I do this in C++? If it isn't really possible, then what is the best way to create a function in C++ that takes a collection as a parameter, but that doesn't need to know what the exact kind of collection is? Addendum Thanks for the answers. In addition to the answers I found some good information on this in paragraph 7.5 (Iterator Traits) of the book The C++ Standard Library: A Tutorial and Reference (by Nicolai M. Josuttis). Paragraph 7.5.1 explains how to write specialized versions of functions for different iterator categories.
Its best to indicate through a naming convention the kind of iterator and subsequently the kind of properties the iterator is required to posses. Below are some common naming conventions for iterators: template<typename Iterator> void foo_iterator(Iterator begin, Iterator end) { typedef typename std::iterator_traits<Iterator>::value_type T; .... } template<typename RandomIterator> void foo_random_iterator(RandomIterator begin, RandomIterator end) { typedef typename std::iterator_traits<RandomIterator>::value_type T; .... } template<typename ForwardIterator> void foo_forward_iterator(ForwardIterator begin, ForwardIterator end) { typedef typename std::iterator_traits<ForwardIterator>::value_type T; .... } template<typename ReverseIterator> void foo_forward_iterator(ReverseIterator begin, ReverseIterator end) { typedef typename std::iterator_traits<ReverseIterator>::value_type T; .... } template<typename InputIterator> void foo_input_iterator(InputIterator begin, InputIterator end) { typedef typename std::iterator_traits<InputIterator>::value_type T; .... } template<typename OutputIterator> void foo_output_iterator(OutputIterator out) { // We don't have a type T, as we can't "always" // know the type, as this type of iterator is a sink. .... } Below is a generic definition for sequence type containers, which include vector and deque. template <typename T, class Allocator, template <class,class> class Sequence> inline void foo_sequence(Sequence<T,Allocator>& sequence) { .... }
1,448,396
1,448,478
How to use enums as flags in C++?
Treating enums as flags works nicely in C# via the [Flags] attribute, but what's the best way to do this in C++? For example, I'd like to write: enum AnimalFlags { HasClaws = 1, CanFly =2, EatsFish = 4, Endangered = 8 }; seahawk.flags = CanFly | EatsFish | Endangered; However, I get compiler errors regarding int/enum conversions. Is there a nicer way to express this than just blunt casting? Preferably, I don't want to rely on constructs from 3rd party libraries such as boost or Qt. EDIT: As indicated in the answers, I can avoid the compiler error by declaring seahawk.flags as int. However, I'd like to have some mechanism to enforce type safety, so someone can't write seahawk.flags = HasMaximizeButton.
The "correct" way is to define bit operators for the enum, as: enum AnimalFlags { HasClaws = 1, CanFly = 2, EatsFish = 4, Endangered = 8 }; inline AnimalFlags operator|(AnimalFlags a, AnimalFlags b) { return static_cast<AnimalFlags>(static_cast<int>(a) | static_cast<int>(b)); } Etc. rest of the bit operators. Modify as needed if the enum range exceeds int range.
1,448,426
1,486,485
How to avoid entering library's source files while debugging in Qt Creator with gdb?
How can I configure Qt Creator and/or gdb so that while debugging my program using Qt libraries the debugger would avoid stepping into Qt's source files?
You need to turn off auto-solib-add. From a normal gdb prompt you would type: (gdb) set auto-solib-add off In Qt Creator, under Options->Debugger->Gdb you can specify a Gdb startup script. Create a file with the "set auto-solib-add off" command in it and then set your Gdb startup script to that file.
1,448,467
1,448,480
initializing a C++ std::istringstream from an in memory buffer?
I have a memory block (opaque), that I want to store in a Blob in mySQL through their C++ adapter. The adapter expects a istream: virtual void setBlob(unsigned int parameterIndex, std::istream * blob) = 0; So my question is: how can I create a std::istream from this memory block (typed as char*). It's not a string as it is not null-terminated (but I know its length of course). I could not find a way to do it without copying my memory block for example in a std::string. I think this is a bit wasteful. Something like this doesn't work: std::streambuf istringbuf(blockPtr, blockLength); std::istringstream tmp_blob(&istringbuf); because std::streambuf doesnt have such a constructor. I saw the following suggestion. std:: istringstream tmp_blob; tmp_blob.rdbuf()->pubsetbuf(blockPtr, blockLength); Is that the correct way?
Look at std::istrstream it has a constructor istrstream( char* pch, int nLength ); This class is sort of depreciated or at least you are normally told to use other classes. The issue with strstream is that it is more complex to manage the memory of the char* buffer so in general you would prefer stringstream as it does the memory management for you. However in this case you are already managing the memory of the char* so the normal benefit is in this case a cost. In fact in this case strstream does exactly what you want with minimal overhead in code or speed. This is similar to the discussion of ostrsteram by Herb Sutter
1,448,596
1,448,673
operator overloading in C++
Besides 'new', 'delete', '<<' & '>>' operators, what other operators can be overloaded in C++ outside of a class context?
The following operators (delimitted by space) can be overloaded as non-member functions: new delete new[] delete[] + - * / % ˆ & | ˜ ! < > += -= *= /= %= ˆ= &= |= << >> >>= <<= == != <= >= && || ++ -- , ->* The following have to be non-static member functions: -> () [] = The following can not be overloaded: . .* :: ?: # ## conversion operators also have to be member functions. And just because it has a '=' in it does not mean it cannot be overloaded as a non-member operator. The following is well-formed: struct A { }; A operator +=(A,A) { return A(); } A a = A()+=A(); And the prefix and postfix increment and decrement operators can indeed be defined as non-members: 13.5.7 The user-defined function called operator++ implements the prefix and postfix ++ operator. If this function is a member function with no parameters, or a non-member function with one parameter of class or enumeration type, it defines the prefix increment operator ++ for objects of that type. If the function is a member function with one parameter (which shall be of type int) or a non-member function with two parameters (the second of which shall be of type int), it defines the postfix increment operator ++ for objects of that type. When the postfix increment is called as a result of using the ++ operator, the int argument will have value zero. The prefix and postfix decrement operators -- are handled analogously Clause 13.5 in the Standard covers this. Hope this helps.
1,448,601
1,448,867
Convenient strategies for assertion checks
Some asserts are costly, some are better turned off at production code. At least it is not clear that assertions should be always enabled. In my application I would like to be able to turn on/off part of assertions on per-file or per-class basis. How to do it in C++?
For deactivating asserts module-wide i'd use: #if defined(assert) # undef assert # define assert(x) ((void)0) #endif ... of course this can be simplified if you are okay with using a custom macro. #if defined(_NO_ASSERTS) # define myAssert(x) ((void)0) #else # define myAssert(x) assert(x) #endif For class-wide deactivation i'd use a static const class member or a class-wide enum in combination with a custom macro: #define myAssert(x) do { if(_CLASS_ASSERT) { assert(x); } } while(0) class AssertOff { enum { _CLASS_ASSERT = 0 } } With enums and static const bools all modern compilers should optimize away the if(_CLASS_ASSERT) {}.
1,448,699
1,448,729
Opinions about list item and its class design
I'm currently designing a list widget to add to my widget engine. Since every elements visual aspects are defined outside the code I can reuse most of the code base. For instance tab buttons are actually checkboxes. New templates take time to implement since they should have at least a viewer in design application. I already have an implementation for a checkbox. It has 2 states (checked/unchecked) and 5 substates: normal, hover/active, mousedown, disabled and in state transition. A checkbox template has text properties, icon (optional), and border (might be resizable). There are also state and substate transitions. Both icons and borders are animatable. My concern is about list items. They are quite similar to checkboxes. Therefore, Im planning to use checkbox template for listitems. However, I require four modes of a list item: simple (text only), with icon, with a checkbox and with a radio button (a radio button is derived from a checkbox and IRadioButton interface). Here its structure: IWidgetObject | Checkbox IRadioButton \ / `--------------´ | RadioButton I wish to implement something like this. ListItemBase should be derived from IWidgetObject. Is it logical or are there better alternatives. class ListItemBase : public Checkbox { void Select() { do something; Checkbox::check(); } } //This listitem type will have a checkbox without any text class ListItemCheckbox : public ListItemBase, private Checkbox { check() { update parents checked list; Checkbox::check(); } } class ListItemRadio : public ListItemBase, private RadioButton, public IRadioButton { //here is the problem } ListItemRadio will have 2 distinct checkbox functionality, also I want to hide ListItemBase's check() function (to rename it). Then should I implement it this way? class ListItemBase : private Checkbox, public IWidgetObject { void Select() { do something; Checkbox::check(); } //does this even works? (layer is a variable) using Checkbox::layer; } //This listitem type will have a checkbox without any text class ListItemCheckbox : public ListItemBase, private Checkbox { check() { update parents checked list; Checkbox::check(); } } class ListItemRadio : public ListItemBase, private RadioButton, public IRadioButton { //here is the problem } But this time I have 2 IWidgetObjects in ListItemRadio, which I should overcome implementing common functions. But ListItemBase will have to map everything of IWidgetObject to Checkbox. Is it possible to use virtual inheritance to solve these problems, like delegating to sister class (checkbox). There is also one more problem, although IWidgetObject seems like an interface, over the years it picked up some common implementation, but I dont think it will be a problem. Also there is one more problem. Checkbox class has non-trivial constructor. Is it possible to write something like this: ListItemBase(IWidgetContainer &container, CheckboxBP &blueprint) : Checkbox(container, blueprint), IWidgetObject(this) { } This would solve lots of problems. Any idea is welcome. Thank you for even reading all these
OK, I come up with an idea IWidgetObject | ICheckbox CheckboxBase IRadioButton | \ / | \ / | | `-------------´ | `---------´ | | | | | | | Checkbox | RadioButton | | | | | ListItemBase | \ | | / `---------------´ `--------------´ | | ListItemCheckbox ListItemRadioButton What do you think?
1,448,817
1,448,846
Why there is no std::copy_if algorithm?
Is there any specific reason for not having std::copy_if algorithm in C++ ? I know I can use std::remove_copy_if to achieve the required behavior. I think it is coming in C++0x, but a simple copy_if which takes a range, a output iterator and a functor would have been nice. Was it just simply missed out or is there some other reason behind it?
According to Stroustrup's "The C++ Programming Language" it was just an over-sight. (as a citation, the same question answered in boost mail-lists: copy_if)
1,448,925
1,449,012
Advice on Abstract Factory, DLL Exporting and Smart Pointers
This is a follow up to one of my previous questions and I have come up with a possible solution to my project and I need some advice or guidance if I have this right. Basically my project is a library to be used and compiled on both Linux and Windows, the Linux part isn't much of an issue, its Windows. My library consists mainly of classes so 95% of C++ code. In order to provide better support and avoid name mangling issues I'm going to be using interfaces and factory methods to get instances of those classes rather than calling it directly. I will also use extern "C" on the factory functions ONLY to avoid name mangling. So here are the questions: I will use the export/import macros on the factory functions but do I then need to add the export/import (__declspec(dllexport/import)) on the header files of all of the classes I wish to provide instances for including the base class interfaces? Or is simply exporting the factory functions enough? I was also thinking of using smart-pointer features for automatic deallocation, good idea or let the user handle it? I was planning on using the autoptr template which is part of the standard library and available on both platforms right? Can anyone enlighten on which calling convention I should use? I know its Microsoft-specific so I hope it doesn't interfere with Linux so should I leave it blank and let it be the default which I think is _thiscall or something along those lines. I get an error for this piece of code, I'm not sure why but it is due to the extern "C": The error is: error: declaration of C function ‘std::ostream& operator<<(std::ostream&, const MemInfo&)’ conflicts with| previous declaration ‘std::ostream& operator<<(std::ostream&, const SpeedInfo&)’ here| error: declaration of C function ‘std::ostream& operator<<(std::ostream&, const analyzed_result&)’ conflicts with previous declaration ‘std::ostream& operator<<(std::ostream&, const MemInfo&)’ here| ... these error messages repeat for all the functions Here is the code: //WINLIB is my macro for the dllimport/export extern "C"{ //operator overloading for stream operation WINLIB std::ostream& operator<<(std::ostream &st, const SpeedInfo &si); WINLIB std::ostream& operator<<(std::ostream &st, const MemInfo &mi); WINLIB std::ostream& operator<<(std::ostream &st, const analyzed_result&); WINLIB std::ostream& operator<<(std::ostream &st, const ustring_set&); WINLIB std::ostream& operator<<(std::ostream &st, const speed_map&); WINLIB std::ostream& operator<<(std::ostream &st, const mem_map&); WINLIB SpeedInfo operator+(SpeedInfo &si, SpeedInfo &si2); WINLIB SpeedInfo& operator+=(SpeedInfo &si, SpeedInfo &si2); WINLIB SpeedInfo operator-(SpeedInfo &si, SpeedInfo &si2); WINLIB SpeedInfo& operator-=(SpeedInfo &si, SpeedInfo &si2); WINLIB MemInfo operator+(MemInfo &mi, MemInfo &mi2); WINLIB MemInfo& operator+=(MemInfo &mi, MemInfo &mi2); WINLIB MemInfo operator-(MemInfo &mi, MemInfo &mi2); WINLIB MemInfo& operator-=(MemInfo &mi, MemInfo &mi2); }
Exporting the factory function and including the headers for the classes in user code is sufficient. If you don't depend on it let the user choose his best tool for the job. __stdcall extern "C" gives you a c-style declaration scope - therefore you can't have overloading there. see here. as win32 dll is c-style too you can't directly export overloaded functions (think GetProcAddress()).
1,449,055
1,449,067
Disk Space? (used/free/total) how do I get this? in C++
Disk Space? (used/free/total) how do I get this? in C++... thanks just for reading.
GetDiskFreeSpaceEx win32 API
1,449,125
1,449,302
Writing a C# Variable Length Structure to Binary and Reading it in in C++?
Okay, so i am continuing to work on my little game engine to teach me C#/C++ more. Now i am attempting to write a way of storing data in a binary format, that i created. (This is learning, i want to do this my self from scratch). What i am wondering what is the best way of dealing with variable length arrays inside a structure when reading it in C++? E.g. Here is what i currently have for my structures: [StructLayout(LayoutKind.Sequential)] public struct FooBinaryHeader { public Int32 m_CheckSumLength; public byte[] m_Checksum; public Int32 m_NumberOfRecords; public FooBinaryRecordHeader[] m_BinaryRecordHeaders; public FooBinaryRecord[] m_BinaryRecords; } [StructLayout(LayoutKind.Sequential)] public struct FooBinaryRecordHeader { public Int32 m_FileNameLength; public char[] m_FileName; public Int64 m_Offset; } [StructLayout(LayoutKind.Sequential)] public struct FooBinaryRecord { public bool m_IsEncrypted; public Int64 m_DataSize; public byte[] m_Data; } Now how would i go about in C++ to actually read this in as a structure in C++? I was kinda hoping to get around reading each of the elements one by one and copying them into a structure. The only real tutorial i found on this is this: http://www.gamedev.net/community/forums/topic.asp?topic_id=310409&whichpage=1&#1989200 I'll take a wild guess and say reading this into a C++ structure is not really possible correct?
You can read it from binary format mapping a copy of these structures. Each array should be treated as a pointer and you should have a integer with size of this array. For example in C# [StructLayout(LayoutKind.Sequential)] public struct A { public Int32 m_CheckSumLength; public byte[] m_Checksum; } C++ struct A { int length char* vector } Notes: byte has the same size of char. When you read from a binary you can read the first 4 byte (int is 32 aka 4 byte) and allocate 4 + (readed length) after that you can read directly to the allocated buffer and treat as a A structure.
1,449,215
1,449,234
Is Vim editor very smart?
I am programming in C++ or Java. So I want to use Vim editor, because it is very flexible. I have heard that I can configure the Vim editor to be able to go from object to the definition from function to the definition from class name to the definition Do we have any professional Vim-er that could tell me exactly how to configure Vim for that? Thanks in advance. P.S. In case readers will consider this question is not connected with programming, I would say that this is improving speed of programming. So it is a help to the programmer. So please don't close this question. EDIT: Also I would like to know how vim works with code completion and can vim hint the list of methods that are available for the certain object? If yes, then I would like to know how to configure these options too?
What you're looking for is ctags and tags/TAGS files. Ctags (I recommend Exuberant Ctags) is a program which scans source files for identifiers and creates a file indexing them. You can then use ^] to jump to the definition for the tag under the cursor. There may be some additional details needed to tell vim how to find the tags file; I'm not sure off-hand what they are. But that's the general idea - run ctags over your source code and then use ^]. Alternatively, you may wish to look at GNU Global. It's a bit more sophisticated. But ctags will accomplish what you've described.
1,449,299
1,449,353
Qsort based on a column in a c-string?
A class project involves sorting an array of strings, with each string containing an equal number of columns like this: Cartwright Wendy 93 Williamson Mark 81 Thompson Mark 100 Anderson John 76 Turner Dennis 56 The program accepts a command-line argument for which column to sort on, and should print out the sorted strings unmodified. I would like to use strtok to break up copies of each string into columns, and make structs for each line like this: struct line { char * line; char column_to_sort_on[MAX_COLUMN]; } My problem is in the comparison function pointer that qsort takes as an arg. If I understand correctly, the comparison function must take two const void pointers to the items to be sorted, and return an int. This means I can't pass pointers to structs into the comparison function because that is not what qsort will be sorting. I can't pass in the column number to sort on to the comparison function, because it can only take two args. How can I get around this to sort these strings based on specific columns? edit: Sorting is limited to qsort or my own if I really want. Give the choice, I choose qsort. :) edit # 2:The consensus seems to be either use a global variable for the column number, or just use qsort to sort an array of structs. I hadn't thought of just sorting the structs, and using the pointer in them to print out the original string. I think that is what I will do. Thanks for the help all!
You can pass the structs like this: struct line { char * line; char column_to_sort_on[MAX_COLUMN]; } ... line* Lines[max_lines]; // here you store the structs int cmp_lines( const void *elem1, const void *elem2 ) { line* line1 = *(line**)elem1; line* line2 = *(line**)elem2; // do the comparisons } qsort(Lines, max_lines, sizeof(line*), cmp_lines);
1,449,304
1,449,350
Ideas to debug and solve a very sporadic crash - appears to be an AV
I have a bug somewhere that is causing my app to just vanish without an error message or something like that. The app just dissapears from the screen and it's no longer listed on the Task Manager. The app is a C++Builder app (CBuilder2007), and I have tried everything I have think of to try to catch this error. It happens very very seldom, it has never crashed on my machine and just once in the test machines we have in the office. With one of our customers it happens a little bit more frequent, but we haven't find a way to make it happen, or to find the circumstances where it happens. It is a heavy multithreaded app. I have madExcept enabled in this app, but it doesn't catch anything. I have already added handlers using the set_terminate and set_unexpected RTL routines, without any luck. The only info I have is from a "loader app" wrapper I did, to get the return code from the main app. It exits with the C0000005 code, which I believe means an Access Violation happened. The strange thing is that, as mentioned, there is not even the Windows error box or something like that. The question would be: any ideas to try to catch this? As I don't even have a clue where this might be happening (I have a lot of logging around the app, but the "trail" before the app crashes hasn't lead to anywhere) my idea with the set_terminate and set_unexpected routines was to get a stack trace to try to see where the error was generated, but so far those routines aren't being called at all (at least the only time this has happened here in my office) Thanks in advance [Update 22.Sept.2009] Using AddVectoredHandlerException I was able to get a callstack from the crash, and now I can start trying to isolate and fix the bug. Thanks!!!
terminate/unexpected gets called only by C++ runtime, and only for C++ exceptions. Access violation is a SEH exception - to catch that, you need SetUnhandledExceptionFilter, or AddVectoredExceptionHandler (if it's >=XP). You could then create a minidump, using MiniDumpWriteDump and related.
1,449,432
1,449,579
Message loop gets blocked when application menu has the focus
I'm developing an application that looks mainly like this: while (true) { while (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&Msg); DispatchMessage(&Msg); } DoSomething(); Sleep(1); } What I noticed is that DoSomething() doesn't get called when I click on the menu bar (displaying menu options). I've observed that DispatchMessage call blocks the messae loop until I get out of the menu bar! How could I avoid this behaviour?? Thanks!
The reason why is because Windows takes over the processing of messages when something like an application menu or message box is displayed, and that message loop which Windows uses won't call your DoSomething() method. This may be hard to visualize, so I'll try to step through what is happening: When someone opens your menu, a message is sent to your window telling it to draw the window. DispatchMessage() sends the message to your WndProc, like all other messages. Since you don't handle this message, it is passed to Windows (since your WndProc more than likely calls DefWindowProc) As the default operation, Windows draws the menu and starts another default message loop which will not call DoSomething() This loop fetches the messages destined for your application and dispatches them to your application by calling WndProc, so your application doesn't freeze and continues to operate (minus the DoSomething() call). Once the menu is closed, control will be returned to your message loop (only at this point will the DispatchMessage() call from the very beginning return) In other words, when a menu is displayed, your message loop is replaced by a default one which looks like this (for example) while (GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } which, as you can see, won't call your DoSomething() method. To test this, try pausing your code in a debugger when no menu is displayed, and while one is. If you see the callstack, you will see that when a menu is displayed, messages are being processed by a Windows message loop, not by yours. The only workaround I can think of (without multithreading) is if you start a timer and handle the WM_TIMER message by calling DoSomething(), but that would not be a perfect solution (since I presume your intent is to call DoSomething() only when there are no messages left to process).
1,449,525
1,449,589
c++ operator overloading memory question
In c++ you can create new instances of a class on both the heap and stack. When overloading an operator are you able to instantiate on the stack in a way that makes sense? As I understood it an instance that sits on the stack is removed as soon as the function is done executing. This makes it seems as though returning a new instance sitting on the stack would be a problem. I am writing this knowing there has to be a way, but I am not sure what the best practice is. If I have some class that is designed to always reside in the stack how do I go about operator overloading? Any info would be helpful, thanks {EDIT} I am overloading the + operator. Right now I use this code Point Point::operator+ (Point a) { Point *c = new Point(this->x+a.x,this->y+ a.y); return *c; } I was skeptical about instantiating c like so: Point c(this->x + a.x, this->y, a.y); because that would allocate it to the stack. My concern is that the stack pointer is going to change once this function finishes executing, and the instance will no longer be safe since any new local variables defined could erase it. Is this not a concern?
If you're talking about for example operator+, where the object returned is not either of those input, then the answer is you instantiate on the stack and return by value: struct SomeClass { int value; }; SomeClass operator+(const SomeClass &lhs, const SomeClass &rhs) { SomeClass retval; retval.value = lhs.value + rhs.value; return retval; } or class SomeClass { int value; public: SomeClass operator+(const SomeClass &rhs) const { SomeClass retval; retval.value = this->value + rhs.value; return retval; } }; or even: class SomeClass { int value; public: SomeClass(int v) : value(v) {} friend SomeClass operator+(const SomeClass &lhs, const SomeClass &rhs) { return SomeClass(lhs.value + rhs.value); } }; The compiler then worries about where (on the stack) the return value is actually stored. It will for example apply return-value optimizations if it can, but in principle what's happening is "as-if" the work you do constructs some value on the stack of your operator overload, and then at return this is copied to wherever it needs to be next. If the caller assigns the return value, it's copied there. If the caller passes it by value to some other function, it's copied wherever the calling convention says it needs to be in order to be that function parameter. If the caller takes a const reference, then it's copied to a temporary hidden away on the stack.
1,449,703
1,449,735
how to append a list<T> object to another
in C++, I have two list<T> objects A and B and I want to add all the members of B to the end of A. I've searched a few different sources and haven't found a simple solution (e.i. A.append(B);) and this surprises me a bit. What is the best way to do this? As it happens, I don't care about B after this (it gets deleted in the very next line) so if there is a way to leverage that for better perf I'm also interested in that.
If you want to append copies of items in B, you can do: a.insert(a.end(), b.begin(), b.end()); If you want to move items of B to the end of A (emptying B at the same time), you can do: a.splice(a.end(), b); In your situation splicing would be better, since it just involves adjusting a couple of pointers in the linked lists.
1,449,818
1,449,864
Formatting C++ console output
I've been trying to format the output to the console for the longest time and nothing is really happening. I've been trying to use as much of iomanip as I can and the ofstream& out functions. void list::displayByName(ostream& out) const { node *current_node = headByName; // I have these outside the loop so I don't write it every time. out << "Name\t\t" << "\tLocation" << "\tRating " << "Acre" << endl; out << "----\t\t" << "\t--------" << "\t------ " << "----" << endl; while (current_node) { out << current_node->item.getName() // Equivalent tabs don't work? << current_node->item.getLocation() << current_node->item.getAcres() << current_node->item.getRating() << endl; current_node = current_node->nextByName; } // The equivalent tabs do not work because I am writing names, // each of different length to the console. That explains why they // are not all evenly spaced apart. } Is their anything that I can use to get it all properly aligned with each other? The functions that I'm calling are self-explanatory and all of different lengths, so that don't align very well with each other. I've tried just about everything in iomanip.
You can write a procedure that always print the same number of characters to standard output. Something like: string StringPadding(string original, size_t charCount) { original.resize(charCount, ' '); return original; } And then use like this in your program: void list::displayByName(ostream& out) const { node *current_node = headByName; out << StringPadding("Name", 30) << StringPadding("Location", 10) << StringPadding("Rating", 10) << StringPadding("Acre", 10) << endl; out << StringPadding("----", 30) << StringPadding("--------", 10) << StringPadding("------", 10) << StringPadding("----", 10) << endl; while ( current_node) { out << StringPadding(current_node->item.getName(), 30) << StringPadding(current_node->item.getLocation(), 10) << StringPadding(current_node->item.getRating(), 10) << StringPadding(current_node->item.getAcres(), 10) << endl; current_node = current_node->nextByName; } }
1,449,908
1,449,960
Multiple Inheritance and Duck Typing
In working on Kira3, I was playing around with the C++ compiler and looking for a good way of implement Kira's duck typing. I was hoping (as it has been a few years of direct C++ programming) that I could use multiple inheritance for member access under multiple types. Alas, I have failed so far... The ideal code would look like: class WithX { public: int x; }; class WithY { public: int y; }; class WithZ { public: int z; }; class Point2D : public WithX, public WithY { }; class Point3D : public WithZ, public WithX, public WithY { }; void ZeroOut(Point2D * p) { p->x = 0; p->y = 0; }; int _tmain(int argc, _TCHAR* argv[]) { Point3D* p = new Point3D(); p->x = 1; p->y = 1; p->z = 1; ZeroOut(p); return 0; } However, it throws a typing error at the invocation of ZeroOut(p). This is ultra sad face. I can force it work by creating a type tower. In the above example, I could change class Point3D : public WithZ, public WithX, public WithY { }; to class Point3D : public Point2D, public WithZ { }; The problem now is when I have structures that overlap. I would either throw an error that would be a pain to solve in kira code, or I have the compiler do something different. I tried class Point3D : public Point2D, public WithZ, public WithX, public WithY { }; with the hope of the compiler combining them, but this gives ambiguous access to member variables. This can be fixed by replicating writes to the ambiguous member variables, and this could be a solution during my compilation phase. This solution requires more memory. Any ideas how to solve this without a memory loss? Or, is there a way to cast variables to multiple types? like (WithX,WithY *)p
I tried ... with the hope of the compiler combining them, but this gives ambiguous access to member variables. To solve that problem, try virtual inheritance.
1,450,133
1,457,665
Code that compiles for the iPhone Device but not for the Simulator
I am using C++ to develop the algorithmic part of an iPhone application, and I am encountering a strange bug. The code that I have, compiles fine with gcc-4.2 both on Linux, on the Mac, and on the iPhone device, just not on the Simulator, which makes debugging and testing very difficult. The error messages from the attempts to compile for the simulator resemble a known bug in 4.0.x, although that is not very clear why since I have explicitly set gcc-4.2 to be the default compiler. To demonstrate the bug, I have prepared the following small code snippet: bug.cpp #include <tr1/unordered_map> #include <iostream> /* a hash key for the visitedTrip table */ struct X { int x; X() : x(0){}; X(int x) : x(x){}; }; typedef std::tr1::unordered_map<int,X> dict; int main() { dict c1; X a(0); X b(1); X c(2); c1[0] = a; c1[1] = b; c1[2] = c; dict::const_iterator it; for(it = c1.begin(); it != c1.end(); it++) std::cout << it->first << std::endl; return (0); } and then tried to compile it as follows: compile.sh #!/bin/bash # # Compiling for the simulator and compiling under gcc-4.0 return the same error message # #SUCCESS c++-4.2 -arch i386 bug.cpp #FAIL c++-4.0 -arch i386 bug.cpp #SUCCESS gcc-4.2 -arch i386 -c bug.cpp #FAIL gcc-4.0 -arch i386 -c bug.cpp #FAIL gcc-4.2 -arch i386 -c bug.cpp -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.sdk Eventhough I am using gcc-4.2 to compile for the simulator, I am getting the same error message as if I were compiling under gcc-4.0, namely: bug.cpp:27: error: no matching function for call to ‘Internal::hashtable_iterator<std::pair<const int, X>, false, false>::hashtable_iterator()’ /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.sdk/usr/include/c++/4.2.1/tr1/hashtable:236: note: candidates are: Internal::hashtable_iterator<Value, is_const, cache>::hashtable_iterator(const Internal::hashtable_iterator<Value, true, cache>&) [with Value = std::pair<const int, X>, bool is_const = false, bool cache = false] /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.sdk/usr/include/c++/4.2.1/tr1/hashtable:234: note: Internal::hashtable_iterator<Value, is_const, cache>::hashtable_iterator(Internal::hash_node<Value, cache>**) [with Value = std::pair<const int, X>, bool is_const = false, bool cache = false] /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.sdk/usr/include/c++/4.2.1/tr1/hashtable:232: note: Internal::hashtable_iterator<Value, is_const, cache>::hashtable_iterator(Internal::hash_node<Value, cache>*, Internal::hash_node<Value, cache>**) [with Value = std::pair<const int, X>, bool is_const = false, bool cache = false] /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.sdk/usr/include/c++/4.2.1/tr1/hashtable:225: note: Internal::hashtable_iterator<std::pair<const int, X>, false, false>::hashtable_iterator(const Internal::hashtable_iterator<std::pair<const int, X>, false, false>&) Any ideas as to why this gcc-4.0.x bug creeps into the simulator, when in fact the simulator is supposed to be using gcc-4.2.x where this bug has been fixed?
Not sure if this is exactly the right answer, but this would probably explain why you're seeing the 4.0 behaviour while using 4.2: > pwd /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.sdk/usr/include/c++ > ls -l total 4 drwxr-xr-x 10 root wheel 2278 10 Sep 09:32 4.0.0/ lrwxr-xr-x 1 root wheel 5 10 Sep 09:30 4.2.1@ -> 4.0.0 It looks like they're trying to use the 4.0 header set for both versions, at least on Snow Leopard with Xcode 3.2.
1,450,423
1,450,433
What's wrong with this c++ code?
My C++ is a bit rusty so... #include<list> typedef list<int> foo; that gives me the oh so nice error message: test.cpp:2: syntax error before `;' token What the heck can I even Google for in that...
You are expecting the list to be in global namespace. But is defined inside std namespace. Hence either you should use using namespace std; or expliictly specify the namespace as std::list; I personally prefer the second option.
1,450,439
1,450,444
Cannot pass string to CreateThread receiver
I have a thread function that looks something like this: DWORD WINAPI Thread_ProcessFile( LPVOID lpParam ) { char *filename = (char*)lpParam; printf( "%s\n", filename ); } I also have a class that calls CreateThread and uses the above function for the routine address: void CMyClass::ProcessFile( void ) { HANDLE tHwnd = 0; char szBuffer[128]; strcpy( szBuffer, "test_string" ); tHwnd = CreateThread( NULL, 0, Thread_ProcessFile, (LPVOID)szBuffer, 0, NULL ); if ( tHwnd == NULL ) return; } The problem is that the routine is receiving/printing a garbage string and not the real thing (eg. random set of characters, if any). If I do this, however: tHwnd = CreateThread( NULL, 0, Thread_ProcessFile, (LPVOID)"test_string", 0, NULL ); the string is received and printed correctly. How can I properly build a string and pass it to my thread function?
You are creating the szBuffer on the stack. Hence by the time your thread starts, the ProcessFile() function would have returned and the stack variable would have been deallocated. Hence you are getting the garbage value. In the second case, you are passing a const-string which post probably resides in the read-only part of the process memory and is not deallocated on the function return (I don't think this is the guaranteed behavior, I wouldn't rely on it). So you are getting proper value in the function. You can allocate the string on the heap using new[] and pass the pointer to the thread. Don't forget to to delete[] once the processing is completed in the thread.
1,450,452
1,450,757
MySQL Connector/C++ Library Linking ERROR Problem
PROBLEM: Ok, I've been TRYING to follow the sample code on the MySQL Forge Wiki and some other websites that offer a tutorial on how to get a simple database connection, but for some reason, my project always fails at a linking error and I can't figure out why or how to fix it myself (I'm still learning). PLEASE HELP ME! I've included the path directory needed for the header files in the project properties AND provided the path directory to the lib files that are used in the MySQL Connector/C++. The code I'm using is below if someone could give me a helpful hint/ comment on how to fix it. I think it has something to do with connecting to the lib files (because of the linking error) but I don't know of a solution to fix it. Has anyone else had trouble like this? http://forge.mysql.com/wiki/Connector_C++ http://dev.mysql.com/tech-resources/articles/mysql-connector-cpp.html#createdb CODE: int main() { // do something sql::mysql::MySQL_Driver *driver; sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; sql::PreparedStatement *pstmt; cout << "Starting Driver Instance" << endl; driver = sql::mysql::MySQL_Driver::get_mysql_driver_instance(); return 0; } ERROR OUTPUT: 1>------ Build started: Project: test, Configuration: Debug Win32 ------ 1>Compiling... 1>main.cpp 1>c:\users\josh bradley\documents\visual studio 2008\projects\test\test\main.cpp(28) : error C2039: 'get_mysql_driver_instance' : is not a member of 'sql::mysql::MySQL_Driver' 1> c:\program files\mysql\mysql connector c++ 1.0.5\include\mysql_driver.h(25) : see declaration of 'sql::mysql::MySQL_Driver' 1>c:\users\josh bradley\documents\visual studio 2008\projects\test\test\main.cpp(28) : error C3861: 'get_mysql_driver_instance': identifier not found 1>Build log was saved at "file://c:\Users\Josh Bradley\Documents\Visual Studio 2008\Projects\test\test\Debug\BuildLog.htm" 1>test - 2 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== UPDATE: I just wanted to let everybody know that I finally found out how to fix my problem. For anyone having a similar problem, go to http://blog.ulf-wendel.de/?p=215#hello and read through the instructions on how to connect to the mysqlcppconn.lib dynamically. My problem was setting up the actual environment so it would connect to the library correctly and this tutorial helped tremendously!
You must first change your code: driver = sql::mysql::get_mysql_driver_instance(); And next, you have to link your code with mysqlclient.lib Add the right path of your lib mysqlclient.lib on your project: Properties->Linker->General-> Additionnal Libraries Here add the path of your lib.
1,450,654
1,518,397
Eclipse CDT with Cygwin GCC: automatic discovery of symbols and paths
I am using Eclipse CDT with Cygwin GCC 3 as compiler. My project is using a custom Makefile. The problem is that when debugging the code, it couldn't locate the source files, even though I added a custom path mapping for: /cygdrive/c <-> c:\ That in addition to the fact that I am getting "unresolved inclusion" for all standard header files, even though the program compiles and run fine. I traced the problem to the "automatic discovery" option, which shows the following error: Note that I made sure that the workspace directory is on a path without any spaces. The weird thing is that when I run that problematic command in the shell, it runs just fine with the following output: $ gcc -E -P -v -dD C:/Users/Amro/workspace/.metadata/.plugins/org.eclipse.cdt.make.core/specs.c Reading specs from /usr/lib/gcc/i686-pc-cygwin/3.4.4/specs Configured with: /managed/gcc-build/final-v3-bootstrap/gcc-3.4.4-999/configure --verbose --program-suffix=-3 --prefix=/usr --exec-prefix=/usr --sysconfdir=/etc --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --enable-languages=c,ada,c++,d,f77,pascal,java,objc --enable-nls --without-included-gettext --enable-version-specific-runtime-libs --without-x --enable-libgcj --disable-java-awt --with-system-zlib --enable-interpreter --disable-libgcj-debug --enable-threads=posix --enable-java-gc=boehm --disable-win32-registry --enable-sjlj-exceptions --enable-hash-synchronization --enable-libstdcxx-debug Thread model: posix gcc version 3.4.4 (cygming special, gdc 0.12, using dmd 0.125) /usr/lib/gcc/i686-pc-cygwin/3.4.4/cc1.exe -E -quiet -v -P -D__CYGWIN32__ -D__CYGWIN__ -Dunix -D__unix__ -D__unix -idirafter /usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../../include/w32api -idirafter /usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../../i686-pc-cygwin/lib/../../include/w32api C:/Users/Amro/workspace/.metadata/.plugins/org.eclipse.cdt.make.core/specs.c -mtune=pentiumpro -dD ignoring nonexistent directory "/usr/local/include" ignoring nonexistent directory "/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../../i686-pc-cygwin/include" ignoring duplicate directory "/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../../i686-pc-cygwin/lib/../../include/w32api" #include "..." search starts here: #include <...> search starts here: /usr/lib/gcc/i686-pc-cygwin/3.4.4/include /usr/include /usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../../include/w32api End of search list. #define __STDC_HOSTED__ 1 #define __GNUC__ 3 [.... truncated ....] #define __unix__ 1 #define __unix 1 I also tried to manually add to the include path: How can I fix this so that it discovers both the include paths and the defined symbols? Should I try turn off the auto discovery and hardcode the required paths in the .cproject file? Any help is appreciated (I only ask that you don't suggest using MinGW instead of Cygwin!)
Yours is a frequest source of complaints regarding mixing eclipse & cygwin. The crux of the problem is that eclipse understands only the windows environment & cygwin, well not so much. Define your paths in in eclipse windows style. Also is /usr is under C:\cygwin, you have to give it the full path. Otherwise eclipse is going to try to find it under c:\usr and come up empty. Also, are your path definitions appending to or replacing your windows environment? You'll probably be happier appending to your environment rather than replacing. Never tried autodetect - you may have to hard code those paths in .cproject
1,450,896
1,450,976
Defragmenting C++ Heap Allocator & STL
I'm looking to write a self defragmenting memory manager whereby a simple incrementing heap allocator is used in combination with a simple compacting defragmenter. The rough scheme would be to allocate blocks starting at the lowest memory address going upwards and keeping book-keeping information starting at the highest memory address working downwards. The memory manager would pass back smart pointers - boost's intrusive_ptr's seems the most obvious to the book-keeping structs that would then themselves point to the actual memory block thus giving a level of indirection so that the blocks can be easily moved around. The defragmenter would compact down the heap starting at 'generation' bookmarks to speed up the process and only defragmenting a fixed amount of memory at a time. Raw pointers to the blocks themselves would be valid until the next defrag pass and so could be passed around freely until such a time improving performance. The specific application for this is console game programming and so at the beginning or end of each frame a defrag pass could be done relatively safely. So my question is has anybody used this kind of allocation scheme in combination with STL would it just completely blow STL apart as I suspect. I can see std::list< intrusive_ptr > working at the intrusive_ptr level but what about the allocation of the stl list nodes themselves is there anyway to override the next/prev pointers to be intrusive_ptr's themselves or am I just going to have to have a standard heap allocator along side this more dynamic one.
If you're going to be moving objects around in memory then you can't do this fully generically. You will only be able to do this with objects that know that they might be moved. You also will need a locking mechanism. When a function is being called on an object, then it can't be moved. The reason is that the whole C++ model relies on objects sitting at fixed points in memory, so if a thread was calling a method on an object, this thread was paused and the object moved, disaster would strike when the thread resumed. Any object which held a raw memory pointer to another object that might be moved (including a sub-object of itself) would not work. Such a memory management scheme may work but you have to be very careful. You need to be strict about implementing handles, and the handle->pointer locking semantics. For STL containers, you can customize the allocator, but it still needs to return fixed raw memory pointers. You can't return an address that might move. For this reason, if you're using STL containers, they must be containers of handles, and the nodes themselves will be ordinary dynamically allocated memory. You may find that you too much in overhead in the handle indirection and still have problems in the fragmentation of the handle collections than you gain by using STL. Using containers that understand your handles directly might be the only way forward, and even then there may still be a lot of overhead compared to a C++ application that uses traditional objects fixed in memory.
1,451,103
1,451,123
Imposing constrains of template function types, without c++0x concepts
Now that we know that Concepts is not part of C++0x, I am looking for methods to impose restrictions on types in template functions. Here are two examples: If we want to make sure that a given type is an integer, we can use: template <class N> inline int f(const N n) { if ((N)0.1 != 0) // if type of N is floating-point err() .... } if we want to make sure that a given type is an unsigned integer, we can use: template <class N> inline int f(const N n) { if ((N)-1 < (N)1) // if type of N is floating-point / signed-integer err() .... } I am looking for creative ways to check for additional restrictions, that will cause in failure in run-time, or better, in compile-time (without concepts and without RTTI). Any suggestions?
Your checks can be handled much better at compile-time by using type-traits. The first: STATIC_ASSERT(std::numeric_limits<N>::is_integer) The second: STATIC_ASSERT(not std::numeric_limits<M>::is_signed) Have a look at the Boost Concept Check Library and at Boost.StaticAssert.
1,451,160
1,451,316
C++ Member Function Pointers and STL Algorithm
I have an abstract functor class that overloads operator() and derived objects that implement it. I have a function (part of another class) that tries to take an Array of these functor classes and tries to pass a pointer to a member function to the std algorithm for_each(), here is a overview of what I'm doing: EDIT: I have re-cleaned it and put the old small example for clarity. class A{ operator()(x param)=0; operator()(y param)=0; } class B: public A{ operator()(x param); //implemented operator()(y param); } ...// and other derived classes from A void ClassXYZ::function(A** aArr, size_t aSize) { ...//some code here for(size_t i = 0; i< aSize; i++){ A* x = aArr[i]; for(v.begin(), v.end(), ...//need to pass pointer/functor to right operator() of x here ..//other code } I've tried a few ways and I can't figure out how to get it to work, I need to use the abstract type as I could have different derived types but they will all have to implement the same operator()(param x) function. I just need the for_each() function to be able to call the member function operator()(param x). I have a different function where it has concrete implementations and simply passes an instance of those and it works. I'm trying to achieve a similar effect here but without the knowledge of what concrete classes I'm given. What am I doing wrong?
If I understand what you want to do, there are quite a few errors in your code snippet: sizeof aArr is wrong, you need to pass the size explicitly (noticed by ChrisW) Missing virtual specifier on the original declaration of operator()() Not sure where your for loop ends as there's no matching } (I suspect it shouldn't be there at all) Here's some code that will loop through an array of A (or A-derived) objects and call operator() on each one, passing across a passed-in argument as the param parameter: #include <iostream> #include <algorithm> #include <functional> using namespace std; typedef double param; // Just for concreteness class A { public: virtual void operator()(param x) = 0; }; class B : public A { public: void operator()(param x) { cerr << "This is a B! x==" << x << ".\n"; } }; void function(A** aArr, size_t n, param theParam) { void (A::*sFunc)(param x) = &A::operator(); for_each(aArr, aArr + n, bind2nd(mem_fun(sFunc), theParam)); } int main(int argc, char** argv) { A* arr[] = { new B(), new B(), new B() }; function(arr, 3, 42.69); delete arr[0]; delete arr[1]; delete arr[2]; return 0; } mem_fun() is necessary to convert a 1-parameter member function pointer to a 2-parameter function object; bind2nd() then produces from that a 1-parameter function object that fixes the argument supplied to function() as the 2nd argument. (for_each() requires a 1-parameter function pointer or function object.) EDIT: Based on Alex Tingle's answer, I infer that you might have wanted function() to do many things on a single A-derived object. In that case, you'll want something like: void function(A** aArr, size_t n, vector<param> const& params) { for (size_t i = 0; i < n; ++i) { void (A::*sFunc)(param x) = &A::operator(); for_each(params.begin(), params.end(), bind1st(mem_fun(sFunc), aArr[i])); } }
1,451,269
1,453,397
C++ libraries for Image Segmentation
I am going to do a project in Data Mining related to image clustering (in C++) .I am looking for a powerful library which is helpful in image processing, linear algebra and 3d graphics. Any thoughts? Thanks.
OpenCV is your best option in the C/C++ world in my opinion.
1,451,304
1,451,334
Python generators in various languages
How do you emulate Python style generators in your favorite language? I found this one in Scheme. It must be interesting to see other implementations, especially in those languages that don't have first-class continuations.
Here is an example in C++ that simulates generators using fibers: Yield Return Iterator for Native C++ Using Fibers The "yield return" iterator is a language feature that was created for one reason: simplicity. It is generally much easier to iterate across whole collectionl, storing all context needed in local variables, rather than crafting a complicated, custom iterator object that stores its state across subsequent retrieval operations. There are also the primitive C routines setjmp, longjmp to achieve similar results. (Lua coroutines are implemented with the above method)
1,451,433
1,451,443
C++ Templates and Inheritance
Let's say I have a simple Server with a template which accepts a Client as it's template argument: template<class T> class Server<T>{ Server(int port); } and a Client is defined something like this: class Client{ Client(Server<Client> *server, // <-- int socket); }; But I also want say, have the class User inherit from Client (class User : public Client), so I could do Server<User> instead of Server<Client>. class User obviously needs to pass Server<Client> as a parameter when constructing Client. However, with the current implementation this seems impossible. How should I approach this problem?
What about this? template<class T> class Server<T>{ Server(int port); }; template<class Derived> class Client { Client(Server<Derived> *server, int socket); virtual ~Client() {} // Base classes should have this }; class User : public Client<User> { };
1,451,569
1,451,585
Member variables and STL algorithms
#include <vector> #include <functional> #include <algorithm> using namespace std; struct Foo { int i; double d; Foo(int i, double d) : i(i), d(d) {} int getI() const { return i; } }; int main() { vector<Foo> v; v.push_back(Foo(1, 2.0)); v.push_back(Foo(5, 3.0)); vector<int> is; transform(v.begin(), v.end(), back_inserter(is), mem_fun_ref(&Foo::getI)); return 0; } Is there a cleaner way to access a member variable then then using a member function like I have above? I know how to do it using tr1::bind, but I need to have C++03 compliant code without boost.
It's absolutely unclean to need an accessor function in order to do that. But that's the current C++. You could try using boost::bind, which does the trick quite easily, or iterate the vector explicitly, using a for( vector<int>::const_iterator it = v.begin(); .....) loop. I find the latter often resulting in clearer code when the creation of the functor becomes too much a hassle. Or, shunning boost, create your own member-accessor shim function. template< typename T, typename m > struct accessor_t { typedef m (T::*memberptr); memberptr acc_; accessor_t( memberptr acc ): acc_(acc){} // accessor_t( m (T::*acc) ): acc_(acc){} // m (T::*acc_); const m& operator()( const T& t ) const { return (t.*acc_); } m& operator()( T& t ) const { return (t.*acc_); } }; template< typename T, typename m > accessor_t<T,m> accessor( m T::*acc ) { return accessor_t<T,m>(acc); } ... transform( v.begin(), v.end(), back_inserter(is), accessor( &C::i ) );
1,451,606
1,451,799
Programably make and play a sound through speakers C++
I'm making a game in native vc++ (not .Net) I'm looking for a way to play a noise (maybe 8 bit or something) through the real speakers (not internal). I know about PlaySound, but I don't want to make my EXE big. I want to program the sound. Is there an api way (kinda like Beep() ) but that plays through the real speakers? Thanks
You mention that you know about PlaySound. One of the it's flags (SND_MEMORY) will allow you to play a WAVE that is already loaded into memory, i.e. a buffer that you have created yourself. As long as the buffer has the appropriate WAVE header, whatever you you put in there should play through the speakers. The header is a 44 byte block that is fairly straight forward struct WaveHeader { DWORD chunkID; // 0x46464952 "RIFF" in little endian DWORD chunkSize; // 4 + (8 + subChunk1Size) + (8 + subChunk2Size) DWORD format; // 0x45564157 "WAVE" in little endian DWORD subChunk1ID; // 0x20746d66 "fmt " in little endian DWORD subChunk1Size; // 16 for PCM WORD audioFormat; // 1 for PCM, 3 fot EEE floating point , 7 for μ-law WORD numChannels; // 1 for mono, 2 for stereo DWORD sampleRate; // 8000, 22050, 44100, etc... DWORD byteRate; // sampleRate * numChannels * bitsPerSample/8 WORD blockAlign; // numChannels * bitsPerSample/8 WORD bitsPerSample; // number of bits (8 for 8 bits, etc...) DWORD subChunk2ID; // 0x61746164 "data" in little endian DWORD subChunk2Size; // numSamples * numChannels * bitsPerSample/8 (this is the actual data size in bytes) }; You'd set up your buffer with something similar to: char *myBuffer = new char[sizeof(WaveHeader) + myDataSize]; WaveHeader *header = (WaveHeader*)myBuffer; // fill out the header... char *data = myBuffer + sizeof(WaveHeader); //jumps to beginning of data // fill out waveform data... So you use it something like: PlaySound(myBuffer, NULL, SND_MEMORY | SND_ASYNC); I'm assuming that you're going to be using you generated sound for the lifetime of you app. If you aren't, be careful with that SND_ASYNC flag. That is, don't go freeing the buffer directly after you call PlaySound (while it is still in use). MSDN PlaySound Docs A page with more detail on the WAV header (OLD - not working now) DirectX also supports playing audio from in-memory buffers and is a much more powerful API, but it maybe overkill for what you need to do :)
1,451,694
1,472,965
Is there a way to diff files from C++?
I'm looking for a C or C++ diff library. I know I can use the Unix diff tool in combination with system or exec, but I really want a library. It would be handy if the library could perform patches as well, like the Unix patch tool.
I think I've found a good solution, finally: The DTL - Diff Template Library --- Tutorial It supports patch. I had to type "diff.cpp" into Google to find it. Hopefully it works!
1,451,740
1,451,753
calculate array index from pointers
Me and some peers are working on a game (Rigs ofRods) and are trying to integrate OpenCL for physics calculation. At the same time we are trying to do some much needed cleanup of our data structures. I guess I should say we are trying to cleanup our data structures and be mindful of OpenCL requirements. One of the problems with using open CL is the inability to use pointers as the memory space is different. From what little I know of OpenCL is copies all the data onto the GPU then performs the calculations, pointer values would be copied but the address would not correspond to the expected address. The data in question is centralized in an array, when objects need to that data they use pointers to the object it needs, or stores an array index. One solution to account for OpenCL is to use array index instead of pointers. This leads to hard coupling that could lead to headaches later on. As a solution I had the idea of calculating the array index based on the address of the start and the address of the current. This of course would only work with a continuous array. I wrote a sample app to test this and it worked just fine, some people verified it on different platforms as well. #include <iostream> typedef struct beam_t { unsigned int item; } beam_t; #define GLOBAL_STATIC_ASSERT(expr, msg) \ extern char STATIC_ASSERTION__##msg[1]; \ extern char STATIC_ASSERTION__##msg[(expr)?1:2] #ifdef __amd64 typedef unsigned long pointer_int; #else typedef unsigned int pointer_int; #endif GLOBAL_STATIC_ASSERT(sizeof(pointer_int) == sizeof(pointer_int*), integer_size); #define MAX_BEAM 5 int main () { beam_t beams[MAX_BEAM]; beam_t* beam_start = &beams[0]; beam_t* beam_ptr = NULL; std::cout << "beams: " << &beams << "\n"; for( pointer_int i = 0; i < MAX_BEAM; ++i ) { beam_ptr = &beams[i]; pointer_int diff = ((pointer_int)beam_ptr - (pointer_int)beam_start); std::cout << "beams[" << i << "]: " << beam_ptr << "\t calculated index:" << diff / sizeof(beam_t) << "\n"; } return 0; } I'm concerned that this more of a kludge than a bonified solution. I'm aware that this would not work no non-coninuous memory. basically my questions are this: What would be the pitfalls for using this approach in known coninuous memory? How would you be able to tell it was continuous? What approaches have people used when dealing with this type of issue? Thanks, and my appologies if the formating is off, this is my first time posting a question.
This should give you the index of pointer relative to base: pointer - base Yes, it's that easy. =] Use ptrdiff_t to store the result portably.
1,451,780
1,451,806
Fast exponentiation: real^real (C++ MinGW, Code::Blocks)
I am writing an application where in a certain block I need to exponentiate reals around 3*500*500 times. When I use the exp(y*log(x)) algorithm, the program noticeably lags. It is significantly faster if I use another algorithm based on playing with data types, but that algorithm isn't very precise, although provides decent results for the simulation, and it's still not perfect in terms of speed. Is there any precise exponentiation algorithm for real powers faster than exp(y*log(x))? Thank you in advance.
If you need good accuracy, and you don't know anything about the distribution of bases (x values) a priori, then pow(x, y) is the best portable answer (on many -- not all -- platforms, this will be faster than exp(y*log(x)), and is also better behaved numerically). If you do know something about what ranges x and y can lie in, and with what distribution, that would be a big help for people trying to offer advice. The usual way to do it faster while keeping good accuracy is to use a library routine designed to do many of these computations simultaneously for an array of x values and an array of y values. The catch is that such library implementations tend to cost money (like Intel's MKL) or be platform-specific (vvpowf in the Accelerate.framework on OS X, for example). I don't know much about MinGW, so someone else will need to tell you what's available there. The GSL may have something along these lines.
1,451,861
1,451,951
Creating an array of zero width and zero height?
I have an assignment from my programming class, which is very poorly worded... The following line really stumps me. We're creating a class called FloatArray, which contains an array (arr, which is just a pointer to a bunch of floats). The default constructor FloatArray(); should create array of zero width and zero height. I have no clue what my professor means by that... Does anyone else? We're required to provide another constructor, which indicates the height and width of the array. That's fine and dandy - just plug in the numbers, and allocate away... But what does he mean by "create array of zero width and zero height"? Just so you know, the array is simply defined as: float *arr; Help me understand this madness! If it were up to me, I wouldn't even make a blank constructor for such a class... Regardless - am I overlooking something here? Is this some kind of terminology I've never encountered before, or am I correct in stating that this is madness? Should I just do the following in the default constuctor? *arr = 0; Because I can't do arr = new float[0], now can I :P (Or maybe I can - I just tried it (thanks Thomas!) and it compiles and runs... !?) Does this mean that when I do arr = new float[0], arr points to some location (the beginning?) on the heap? I know this question seems quite vague, but that's how the entire assignment is - very poorly worded. I just want to make sure it's not just me!
Doing *arr = 0 in the constructor would be very unwise. Since arr is uninitialized it might point to anything. Therefor *arr = 0 means "set some random memoryblock to 0 which probably will fail. On the other hand, doing arr = new float[0] is indeed a valid operation. I would recommend using a "new float[0]" for 0-size arrays. This reduces some special handling of 0-size arrays, such as arrays explicitly created using new FloatArray(0) which should result in the exact same array as new FloatArray(). Note that a good alternative may be to have a default zero-value of the length argument in the "regular" constructor.
1,451,925
1,476,691
DirectShow DVD playback
I have created a custom allocator/presenter that works fine for playback of normal media files. However, when I use the following code to try to playback a DVD, it fails with a stack overflow exception. vmr9_ap = new vmr9ap(); HMONITOR monitor = MonitorFromWindow(hwnd, NULL); IGraphBuilder *graph; IBaseFilter *filter; IDvdGraphBuilder *builder; CoCreateInstance(CLSID_DvdGraphBuilder, NULL, CLSCTX_INPROC_SERVER, IID_IDvdGraphBuilder, reinterpret_cast<void**>(&builder)); CoCreateInstance(::CLSID_VideoMixingRenderer9, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, reinterpret_cast<void**>(&filter)); builder->GetDvdInterface(IID_IVMRFilterConfig9, (void**)&vmr9_config); vmr9_ap->Initialize(g_pd3dDevice, monitor, vmr9_config); HRESULT hr = builder->RenderDvdVideoVolume(L"G:\\VIDEO_TS", AM_DVD_SWDEC_PREFER | AM_DVD_VMR9_ONLY, &status); builder->GetFiltergraph(&graph); IDvdControl2 *dvdControl; builder->GetDvdInterface(::IID_IDvdControl2, (void**)&dvdControl); graph->QueryInterface(::IID_IMediaControl, (void**)&control); HRESULT h = control->Run(); The stack overflow happens immediately after the call to control->Run(). It's driving me nuts, as I'm sure I'm just forgetting something really really simple. Thanks.
Your graph should look something like this. Make sure there aren't any buggy filters in your graph. Because you are using a custom allocator, I would look there for the issue and set some breakpoints there. You code you pasted might be incomplete as I do not see you configure the VMR9 with the custom allocator, nor do I see it being added to the graph. I avoid using the DVDGraphBuilder as I had too difficult of a time getting it RenderVolume correctly with my VMR9+Allocator. I would build the graph a little more manually. I have a custom allocator in my open source project, along w/ a DVD player. You can check that out for reference, though there is a lot of code noise in there due to me needing to hack a few things in there for WPF compatiblity. http://wpfmediakit.codeplex.com What you are seeing should NOT be a DRM issue. alt text http://img29.imageshack.us/img29/7798/capturelu.jpg
1,451,973
1,451,985
Good books or tutorials for beginning Direct X with c++
I'm pretty familiarity with c++. I'v made a few games like tetris and solitaire with it. But what I would really like is some nice textured graphics for those games :-p GDI just isn't doing it for me anymore. Really, all I would need to know is: DX scene initialization making something simple like a round rectangle and basic shapes ability to move those shapes in X and Y add basic bitmap texture dispose of the objects anything that would cover these concepts would be really useful Thanks
This is a good tutorial. I've started with it and it was helpful. That is not a book, but good enough tutorial with step-by-step explanations.
1,452,040
1,452,435
How to read an intermittent hard drive consistently?
I have a faulty hard drive that works intermittently. After cold booting, I can access it for about 30-60 seconds, then the hard drive fails. I'm willing to write a software to backup this drive to a new and bigger disk. I can develop it under GNU/Linux or Windows, I don't care. The problem is: I can only access the disk for some time, and there are some files that are big and will take longer than that to be copied. For this reason, I'm thinking of backing up the entire hard disk in smaller pieces, something like bit torrenting. I'll read some megabytes and store it, before trying to read another set. My main loop would be something like this: while(1){ if(!check_harddrive()){ sleep(100ms); continue; } read_some_megabytes(); if(!check_harddrive()){ sleep(100ms); continue; } save_data(); update_reading_pointer(); if(all_done){ break; } } The problem is the check_harddrive() function. I'm willing to write this in C/C++ for maximus API/library compatibility. I'll need some control over my file handlers to check if they are still valid, and I need something to return bad data, but return, if the drive fails during the copy process. Maybe C# would give me best results if I abuse "hardcoded" hardware exceptions? Another approach would be measuring how much time would I need to power cycle my harddrive and code a program to read it during this time only, and flagging me when to power cycle. What would you do in this case? Are there any tools/utilities that already do this? Oh, there is a GREAT app to read bad optical medias here, it's called IsoPuzzle, it's not mine, I just wanted to share something related to my problem. !EDIT! Some clarifications. I'm a home user, a student of computer engineering at college, I'd rather lose the data than spend thousands of dollars recovering it. The harddrive is still covered by Seagate's warranty, but since they gave me 5 years of warranty, I wanna try everything possible until the time runs out. When I say cold booting, I mean booting after some seconds without power. Hot booting would be rebooting your computer, cold booting would be shutting it down, waiting a few seconds then bootting it up again. Since the harddisk in question is internal but SATA, I can just disconnect the power cable, wait a few seconds and connect it again. Until now I'll go with robocopy, I'm just searching for it to see how I can use it. If I don't need to code myself, but script, it'll be even easier. !EDIT2! I wasn't clear, my drive is a Seagate 7200.11. It's known that it has a bad firmware and it's not always fixable with a simple firmware update (not after this bug appears). The drive physically is 100% in working condition, just the firmware is screwed, making it enter on a infinite busy state after some seconds.
I think the simplest way for you is to copy the entire disk image. Under Linux your disk will appear as a block device, /dev/sdb1 for example. Start copying the disk image until the read error appear. Then wait for the user to "repair" the disk and start reading from the last position. You can easily mount file disk image and read its content, see -o loop option for mount. Cool down disk before use. I heard that helps.
1,452,140
1,452,206
Count up and down elegantly
I'm trying to make a flashing object, i.e., increment it's alpha value from 0 to 255 (gradually) and then back down to 0, and repeat. Is there a way I can do this without using some boolean? Getting it to increment is easy: alpha = time.elapsed()%256; But what's a nice way to get it to count back down again after that?
How about using a sin function, that way the fading is more pleasant and you'll get what you want.
1,452,235
5,570,354
Does an R compiler to C/C++ exist?
I'm wondering about the best way to deploy R. Matlab has the "matlab compiler" (MCR). There has been discussion about something similar in the past for R that would compile R into C or C++. Does anyone have any experience with the R to C Compiler (RCC) that was developed by John Garvin at Rice? I've looked into it, and it seems to be the only project that worked on compiling R code into executable code. And as far as I can tell, it isn't still being used. [Edit 1:]: To be clear, I know that there are C and C++ (and Java, Python, etc.) interfaces to R (rJava, rcpp, Rpy, etc.). I'm wondering about specific ways to compile and deploy R code without installing R in advance. [Edit 2:]: John Mellor-Crummey tells me that they're still working on RCC and hope to make it available in 4 months or so (at the earliest). I'll update this further if I find anything else out.
A byte code compiler will be part of the R 2.13 release. By default it is not used in this release but it is available; I expect the 2.14 release will by default byte compile all base and recommended packages. The compiler::compile help page and the R Installation and Administration Manual give some more details.
1,452,501
1,452,520
String Replace in C++
I've spent the last hour and a half trying to figure out how to run a simple search and replace on a string object in C++. I have three string objects. string original, search_val, replace_val; I want to run a search command on original for the search_val and replace all occurrences with replace_val. NB: Answers in pure C++ only. The environment is XCode on the Mac OSX Leopard.
A loop should work with find and replace void searchAndReplace(std::string& value, std::string const& search,std::string const& replace) { std::string::size_type next; for(next = value.find(search); // Try and find the first match next != std::string::npos; // next is npos if nothing was found next = value.find(search,next) // search for the next match starting after // the last match that was found. ) { // Inside the loop. So we found a match. value.replace(next,search.length(),replace); // Do the replacement. next += replace.length(); // Move to just after the replace // This is the point were we start // the next search from. } }
1,452,668
1,452,758
Advantages of knowing for a client, how big the package sended by the server is
I'm really new at network-programming, so I hope this isn't a complete Newbie-question. I read a tutorial at the Qt-Homepage how to build a little server, and I found this: QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out << (quint16)0; out << "..."; // just some text out.device()->seek(0); out << (quint16)(block.size() - sizeof(quint16)); At the start of our QByteArray, we reserve space for a 16 bit integer that will contain the total size of the data block we are sending. [We continue by streaming in a random fortune.] Then we seek back to the beginning of the QByteArray, and overwrite the reserved 16 bit integer value with the total size of the array. By doing this, we provide a way for clients to verify how much data they can expect before reading the whole packet. So I want to know, what are the advantages of this procedure? What can happen if you don't do that? Maybe you also could add a little example.
It is standard stuff. To the receiving program everything coming over the network is just a stream of bytes. The stream has no meaning beyond what the application imposes upon it, exactly the same way a file has no meaning beyond how its records, lines, etc., are defined by the application(s). The only way the client and server can make sense of the stream is to establish a convention, or protocol, that they agree upon. So some common ways to accomplish this are by: have a delimiter that designates the end of a message (e.g. a carriage return) pass a length field, as in your example, which tells the receiver how much data comprises the next message. just establish a fixed convention (e.g. every message will be 20 bytes or type 'A' records will be one defined format, type 'B' records another...) just treat it like a stream by having no convention at all (e.g. take whatever comes over the network and put it in a file w/o paying any attention to what it is) One advantage of the length byte method is that the receiver knows exactly how much data to expect. With some added sanity checks this can help eliminate things like buffer overflows and such in your application.
1,452,710
1,453,259
RTSP library in Python or C/C++?
I am trying to find any RTSP streaming library for Python or C/C++. If not is there any other solutions for real time streaming? How much easy or difficult it is to implement RTSP in Python or C/C++ and where to get started?
try live555. They have a lots of libraries and modules for implementing rtp and rtsp (as well as sip) into your c and c++ programs
1,452,721
1,452,738
Why is "using namespace std;" considered bad practice?
I have heard using namespace std; is bad practice, and that I should use std::cout and std::cin directly instead. Why is this? Does it risk declaring variables that share the same name as something in the std namespace?
Consider two libraries called Foo and Bar: using namespace foo; using namespace bar; Everything works fine, and you can call Blah() from Foo and Quux() from Bar without problems. But one day you upgrade to a new version of Foo 2.0, which now offers a function called Quux(). Now you've got a conflict: Both Foo 2.0 and Bar import Quux() into your global namespace. This is going to take some effort to fix, especially if the function parameters happen to match. If you had used foo::Blah() and bar::Quux(), then the introduction of foo::Quux() would have been a non-event.
1,452,883
1,452,905
Is there an C++ equivalent to Python's "import bigname as b"?
I've always liked Python's import big_honkin_name as bhn so you can then just use bhn.thing rather than the considerably more verbose big_honkin_name.thing in your source. I've seen two type of namespace use in C++ code, either: using namespace big_honkin_name; // includes fn(). int a = fn (27); (which I'm assured is a bad thing) or: int a = big_honkin_name::fn (27); Is there a way to get Python functionality in C++ code, something like: alias namespace big_honkin_name as bhn; int a = bhn::fn (27);
namespace bhn = big_honkin_name; There's another way to use namespaces too: using big_honkin_name::fn; int a = fn(27);
1,453,131
1,453,141
How can I get polymorphic behavior in a C++ constructor?
I have a base class that I want to look like this: class B { // should look like: int I() { return someConst; } virtual int I() = 0; public B() { something(I()); } } The point being to force deriving classes to override I and force it to be called when each object is constructed. This gets used to do some bookkeeping and I need to know what type of object is being constructed (but I otherwise treat the current object as the base class). This doesn't work because C++ won't let you call an abstract virtual function from the constructor. Is there a way to get the same effect? Based on this link it would seem that the answer is there is no way to get what I want. However what it says is: The short answer is: no. A base class doesn't know anything about what class it's derived from—and it's a good thing, too. [...] That is, the object doesn't officially become an instance of Derived1 until the constructor Derived1::Derived1 begins. However in my case I don't want to know what it is but what it will become. In fact, I don't even care what I get back as long as I the user can (after the fact) map it to a class. So I could even use something like a return pointer and get away with it. (now back to reading that link)
You can't call virtual methods from the constructor (or to be more precise, you can call them, but you'll end up calling the member function from the class currently being constructed)., the problem is that the derived object does not yet exist at that moment. There is very little you can do about it, calling virtual methods from the constructor polymorphically is simply out of the question. You should rethink your design -- passing the constant as an argument to the constructor, for example. class B { public: explicit B(int i) { something(i); } }; See C++ faq for more. If you really want to call virtual functions during construction, read this.
1,453,243
1,453,266
How can I avoid using exceptions in C++?
What techniques can I use to avoid exceptions in C++, as mentioned in Google's style guide?
Don't throw exceptions. Don't use STL (which relies heavily on exceptions). Use only new(std::nothrow) or override ::operator new to return 0 on failure. Note that by avoiding exceptions, you're effectively throwing out lots of useful libraries, including Boost. Basically, you'll have to program everything from scratch.
1,453,392
1,453,898
UpdateLayeredWindow, SIZE_RESTORED and GetClientRect problem
I have a layered window set up in my MFC application. I have set up my own derivation of CDialog to allow me to customise various parts of how the window is rendered. Everything works fine right up until I start worrying about minimise and maximise. If you click minimise or maximise then the window reacts exactly as you'd expect (ie exactly as it does when NOT using a layered window). However, when I restore the window something very odd happens. The default client rectangle for my test window is 324x102. When I restore from the minimised state, for example, the cx and cy passed to OnSize is 994, 550. If I then do a GetClientRect (within OnSize) this is the size reported for the window. Weirdly, though if i do GetWindowRect I get the correct size back (though obviously including all my non-client areas). Does anybody have any idea what is going on here and, more importantly, how I can fix it such that GetClientRect reports the CORRECT information? Thanks in advance!
I have come up with a sort of hack to solve this problem. In OnSize and OnMove I ignore the (c)x and (c)y that I receive and work everything out from a GetWindowRect. The application now reacts as expected. I have marked the code with a [HACK] comment. This does seem very odd though, I'd love to hear WHY this is happening.
1,453,393
1,453,412
Legit Uses of the offsetof Macro in C / C++
There is this macro offsetof in C/C++ which allows you to get the address offset of a member in a POD structure. For an example from the C FAQ: struct foo { int a; int b; }; struct foo; /* Set the b member of foo indirectly */ *(int *)((char *)foo + offsetof(b)) = 0xDEADBEEF; Now this just seems evil to me and I can't see many legit uses of this macro. One legit example I have seen is it's use in the container_of macro in the Linux Kernel for getting the address of an embedded structures parent object: /* get the address of the cmos device struct in which the cdev structure which inode points to is embedded */ struct cmos_dev *cmos_devp = container_of(inode->i_cdev, struct cmos_dev, cdev); What other legit uses are there for this macro? When should you not use this macro? EDIT So far this answer to a different SO question is the best one I've seen so far.
Well ... In C, it's very useful for any place where you need code to describe a data structure. I've used it e.g. to do run-time-generated GUI:s for setting options. This worked like this: a command that needs options defines a local structure holding its options, and then describes that structure to the code that generates the GUI, using offsetof to indicate where fields are. Using offsets rather than absolute addresses allows the GUI code to work with any instance of the struct, not just one. This is bit hard to sketch quickly in an example (I tried), but since comments indicate an example is in order, I'll try again. Assume we have a self-contained module, called a "command", that implements some action in the application. This command has a bunch of options that control its general behaviour, which should be exposed to the user through a graphical user interface. For the purposes of this example, assume the application is a file manager, and the command could be e.g. "Copy". The idea is that the copy code lives in one C file, and the GUI code in another, and the GUI code does not need to be hard-coded to "support" the copy command's options. Instead, we define the options in the copy file, like so: struct copy_options { unsigned int buffer_size; /* Number of bytes to read/write at a time. */ unsigned int copy_attributes; /* Attempt to copy attributes. */ /* more, omitted */ }; static struct copy_options options; /* Actual instance holding current values. */ Then, the copy command registers its configuration settings with the GUI module: void copy_register_options(GUIModule *gui) { gui_command_begin(gui, "Copy"); gui_command_add_unsigned_int(gui, "Buffer size", offsetof(struct copy_options, buffer_size)); gui_command_add_boolean(gui, "Copy attributes", offsetof(struct copy_options, copy_attributes)); gui_command_end(gui); } Then, let's say the user asks to set the copy command's options. We can then first copy the current options, to support cancelling, and ask the GUI module for a dialog holding controls, built at run-time, suitable for editing this command's options: void copy_configure(GUIModule *gui) { struct copy_options edit = options; /* Assume this opens a modal dialog, showing proper controls for editing the * named command's options, at the address provided. The function returns 1 * if the user clicked "OK", 0 if the operation was cancelled. */ if(gui_config_dialog(gui, "Copy", &edit)) { /* GUI module changed values in here, make edit results new current. */ options = edit; } } Of course, this code assumes the settings to be pure value-types, so we can copy the struct using simple struct assignment. If we also supported dynamic strings, we'd need a function to do the copying. For configuration data though, any string would probably best be expressed as a statically-sized char array in the struct, which would be fine. Note how the fact that the GUI module only knows where each value lives expressed as an offset allows us to provide the dialog function with a temporary on-stack copy. Had we instead set up the GUI module with direct pointers to each field, this would not be possible which would be far less flexible.
1,453,497
1,453,573
Discover if user has Admin rights
How can I determine if the current user (the user running my application) has admin rights (i.e. is a member of the Administrator group)? I need to register some COM components differently for users with limited access. I am using C++ (WTL and Win32).
IsUserAnAdmin() is the fast and easy way, but MSDN warns that it might go away in the future, so you might want to call CheckTokenMembership() on your thread/process token instead (Comparing with a well known sid for the admin group)
1,453,568
1,453,620
Portable way to detect heap fragmentation in c++ at runtime?
I'm writing a qt-based c++ application and i need to be able to detect memory fragmentation in order to check if the current system can actually sustain the memory load: the program load a big image (15/21 megapixels are the norm) in memory and then perform some filtering on it (w/ sparse matrices). For instance, i'm having memory fragmentation problem in Windows and VMMap has been very helpful in this: the problem was some DLLs (Wacom tablet "wintab32.dll" and the UltraMon app) doesn't get relocated so are splitting the address space at the 0x10000000-0x30000000 VA of the process. I want to provide the application with some sort of awareness toward the fragmentation problem and wondering if a cross-platform (linux/mac/win32) approach giving the information VMMAP gives already exist.
Short answer: There is no portable way. Longer answer: How the heap is implemented and how it works is an implementation detail of your implementation that widely differs between platforms, std libraries, and operating systems. You'll have to create a different version for each implementation - provided, the implementation gives you an API to hook into it. (Which I think should be the case for the three platforms you target.)
1,453,725
1,453,758
Sorting names with numbers correctly
For sorting item names, I want to support numbers correctly. i.e. this: 1 Hamlet 2 Ophelia ... 10 Laertes instead of 1 Hamlet 10 Laertes 2 Ophelia ... Does anyone know of a comparison functor that already supports that? (i.e. a predicate that can be passed to std::sort) I basically have two patterns to support: Leading number (as above), and number at end, similar to explorer: Dolly Dolly (2) Dolly (3) (I guess I could work that out: compare by character, and treat numeric values differently. However, that would probably break unicode collaiton and whatnot)
That's called alphanumeric sorting. Check out this link: The Alphanum Algorithm
1,453,878
1,453,893
Distributed shared memory library for C++?
I am writing a distributed application framework in C++. One of the requirements is the provision of distributed shared memory. Rather than write my own from scratch (and potentially re-invent the wheel), I thought I would see if there were any pre-existing Open source libraries - a quick google search did not yield anything to useful. Does anyone on here have any experience of a good C++ DSM library that they can recommend? Ideally, the library will support MRMW (Multiple readers/multiple writers), but I can make do with MRSW (Multiple readers, single writer) if need be. I am developing on Linux.
Have you considered memcached ? It is network distributed and it can be really fast. It has bindings for lots of languages, you can access it from different OS and supports multiple writers multiple readers.
1,454,050
1,454,069
Borland C++ localization
I am currently using Codegear RAD Studio 2007. One of my company clients' decided that he would be interested in localized version of our software (to Russian - I don't know if it matters, that we won't be able to use standard windows code page). As a part of our software we are using RAVE to generate some reports. Is there any solution, that would work out-of-the-box? We are looking for a way that would make it as automatic as possible. There is huge amount of code, and not much time ;) We have forged some ideas how to make it from scratch, but they seem very time-consuming. Personally, I have used QT for some time, but unfortunately switching to another framework is not an option.
I'm not sure about your particulars, but generally the gettext library is the right way to go about internationalization and googling for gettext borland c++ does yield some results.
1,454,058
1,462,211
Windows messages serviced whilst assert dialog is being displayed?
I have an MFC application that spawns a number of different worker threads and is compiled with VS2003. When calling CTreeCtrl::GetItemState() I'm occasionally getting a debug assertion dialog popup. I'm assuming that this is because I've passed in a handle to an invalid item but this isn't my immediate concern. My concern is: From my logs, it looks as though the MFC thread continues to service a number of windows messages whilst the assert dialog is being displayed. I thought the assert dialog was modal so I was wondering if this was even possible?
The message box that shows the assertion failure has a message pump for its own purposes. But it'll dispatch all messages that come in, not just those for the message box (otherwise things could get blocked). With a normal modal dialog, this isn't a problem because the parent window is typically disabled for the duration of the dialog. The code that launches the assertion dialog must've failed to figure out the parent window, and thus it wasn't disabled. This can happen if your main window isn't the active window at the time of the assertion. Other things can go wrong as well. You can change how Visual Studio's C run-time library reports assertion failures with _CrtSetReportMode. You can make it stop in the debugger and/or log to the output window instead of trying to show the dialog.
1,454,208
1,454,288
Passing ant command line options to an exec'd ant process?
I'm using ant to build a mixture of Java and C++ (JNI) code that makes up a client project here. I've recently switched the C++ part of the build to using ant with cpptasks to build the C++ code instead of having ant invoke the various versions of Visual Studio that are necessary to build the code. In order to get this to work, it is necessary to use ant's exec task to spawn off a shell in which a shell script or a batch file executes to set up the compiler environment before triggering another ant that executes the cpptasks-based C++ build. Essentially, the C++-related build tasks in the main ant build file look like this for Windows: <target name="blah"> <exec executable="cmd" failonerror="true"> <arg value="/C"/> <arg line="&quot;${cpp.compiler.path}/vsvars32.bat&quot; &amp;&amp; %ANT_HOME%/bin/ant -f cpp-build.xml make-cpp-stuff" /> </exec> </target> There is no way to get rid of the vsvars32.bat invocation as the code has to be built with multiple VS versions and on build machines where none of the Visual Studio setup can be part of the build user's environment. The above works, but the issue I'm running into is that I would like to pass certain command line options (like -verbose, -quiet, -emacs) through to the child ant if they have been passed to the parent ant. Is it possible to get access at the command line options given to the parent ant at all? Please note I'm not talking about the usual property definitions, but the ant-internal options.
<target name="blah"> <property environment="env"/> <exec executable="cmd" failonerror="true"> <arg value="/C"/> <arg value="${cpp.compiler.path}/vsvars32.bat"/> <arg value="&amp;&amp;"/> <arg value="${env.ANT_HOME}/bin/ant.bat"/> <arg value="-f" /> <arg value="cpp-build.xml" /> <arg value="make-cpp-stuff" /> </exec> </target> Addition You can create an external batch file that will run the vsvars and the ant, and then you will have only one process to create. I believe the && is not working as you expect it to: run-ant-vs.bat: ....\vsvars32.bat %ANT_HOME\bin\ant.bat -f cpp-build.xml make-cpp-stuff