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,209,406
1,209,473
Interprocess Communication between C++ app and Java App in Windows OS environment
We have a C++ application on Windows that starts a java process. These two apps need to communicate with each other (via snippets of xml). What interprocess communication method would you choose, and why? Methods on the table for us are: a shared file(s), pipes and sockets (although I think this has some security concerns). I'm open to other methods.
I'm not sure why you think socket-based communication would have security concerns (use SSL). It is often a very good approach as it is language agnostic, assuming that you have a well-defined communication protocol. Have a look at Google's protocol buffers, for example - they generate the required Java classes and streams. In my experience, file systems (especially network file systems) are not well suited to such communication as they are not necessarily tuned for messaging (I've seen caching issues result in files being not picked up by the target process for example). Another option is a messaging layer (AMQ or Tibco for example) although this will likely involve a greater administrative overhead (plus expertise) to set up. Personally I would opt for a pure-socket approach because of its flexibility and simplicity. You will be in complete control.
1,209,497
1,209,516
How to configure Visual Studio for native C++ (unmanaged) development?
I am completely new to C++ development and am trying to learn it in Visual Studio. How can I be sure that I am learning only C++ and not the managed extensions? What configuration settings do I need to change? What project types should I stick to? Any other advice? Side issue: I have tried turning off Language Extensions under Project properties -> C/C++ -> Language -> Disable Language Extensions but this has generated a compiler error: Error 1 Command line error D8016 : '/Za' and '/clr' command-line options are incompatible I've no idea what's going on here ..
The fact that you have /clr switch in there means you're using a .Net project type - you need to choose a "Win32" project type to get a pure C++ project. Avoid anything calling itself "managed" or "CLR".
1,209,528
1,209,839
Converting simple C++ code to C# automatically
I have a file in C++ containing constant definitions, I want to use the same definitions in a C# project. Since both projects are part of a bigger project, I want if there is a change (addition/deletion) in the C++ file it should get reflected in corresponding C# file too. I want to keep the 2 files in sync. I was wondering if there is a script/tool to do this. A reverse solution (C#-->C++) would also work. Clarification: Currently the code is: //C++ struct Colors{ static const int Red = 100; //Custom Values are important static const int Green = 101; } //C# public enum Color{ Red = 100; Green =101; } Now I want to have a single file so that any changes in C++ are reflected in C# (or other way around) so that I can have a single file across the projects for these constants. As you see, I want to map bunch of constants defined in a struct in C++ to a enum in C#. I want to make no/minimal changes in above expected definitions as there is other code dependent (in both projects) on the above structures (but might do it, if there's not a good way of accomplishing this in the current format)
You probably wont find a script... You should have your own script to do this. Otherwise MACROs are the best fit... If you have a script then you can create a rule in your makefile that will automatically run this script whenever you build your project.
1,209,748
1,210,156
How do I call C++ functions from a Lua script?
I'm using Visual Studio 2005. ------------------------[ luapassing.cpp ]-------------------- #include "lua.h" static int myCfunc (Lua_State *L){ double trouble = lua_tonumber(L,1); lua_pushnumber(L,16.0 -trouble); return 1; } int luaopen_luapassing (Lua_State *L){ static const lua_reg Map [] = {{"dothis",myCfunc},{NULL,NULL}}; luaL_register(L,"cstuff",Map); return; } -------------------------[ csample.lua ]------------------------- package.cpath = "./CLua2.dll" require "luapassing" print("hola") print(seth.doThis(120))
I see several issues. I'll describe them, and provide a code fragment that should work as I believe you intended this sample to work. Your first problem is that the C++ compiler mangled the name of the only function exported from your DLL whose name matters to Lua: luaopen_luapassing(). The stock binary distribution for Windows was compiled as a C program, and assumes a C style name for the DLL module entry point. Also, you have the protocol for the luaopen_x function slightly wrong. The function returns an integer which tells Lua how many items on the top of Lua's stack are return values for use by Lua. The protocol assumed by require would prefer that you leave the new module's table object on the top of the stack and return it to Lua. To do this, the luaopen_x function would ordinarily use luaL_register() as you did, then return 1. There is also the issue of naming. Modules written in pure Lua have the opportunity to be less aware of their names. But modules written in C have to export a function from the DLL that includes the module name in its name. They also have to provide that module name to luaL_register() so that the right table is created and updated in the global environment. Finally, the client Lua script will see the loaded module in a global table named like the name passed to require, which is also returned from require so that it may be cached in a local in that script. A couple of other nits with the C code are that the numeric type really should be spelled lua_Number for portability, and that it would be conventional to use luaL_checknumber() rather than lua_tonumber() to enforce the required argument to the function. Personally, I would name the C implementation of a public function with a name related to its name that will be known publicly by Lua, but that is just a matter of taste. This version of the C side should fix these issues: #include "lua.h" static int my_dothis (Lua_State *L){ lua_Number trouble = luaL_checknumber(L,1); lua_pushnumber(L,16.0 -trouble); return 1; } extern "C" int luaopen_luapassing (Lua_State *L){ static const lua_reg Map [] = { {"dothis", my_dothis}, {NULL,NULL} }; luaL_register(L,"luapassing",Map); return 1; } The sample script then needs to refer to the loaded module by its proper name, and to the functions defined by that module by their proper names. Lua is case sensitive, so if the module creates a function named dothis(), then the script must use that same name, and cannot find it named doThis(), for example. require "luapassing" print("hola") print(luapassing.dothis(120)) I should add that I haven't actually compiled and run the above, so there might be a typo or two left as an exercise ;-)
1,209,885
1,209,920
Visual Studio: How to Build a Static Library for use in Another Project (Avoiding STL Linking Errors)
I'm new to Visual Studio and Windows as a development platform, and I'm having troubles linking a static library from one 'Project' into an executable in another. The library builds without error, but linking bails after finding several STL template instantiations defined in the library. For the purpose of this question, Project A builds a static library, which I then attempt to link with in Project B. I'm hoping someone can point out what I'm missing here. The build command line for Project A: /Od <includes> /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_WIN32_WINNT=0x0501" /D "DEBUG" /D "WS4_WIN32" /D "AF" /D "_VC80_UPGRADE=0x0710" /D "_MBCS" /Gm /EHsc /RTC1 /MTd /Fo"Debug\\" /Fd"Debug\vc90.pdb" /W3 /nologo /c /Wp64 /ZI /TP /wd4290 /errorReport:prompt The build and link command lines for Project B: /Od <includes> /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Gm /EHsc /RTC1 /MDd /Fo"Debug\\" /Fd"Debug\vc90.pdb" /W3 /nologo /c /ZI /TP /wd4290 /errorReport:prompt /OUT:<exe name> /INCREMENTAL /NOLOGO /MANIFEST /MANIFESTFILE:"<exe name>.intermediate.manifest" /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /DEBUG /PDB:<pdb name> /SUBSYSTEM:CONSOLE /DYNAMICBASE /NXCOMPAT /MACHINE:X86 /ERRORREPORT:PROMPT kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib <Project A Lib file> When the linker runs, I get a ton of errors of the following form: msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "<some STL template instantiation>" (<mangled name>) already defined in <Project A>.lib(<some Project A object>.obj) I think this is telling me that an STL instantiation defined in an object of my library is also defined in msvcprtd.lib. What's not clear to me is if I'm not building my static library correctly, or if my linker settings are wrong. I would appreciate any guidance on this.
You have mismatching runtime libraries specified. It is set to /MTd for project A and /MDd for project B. /MTd - Multithreaded Debug /MDd - Multithreaded Debug DLL
1,209,893
1,220,022
CStatic Custom Control
I am trying to create a custom CStatic control in vc++ and have a few problems. I originally was just using a CStatic control with the SS_BLACKRECT style. This was good for the situation until I needed to display an image over the control on demand. I figured out all the logistics behind actually drawing the image onto the control but I cant seem to figure out how to do so without interfering with other things. Basically I want the control to function as a normal CStatic with the SS_BLACKRECT style most of the time. Then I need to be able to call a method that will cause it to draw an image over the control instead. I am doing the drawing using GDI and have tried it both in the OnPaint() method and the DrawItem() method without success. I can get it to draw in the OnPaint() but when I call the base CStatic::OnPaint() it draws over my image. I need to be able to allow it to draw like normal but then just throw an image in on top. When I tried to do it in the DrawItem() method I had a problem because obviously it was not drawing using the SS_BLACKRECT style but waiting for me to draw the control like its supposed to. I guess what I think I'm looking for is one of three things. A way to draw using GDI after the base OnPaint() method finishes. A way to have the control draw the default SS_BLACKRECT style and then OWNERDRAW the image afterwards. Or the code to mimic the drawing of SS_BLACKRECT. The last one might be the easiest but I just don't know all the things I need to set up to draw a CStatic control like the default DrawItem.
Try calling Default() in your OnPaint() handler. Then, depending on whether you're drawing your image, you can then draw over the top of the standard CStatic control.
1,210,013
1,210,049
Why isn't stl compare function a member?
Just idly curious why the compare function for stl::sort can't be a static member? I have a small little helper class foo that is declared and defined in a header, but now I have to create a foo.cpp file for the implementation of cmp() so it isn't multiply defined. I also have to think of a suitably decorated name so fooCmp() doesn't clash with any other cmp(). Because it has no access to any member variables any compare operation that needs access to some other value (eg. sort by distance from foo.bar) needs the complex bind2nd call.
I am not sure what you are complaining about: std::sort(begin,end) // use operator< std::sort(begin,end,order) // Where order is a functor So order can be: A function A static member function Or an object that behaves like a function. The following works for me: class X { public: static bool diff(X const& lhs,X const& rhs) { return true;} }; int main() { std::vector<X> a; std::sort(a.begin(),a.end(),&X::diff); } But if the class has some natural ordering then why not just define the operator< for the class. This will allow you the access to the members and will behave nicely for most of the standard containers/algorithms that need to define an ordering. class X { public: bool operator<(X const& rhs) const { return true;} }; int main() { std::vector<X> a; std::sort(a.begin(),a.end()); }
1,210,072
1,210,270
How to select an unlike number in an array in C++?
I'm using C++ to write a ROOT script for some task. At some point I have an array of doubles in which many are quite similar and one or two are different. I want to average all the number except those sore thumbs. How should I approach it? For an example, lets consider: x = [2.3, 2.4, 2.11, 10.5, 1.9, 2.2, 11.2, 2.1] I want to somehow average all the numbers except 10.5 and 11.2, the dissimilar ones. This algorithm is going to repeated several thousand times and the array of doubles has 2000 entries, so optimization (while maintaining readability) is desired. Thanks SO! Check out: http://tinypic.com/r/111p0ya/3 The "dissimilar" numbers of the y-values of the pulse. The point of this to determine the ground value for the waveform. I am comparing the most negative value to the ground and hoped to get a better method for grounding than to average the first N points in the sample.
Given that you are using ROOT you might consider looking at the TSpectrum classes which have support for extracting backgrounds from under an unspecified number of peaks... I have never used them with so much baseline noise, but they ought to be robust. BTW: what is the source of this data. The peak looks like a particle detector pulse, but the high level of background jitter suggests that you could really improve things by some fairly minor adjustments in the DAQ hardware, which might be better than trying to solve a difficult software problem. Finally, unless you are restricted to some very primitive hardware (in which case why and how are you running ROOT?), if you only have a couple thousand such spectra you can afford a pretty slow algorithm. Or is that 2000 spectra per event and a high event rate?
1,210,115
1,210,145
How to call c++ functionality from java
I have a Java program that is mostly GUI and it shows data that is written to an xml file from a c++ command line tool. Now I want to add a button to the java program to refresh the data. This means that my program has to call the c++ functionality. Is the best way to just call the program from java through a system call? The c++ program will be compiled for mac os and windows and should always be in the same directory as the java program. I would like to generate an executable can the c program be stored inside the jar and called from my program?
Assuming no better communication method is available (SOAP, ICE, Sockets, etc), I'd call the executable using Runtime.exec(). JNI can be used to interface directly, but I wouldn't recommended it. No you can't put an executable in the jar. Well you can, but you can't run it, since the shell doesn't know how to run it.
1,210,149
1,210,154
serving up a png file via ifstream
This seems like a really simple task, so bear with me. I'm trying to extend a server which serves up files and webpages. Currently the server gets an HTTP request, parses it, and calls a function called sendFile: void sendFile(ostream& ostr, std::string filename) { std::ifstream ifs(filename.c_str(), std::ios_base::binary); ostr << ifs.rdbuf(); } This scheme currently works fine for text files like javascript and css which are in the same directory as the server binary. But when I try to serve up a png file, the browser sits forever. It seems like the difference is that the png file is not a text file, but if this is indeed the problem, what should I be using instead of ifstream? I see that the std::ios_base::binary flag is specified. Thanks!
You really should be setting the length and the mime type in the http headers.
1,210,282
1,210,293
C++ linker problems with static method
I'm writing a Vector3D class that calls a static method on a VectorMath class to perform a calculation. When I compile, I get this: bash-3.1$ g++ VectorMath.cpp Vector3D.cpp /tmp/cc5cAPia.o: In function `main': Vector3D.cpp:(.text+0x4f7): undefined reference to 'VectorMath::norm(Vector3D*)' collect2: ld returned 1 exit status The code: VectorMath.h: #ifndef VECTOR3D_H #include "Vector3D.h" #endif class VectorMath { public: static Vector3D* calculatePerpendicularVector(Vector3D*, Vector3D*); static Vector3D* norm(Vector3D*); static double length(Vector3D*); }; VectorMath.cpp #include "VectorMath.h" Vector3D* norm(Vector3D* vector) { // can't be found by linker // do vector calculations return new Vector3D(xHead, yHead, zHead, xTail, yTail, zTail); } // other methods Vector3D.cpp #include "Vector3D.h" #include "VectorMath.h" // ... // vector implementation // ... int main(void) { Vector3D* v = new Vector3D(x, y, z); Vector3D* normVector = VectorMath::norm(v); // error here } Why can't the linker find the VectorMath::norm method? At first glance I'd think that I'd need to declare norm like this: Vector3D* VectorMath::norm(Vector3D* vector) { but that doesn't help either...
You're missing this: //VectorMath.cpp #include "VectorMath.h" | V - here Vector3D* VectorMath::norm(Vector3D* vector) { ... } The norm function is part of VectorMath::. Without that, you just have a free function. This is more about your design, but why are you using pointers to everything? This is much cleaner: class VectorMath { public: static Vector3D norm(const Vector3D&); }; Take references, you're in C++ so don't write C code. What happens when I call this? VectorMath::norm(0); // null It will either crash, you have to put in a check, in which case, what should it return? This is all cleaned up by using references. Also, why not just make these members of the Vector3D class? Vector3D* v = new Vector3D(x, y, z); v->norm(); // normalize would be better, in my opinion Lastly, stack-allocate things. Your code right now has a memory leak: int main(void) { Vector3D* v = new Vector3D(x, y, z); Vector3D* normVector = VectorMath::norm(v); // delete v; // ^ you're not deleting it! } Change it to this, and use RAII concepts: int main(void) { Vector3D v(x, y, z); Vector3D* normVector = VectorMath::norm(v); // delete v; // ^ you're not deleting it! } And by making norm a member function you end up with the very clean code: int main(void) { Vector3D v(x, y, z); Vector3D normVector(v.norm()); } No pointers, no leaks, all sexy.
1,210,306
1,320,197
Format of parameter to display call graph for templated method with gprof?
What is the command line format to display function call graph for a method in templated class with gprof? For simple C method you would specify it like: gprof -f foo myprogram > gprof.output How do you specify method parse from the following: template <typename T> class A { public: template <typename X> bool parse(X& x, char*buf) { ... lots of code here ...; } };
I was after the actual format to be used on command line. I can see the compiled symbols by looking at the generated files but I'm not sure what format to use on command line. Thanks anyway for all answers.
1,210,362
1,210,379
Which C++ material should I work on next?
I've been doing C++ for 3-4 months in a local college and I'm doing extra reading / learning using Accelerated C++ and so far, I've "finished" it. Now, I'm wondering which book to get next that'll help me code better in C++. I've looked around and found this: The Definitive C++ Book Guide and List I'm sorry if this question may seem stupid for most of you here but I'm a bit tight in cash and I would really want to invest in something that's "right" for me at this time. Right now, I only know the basics of stuff like (classes, templates, STL, iterators, dynamic memory management). Do you have any suggestions? Should I focus on STL or templates..? Or should I read something like The C++ Programming language?
If you haven't yet read Stroustrup's books, they are definitely a good read. There's nothing quite like reading about the language from the person who designed it. Whenever I learn a new language, I always try to find the canonical reference material written by the language designer or somebody very close to them.
1,210,533
1,210,556
interposers on Windows
Is it possible to substitute system functions, as is possible on Linux and Solaris using the LD_PRELOAD For example by setting the environment variable: LD_PRELOAD=/path/to/mymalloc.so I would have my replacement malloc functions instead of in the C runtime already installed in the system libraries. All other functions in the system dll's would run as normal.
Microsoft Research has a library called Detours which allows you to intercept Win32 API calls. Detours is a library for instrumenting arbitrary Win32 functions on x86, x64, and IA64 machines. Detours intercepts Win32 functions by re-writing the in-memory code for target functions. The Detours package also contains utilities to attach arbitrary DLLs and data segments (called payloads) to any Win32 binary.
1,210,623
1,210,634
best way to write a linux daemon
For work i need to write a tcp daemon to respond to our client software and was wondering if any one had any tips on the best way to go about this. Should i fork for every new connection as normally i would use threads?
It depends on your application. Threads and forking can both be perfectly valid approaches, as well as the third option of a single-threaded event-driven model. If you can explain a bit more about exactly what you're writing, it would help when giving advice. For what it's worth, here are a few general guidelines: If you have no shared state, use forking. If you have shared state, use threads or an event-driven system. If you need high performance under very large numbers of connections, avoid forking as it has higher overhead (particularly memory use). Instead, use threads, an event loop, or several event loop threads (typically one per CPU). Generally forking will be the easiest to implement, as you can essentially ignore all other connections once you fork; threads the next hardest due to the additional synchronization requirements; the event loop more difficult due to the need to turn your processing into a state machine; and multiple threads running event loops the most difficult of them all (due to combining other factors).
1,210,988
1,210,995
For C++ developers, is it worth to switch from VS2005 to VS2008?
We're mostly doing C++ developing in Visual Studio 2005, and some C# coding. We're considering upgrading to Visual Studio 2008, but we're wondering if it will be worth the trouble. From what I've seen, and that is not much, VS2008 doesn't have any big advantages over VS2005. So is it worth switching to VS2008 from VS2005, or is it better to wait for VS2010? What are your experiences switching from VS2005 to VS2008? Thanks in advance! Regards, Sebastiaan
No, not really. There were only minor improvements to the C++ IDE, and the major improvements coming from the C++ team at MSFT are in Visual Studio 2010 (including an intellisense overhaul). It would not be beneficial to C++ developers in anyway really, you're not missing out.
1,211,092
1,211,214
Implementing Monitor with signaling using mutex and condition variable in C++
Did any body implemented a Monitor with signaling (wake up waiting threads) using a mutex and condition variables in C++. I dont know how to start. Any sample code or online article will be great. Are there any open source libraries who have implemented these? I need for windows and linux. But to start with windows(win32) will be fine.
This Qt Quarterly article explains how to do this using Qt's QMutex and QWaitCondition. But you should be able to reimplement it with whatever mutex class you want to use.. See also the more advanced example in here..
1,211,144
1,211,436
What features to implement in a version control system?
I will be implementing a version control system in C++ for my final year project. I would like to know: What are the features a version control system should must support. What features do you consider are missing in existing implementations (so that my version control system does more than just reinventing the wheel) References (if any) to start with.
What are the features a version control system should must support. Core features: Create Project, Check in, Check out, Branch, Get Latest/Previous, View History, Compare, Rollback What features do you consider are missing in existing implementations (so that my version control system does more than just reinventing the wheel ) Auto Build, Code Analysis, Email Notification, In-place editor, Database based storage
1,211,190
1,386,558
How to setup sound intensity on windows mobile?
I playing a sound file with a custom player, when the mobile goes in suspend mode (because the user pushed the red button) I would like to resume sound intensity when the mobile resume. How can I do ?
You can set the volume by opening the waveOut device and setting the volume. This will affect all sound playback: waveOutOpen waveOutSetVolume
1,211,399
1,211,402
In C++, what is a "namespace alias"?
What is a "namespace alias" in C++? How is it used?
A namespace alias is a convenient way of referring to a long namespace name by a different, shorter name. As an example, say you wanted to use the numeric vectors from Boost's uBLAS without a using namespace directive. Stating the full namespace every time is cumbersome: boost::numeric::ublas::vector<double> v; Instead, you can define an alias for boost::numeric::ublas -- say we want to abbreviate this to just ublas: namespace ublas = boost::numeric::ublas; ublas::vector<double> v;
1,211,841
7,273,530
How can I make Visual Studio's build be very verbose?
I need to get a hold of every flag, every switch used in the build process by the Visual Studio binaries. I tried to obtain a verbose output by using vcbuild, but I wasn't able. What do I have to do to see everything performed by Visual Studio for me? It's not necessary to obtain the output in the build window. Anywhere would be fine.
Open the project properties dialog, then choose Configuration Properties → C/C++ → General Change the setting for Suppress Startup Banner to No The cl command line(s) will be shown in the output window.
1,211,982
1,212,950
Can someone explain how the signedness of char is platform specific?
I recently read that the differences between char unsigned char and signed char is platform specific. I can't quite get my head round this? does it mean the the bit sequence can vary from one platform to the next ie platform1 the sign is the first bit, platform2 the sign could be at the end? how would you code against this? Basically my question comes from seeing this line: typedef unsigned char byte; I dont understand the relevance of the signage?
Let's assume that your platform has eight-bit bytes, and suppose we have the bit pattern 10101010. To a signed char, that value is −86. For unsigned char, though, that same bit pattern represents 170. We haven't moved any bits around; it's the same bits, interpreted two different ways. Now for char. The standard doesn't say which of those two interpretations should be correct. A char holding the bit pattern 10101010 could be either −86 or 170. It's going to be one of those two values, but you have to know the compiler and the platform before you can predict which it will be. Some compilers offer a command-line switch to control which one it will be. Some compilers have different defaults depending on what OS they're running on, so they can match the OS convention. In most code, it really shouldn't matter. They are treated as three distinct types, for the purposes of overloading. Pointers to one of those types aren't compatible with pointers to another type. Try calling strlen with a signed char* or an unsigned char*; it won't work. Use signed char when you want a one-byte signed numeric type, and use unsigned char when you want a one-byte unsigned numeric type. Use plain old char when you want to hold characters. That's what the programmer was thinking when writing the typedef you're asking about. The name "byte" doesn't have the connotation of holding character data, whereas the name "unsigned char" has the word "char" in its name, and that causes some people to think it's a good type for holding characters, or that it's a good idea to compare it with variables of type char. Since you're unlikely to do general arithmetic on characters, it won't matter whether char is signed or unsigned on any of the platforms and compilers you use.
1,212,391
1,223,284
Microsoft Visual Studio: Loading resources in Qt application (without plug-in)
We don't have a Qt plug-in installed for MSVS, and it makes me wonder how/whether it is possible to load resources (images, etc) to the application.
Yes, you can load ressources. Unfortunately, the qrc Editor which create qrc files is part of the Qt Addin for VS... But you can create this xml file by hands, for the format see here Once the qrc file created, you have at least two possibilities : A) Use qmake Add a reference to your qrc file in your pro file : RESOURCES = ApplicationResources.qrc Regenerate your vcproj from your pro by using qmake qmake -tp vc B) If you don't generate your vcproj file from your pro file, you can : Add manually your qrc file in your solution, for example in the following path : Resource Files/Res/ApplicationResources.qrc Add the following commands in the properties of the qrc file in visual studio : command line : $(QTDIR)\bin\rcc.exe -name ApplicationResources res\ ApplicationResources.qrc -o $(IntDir)\qrc__ ApplicationResources.cpp Description : RCC res/ApplicationResources.qrc Output : $(IntDir)\qrc__ ApplicationResources.cpp C) You can also use an external binary resources file The command line :rcc -binary myresource.qrc -o myresource.rcc In the application, you have to register the resource file : QResource::registerResource("/path/to/myresource.rcc"); For using resource file in the source code see the doc However, like cheez, I also suggest using qmake and pro file and do not edit properties by hand in Visual Studio... Hope this helps !
1,212,525
1,212,638
How do I change the background color of a conditional macro in eclipse?
How do I change the background color of a conditional macro in eclipse? I am using the C/C++ version of Eclipse so I would assume it would be associated with a mysterious preprocessor background color setting.
Preferences -> C/C++ -> Editor -> Inactive Code Highlight Duh! ;-)
1,212,713
1,212,809
Marshaling from C# to C++
I gotta pass an InParameter from my C# application to an exported function from a VC++ DLL. The function accepts 2 parameters : int func_name (FILE* fp, BYTE& by); fp is In and by is Out parameter. I was thinking of marshaling using IntPtr for the FILE* and using byte for BYTE. Is it correct? If I write the following in C# [DllImport("name_of_project.dll", CharSet = CharSet.Ansi)] public static extern int func_name(IntPtr FilePointer, [MarshalAs(UnmanagedType.BYTE&)] byte by); will it work? I think it will give an error for the '&' sign in the marshaling statement. How do I pass the out parameter by reference? Your help would be much appreciated. Thanks,Viren
If native function expects reference, you can marshal it using it ref/out. So in your situation, you could use: out byte by. I've checked it, and it works for me. Edit again: It just came to my mind, that advices I gave you won't work, as FILE is a struct, that you won't be able to marshall from c# that easily. So scratch those, you can use this approach if you will threat SafeFileHandle as HANDLE object inside your unmanaged library. If you can't modify this dll, one solution is to create own wrapper for creating files using stdio, it could look like this: Create library that exposes functionality of fopen, fclose etc. Fe. (in c++): FILE* CreateFile(char* name); Marhall this function, in this example you would use (c#): public static extern IntPtr CreateMyFile([MarshalAs( UnmanagedType.LPStr)] string name); Marshall all FILE* parameters to IntPtr, and then just pass result of function CreateMyFile as FILE*.
1,212,859
1,213,909
Real time dynamic shadows to complement deferred shading?
I currently have a deferred rendering system setup and can render point lights and directional lights. My question is what are my options for different forms of shadowing which can make shadows based on point lights and directional lights which can maybe make use of a deferred shading setup?
There's not really anything special about deferred rendering that requires unique shadowing techniques. Most of the standard approaches to producing shadows work just fine with deferred rendering schemes. Shadow mapping is the most common shadowing algorithm in use today in real time applications like games. Stencil shadows were popular a few years ago but have fallen out of favour a bit due to various limitations. Shadow mapping works fine with deferred shading. The basic algorithm for shadow mapping is reasonably straightforward: Render depth to a render target texture from the point of view of the light (you need to render 6 faces of a cube map for a point light). When you perform the lighting pass for the light, for each pixel transform the world space position to the light's view space and compare the depth to the depth stored in the shadow map. If it is greater than the shadow map depth then the point is in shadow, otherwise light it normally. As usual with rendering, the devil is in the details. In order to get good quality shadows you need to set up your shadow map projection carefully to make best use of the pixels available in the shadow map (search for perspective shadow maps, cascaded shadow maps). Due to precision issues you will get various artifacts with self shadowing surfaces ('shadow acne' is the most common one) and there are various strategies to reduce the incidence of these artifacts (depth bias, projection matrix tweaks). In order to reduce the blocky, pixelated look of shadow maps with insufficient resolution you will probably want to perform some shadow map filtering. Percentage Closer Filtering is the standard approach and there are various ways to go about performing PCF. You also face the standard quality/performance tradeoff with shadows and dynamic shadowing tends to be one of the most expensive aspects of scene rendering. There are numerous tricks and techniques to attempt to maximize the performance of shadow mapping. Recently there have been a number of variations on the basic shadow mapping algorithm that attempt to give better looking results for a given shadow map resolution by approaching the filtering problem differently. Variance Shadow Maps and Exponential Shadow Maps are two recent techniques that have some nice benefits but some unique problems of their own. Nvidia's developer site is a good resource for graphics programming in general and has lots of articles on shadowing. Take a look at the HTML versions of the GPU Gems books available on the site as well, they have various articles on shadowing, including the definitive article on Variance Shadow Maps in GPU Gems 3.
1,212,874
1,215,348
mmap to overlay VME bus into user space memory over a PCI?
I'm trying to map a VME address space through a PCI bus into user space so I can perform regular read/writes on the memory. I have done this with another PCI device like this :- unsigned long *mapArea(unsigned int barAddr, unsigned int mapSize, int *fd) { unsigned long *mem; *fd = open("/dev/mem", O_RDWR); if ( *fd<0 ) { printf("Cannot open /dev/vme_mem\n"); exit(-1); } unsigned long *mem = (unsigned long*) mmap ( 0, mapSize, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, *fd, barAddr); if ( (mem == NULL) || (mem == (unsigned long*)-1) ) { printf ( "Cannot map memory, error is %s\n", strerror(errno) ); exit(-1); } return mem; } volatile unsigned long *bar = (volatile unsigned long *)mapArea(barAddr, mapSize, &fd); And then "bar" can be used normally for read/writes. So to VME, and with a Tundra Universe II PCI-VME Bridge chip :- Should I open "/dev/vme_m0" Where do I map my BAR from? the lspci -vv : "Region 1: Memory at 80020000" Also the addresses within the VME BUS are offset by 0x20000000, so how does that work wrt accessing/mapping it?! (Using Linux 2.6.18-128.el5 #1 SMP) (Need new tag "vme"!)
Where does /dev/vme_m0 come from and what does it represent? It is hard to tell what opening and accessing it will do without knowing more. You need to look at the bridge chip manual to figure out how a read/write to Region 1 will translate to a read/write on the VME bus. The bridge chip should have a set of registers that define PCI -> VME address translations. The VME address generated by accessing 0x80020000 would depend on the VME address specified in one of those registers.
1,212,978
1,213,058
In C++, if throw is an expression, what is its type?
I picked this up in one of my brief forays to reddit: http://www.smallshire.org.uk/sufficientlysmall/2009/07/31/in-c-throw-is-an-expression/ Basically, the author points out that in C++: throw "error" is an expression. This is actually fairly clearly spelt out in the C++ Standard, both in the main text and the grammar. However, what is not clear (to me at least) is what is the type of the expression? I guessed "void", but a bit of experimenting with g++ 4.4.0 and Comeau yielded this code: void f() { } struct S {}; int main() { int x = 1; const char * p1 = x == 1 ? "foo" : throw S(); // 1 const char * p2 = x == 1 ? "foo" : f(); // 2 } The compilers had no problem with //1 but barfed on //2 because the the types in the conditional operator are different. So the type of a throw expression does not seem to be void. So what is it? If you answer, please back up your statements with quotes from the Standard. This turned out not to be so much about the type of a throw expression as how the conditional operator deals with throw expressions - something I certainly didn't know about before today. Thanks to all who replied, but particularly to David Thornley.
According to the standard, 5.16 paragraph 2 first point, "The second or the third operand (but not both) is a throw-expression (15.1); the result is of the type of the other and is an rvalue." Therefore, the conditional operator doesn't care what type a throw-expression is, but will just use the other type. In fact, 15.1, paragraph 1 says explicitly "A throw-expression is of type void."
1,213,229
1,215,062
How to acquire an event only at defined times?
I have a QWidget which handles the mouseevent, i.e. it stores the mouseposition in a list when the left mouse button is pressed. The problem is, I cannot tell the widget to take only one point every x ms. What would be the usual way to get these samples? Edit: since the mouseevent is not called very often, is it possible to increase the rate?
It sounds like you don't want asynchronous event handling at all, you just want to get the location of the cursor at fixed intervals. Set up a timer to fire every x milliseconds. Connect it to a slot which gets the value of QCursor::pos(). Use QWidget::mapFromGlobal() if you need the cursor position in coordinates local to your widget. If you only want to do this while the left mouse button is held down, use mousePressEvent() and mouseReleaseEvent() to start/stop the timer.
1,213,265
1,213,285
How is heap and stack memories mananged, implemented, allocated
Possible Duplicates: How is heap and stack memories mananged, implemented, allocated? Stack,Static and Heap in C++ In C/C++ we can store variables, functions, member functions, instances of a class either on a stack or a heap. How is each implemented? How is it managed (high level)? Does gcc preallocates a chunk of memory to be used for the stack and heap, and then doles out on request? Is original memory coming from RAM? Can a function be allocated on the heap instead of a stack? --Clarification-- I am really asking about implementation and management of heap and stack memories. After reading referenced question, I didn't find anything that addresses that... thanks for the link
I think to your question one can easily write at least some chapters for the book on Operating Systems. I suggest you to read Tanenbaum: Modern Operating Systems. Main difference of heap and stack, that one is per process item, the other per thread item. Initially when program is started it gets some minimal heap and some stack segment. Heap is grown, stack is static (for each thread). If you write a recursive function which does not terminate (endless recursion) you will get stack overflow ;) Any function call has a stack frame on stack segment, when the function leaves, the stack is unwound and frame is free to be used by the next function. Stack is a continuous linear structure. On Linux you can configure the stack segment size for a process via an environment variable. On windows (at least with MS Visual C++) you can pass a linker flag with the size of stack segment. Stack overflows can also be produced when allocating at compile time some big array: char test[1000000]; Heap is a different story. When a process starts up heap size is some default value and can vary form OS to OS or configuration being used on that OS (e.g. on Windows it is 2MB by default, as far as I remember it). Further, if you need more heap, to allocate more space for variables etc. it will grow. If the program doesn't free heap memory it runs out of it (or heap space). There are different data structures for heap implementation some of them are binary tree derivatives, some are not e.g. Fibonacci Heap (forrest of trees). You can read some articles etc. on how to write a memory allocator. These data structures must be optimized for finding the heap node when an allocated chunk needs to be de-allocated, or appending (finding a free chunk) when new heap space is needed. Each process on a 32 bit OS has 4GB of virtual address space. As you can imagine there can't be so much RAM where all processes with their 4GBs of virtual address space fit. OS memory is organized in pages, which are swapped to HD when no longer needed or expired. This is where paging comes to play. Everything is mapped to pages: a process with the stack or the growing heap. Due to the structure of heap that it grows dynamically, it can be placed on multiple pages. This is why heap access can be very expensive, because if the page is not in memory a page fault happens and OS has to load a page from the disk (and that can be by magnitude slower). Stack frame of the thread being executed is in processor cache, which is much faster as RAM. Different heap types are possible, there might be heaps which are very fast for small objects or heaps which are very efficient in multi-threaded environments. Alexandrescu describes in "Modern C++ Design" how to develop small object allocator and a heap which manages small objects. This implementation is available in his Loki C++ library. Some embedded systems offer physically different memory regions, where different heap types can be implemented ontop. To write an own allocator (heap manager etc.) is a hard job if you want to beat a compiler. Regards, Ovanes
1,213,334
1,213,820
Boost.Intrusive and unordered_map
I am looking to use an intrusive unordered_map. For some reason there is only an unordered_set in the library. There is also an intrusive hashtable but I'm not sure it has the same functunality, also it doesn't have the same interface. Am I wrong and I missed the unordered_map link? If I am not is there a tutorial that will help me implement one?
It's an interesting question. Boost.Intrusive doesn't seem to provide any map interface, ordered or unordered. It has a lot of implementation types that will work fine as maps both ordered (red-black trees, AVL trees, splay trees) and unordered (hashtables). But no maps and I couldn't tell you why. You have two choices as I see it: Just use hashtable: the unordered containers are implemented as hashtables (and the only reason they aren't called hash_map is to avoid name collisions with pre-existing libraries using that name already). That will work if you want to get your work done. If you really want to implement your own, you want to take a look at the interface description for Boost.Intrusive's unordered_set. I have not looked at the implementation but it is almost certainly a wrapper around one or more of the tree types. std::set and std::map are both typically implemented as wrappers around a red-black tree (in all standard library implementations I've looked at: GCC's, MSVC's, and Apache's stdcxx). Also take at how libstdc++ wraps their tree implementation in <map> and in <set>. It's a lot of boilerplate, much of it tedious but both types defer almost all the work to the tree. Something analogous is almost certainly happening with Boost.Intrusive's unordered_set. You will need to look at the differences between the map and set interfaces, and use that as the basis for modifying unordered_set into unordered_map. I've done the latter. It's a bit on the tedious side, and I highly highly recommend writing unit tests for it (or stealing the ones that come with libstdc++ or Boost.Intrusive). But it's doable. I also highly recommend reading the requirements documents for sets and maps, either at SGI (set, map) or for libstdc++ Update: I realized why they aren't doing maps: the intrusive containers require that you embed the node information for the data structure in the value type you are storing in it. For maps you would have to do this for both the values and the keys. It's not that this isn't possible, but the standard implementation for a map uses the same internal type as the sets do. But those internal types only have one value_type variable: to store keys and values they copy the key and the value into that variable and store that in the nodes. To do that with an intrusive type (i.e. without copying) you'd have to modify that implementation type to be incompatible with sets: it has to store references to the keys and values separately. So to do it you also have to modify the implementation you use (probably hashtable). Again not impossible, but the library designers are likely trying to avoid serious code duplication so in the absence of simple way to implement this they have most likely decided to leave maps out. Does that make sense?
1,213,366
1,213,537
Can template polymorphism be used in place of OO polymorphism?
I am trying to get my head around applying template programming (and at some future point, template metaprogramming) to real-world scenarios. One problem I am finding is that C++ Templates and Polymorphism don't always play together the way I want. My question is if the way I'm trying to apply template programming is improper (and I should use plain old OOP) or if I'm still stuck in the OOP mindset. In this particular case, I am trying to solve a problem using the strategy-pattern. I keep running into the problem where I end up wanting something to behave polymorphically which templates don't seem to support. OOP Code using composition: class Interpolator { public: Interpolator(ICacheStrategy* const c, IDataSource* const d); Value GetValue(const double); } void main(...) { Interpolator* i; if(param==1) i = new Interpolator(new InMemoryStrategy(...), new TextFileDataSource(...)); else if(param==2) i = new Interpolator(new InMemoryStrategy(...), new OdbcDataSource(...)); else if(param==3) i = new Interpolator(new NoCachingStrategy(...), new RestDataSource(...)); while(run) { double input = WaitForRequest(); SendRequest( i->GetValue(input)); } } Potential Template Version: class Interpolator<class TCacheStrategy, class TDataSource> { public: Interpolator(); Value GetValue(const double); //may not be the best way but void ConfigCache(const& ConfigObject); //just to illustrate Cache/DS void ConfigDataSource(const& ConfigObject); //need to configured } //Possible way of doing main? void main(...) { if(param==1) DoIt(Interpolator<InMemoryStrategy,TextFileDataSource>(),c,d); else if(param==2) DoIt(Interpolator<InMemoryStrategy,OdbcDataSource>(),c,d) else if(param==3) DoIt(Interpolator<NoCachingStrategy,RestDataSource>(),c,d) } template<class T> void DoIt(const T& t, ConfigObject c, ConfigObject d) { t.ConfigCache(c); t.ConfigDataSource(c); while(run) { double input = WaitForRequest(); SendRequest( t.GetValue(input)); } } When I try to convert the OOP implementation to a template-based implementation, the Interpolator code can be translated without a lot of pain. Basically, replace the "interfaces" with Template type parameters, and add a mechanism to either pass in an instance of Strategy/DataSource or configuration parameters. But when I get down to the "main", it's not clear to me how that should be written to take advantage of templates in the style of template meta programming. I often want to use polymorphism, but it doesn't seem to play well with templates (at times, it feels like I need Java's type-erasure generics... ugh). When I often find I want to do is have something like TemplateType<?,?> x = new TemplateType<X,Y>() where x doesn't care what X,Y is. In fact, this is often my problem when using templates. Do I need to apply one more level of templates? Am I trying to use my shiny new power template wrench to install a OOP nail into a PCI slot? Or am I just thinking of this all wrong when it comes to template programming? [Edit] A few folks have pointed out this is not actually template metaprogramming so I've reworded the question slightly. Perhaps that's part of the problem--I have yet grok what TMP really is.
Templates provide static polymorphism: you specify a template parameter at compile time implementing the strategy. They don't provide dynamic polymorphism, where you supply an object at runtime with virtual member functions that implement the strategy. Your example template code will create three different classes, each of which contains all the Interpolator code, compiled using different template parameters and possibly inlining code from them. That probably isn't what you want from the POV of code size, although there's nothing categorically wrong with it. Supposing that you were optimising to avoid function call overhead, then it might be an improvement on dynamic polymorphism. More likely it's overkill. If you want to use the strategy pattern dynamically, then you don't need templates, just make virtual calls where relevant. You can't have a variable of type MyTemplate<?> (except appearing in another template before it's instantiated). MyTemplate<X> and MyTemplate<Y> are completely unrelated classes (even if X and Y are related), which perhaps just so happen to have similar functions if they're instantiated from the same template (which they needn't be - one might be a specialisation). Even if they are, if the template parameter is involved in the signatures of any of the member functions, then those functions aren't the same, they just have the same names. So from the POV of dynamic polymorphism, instances of the same template are in the same position as any two classes - they can only play if you give them a common base class with some virtual member functions. So, you could define a common base class: class InterpolatorInterface { public: virtual Value GetValue(const double) = 0; virtual void ConfigCache(const& ConfigObject) = 0; virtual void ConfigDataSource(const& ConfigObject) = 0; virtual ~InterpolatorInterface() {} }; Then: template <typename TCacheStrategy, typename TDataSource> class Interpolator: public InterpolatorInterface { ... }; Now you're using templates to create your different kinds of Interpolator according to what's known at compile time (so calls from the interpolator to the strategies are non-virtual), and you're using dynamic polymorphism to treat them the same even though you don't know until runtime which one you want (so calls from the client to the interpolator are virtual). You just have to remember that the two are pretty much completely independent techniques, and the decisions where to use each are pretty much unrelated. Btw, this isn't template meta-programming, it's just using templates. Edit. As for what TMP is, here's the canonical introductory example: #include <iostream> template<int N> struct Factorial { static const int value = N*Factorial<N-1>::value; }; template<> struct Factorial<0> { static const int value = 1; }; int main() { std::cout << "12! = " << Factorial<12>::value << "\n"; } Observe that 12! has been calculated by the compiler, and is a compile-time constant. This is exciting because it turns out that the C++ template system is a Turing-complete programming language, which the C preprocessor is not. Subject to resource limits, you can do arbitrary computations at compile time, avoiding runtime overhead in situations where you know the inputs at compile time. Templates can manipulate their template parameters like a functional language, and template parameters can be integers or types. Or functions, although those can't be "called" at compile time. Or other templates, although those can't be "returned" as static members of a struct.
1,213,418
1,213,440
Why won't C++ allow non-const to const conversion in copy ctor?
I have two getter members: Node* prev() { return prev_; } int value() { return value_ } Please note the lack of const identifiers (I forgot them, but now I want to know why this won't work). I am trying to get this to compile: Node(Node const& other) : prev_(other.prev()), value_(other.value()) { } The compiler rejects this. I thought that C++ allows non-const to const conversion in function parameters, such as: { Foo(int bar); } Foo(const int bar) { //lala } Why won't it let me do the same thing with a copy constructor? The const identifier means I promise not to change anything, so why would it matter if I get my value from a const or non-const source?
You're not trying to do a non-const to const conversion. You're attempting to call two methods which are not const an a const reference (calls to prev and value). This type of operation is strictly forbidden by const semantics. What you could do instead is use the fields prev_ and value_ directly. Because it's a member of the same type you can access privates which will be available on the const object.
1,213,607
1,213,624
How to manage large buffer in C++?
If I need a large buffer in my program written in C++, which one is better? Allocate the buffer in heap, and keep a reference to that buffer in the class that use it. Allocate a static buffer, and make it global.
How about: 3. Use a vector. [Edited to add: or boost::array is a good option if you're happy with the dependency]
1,213,768
1,213,818
Visual c++ redistributable redistribution
I'm coming from a Linux background, but I'd like to provide a version of my software on Windows. For users to run my program, they will need the Visual C++ redistributable. I would like to provide it for them as part of the package. My worry is that there, in the future, will be an SP2 of the Visual Studio 2008 Redistributable. If I provide them SP1, or ask them to install it themselves, will it clobber later versions of the dll's that may be required by future tools? Is there any instruction to give users to make sure they do not do this? I'd certainly not want to screw up someone's machine or other applications by giving them incorrect instructions. Aside from the redistributable exe, I was going to provide my tool as a zip file which they can extract into any directory they please, so I was not planning on providing an installer.
With VS 2008 the runtimes are manifested and will install side-by-side. So if your application is linked to SP1's runtime, it will run only with the SP1 runtime (unless a manifest explicitly indicates that the Sp1 version should be overridden). So you're protected from that type of DLL hell, in exchange for another (the user must have the SP1 redistributable installed).
1,214,099
1,214,262
Profile single function in gprof
Is it possible to use gprof to line-profile a single function in C++? Something like: gprof -l -F function_name ... , which does not seem to work.
That can be done easily with valgrind. It is a wonderful tool if you have the chance to use it in your development environment. It even have and graphical interface kcachegrind.
1,214,151
1,214,404
Can we take advantage of the type system to make programs more secure?
This question is inspired from Joel's "Making Wrong Code Look Wrong" http://www.joelonsoftware.com/articles/Wrong.html Sometimes you can use types to enforce semantics on objects beyond their interfaces. For example, the Java interface Serializable does not actually define methods, but the fact that an object implements Serializable says something about how it should be used. Can we have UnsafeString and SafeString interfaces/subclasses in, say Java, that are used in much of the same way as Joel's Hungarian notation and Java's Serializable so that it doesn't just look bad--it doesn't compile? Is this feasible in Java/C/C++ or are the type systems too weak or too dynamic? Also, beyond input sanitization, what other security functions can be implemented in this manner?
The type system already enforces a huge number of such safety features. That is essentially what it's for. For a very simple example, it prevents you from treating a float as an int. That's one aspect of safety -- it guarantees that the type you're working on are going to behave as expected. It guarantees that only string methods are called on a string. Assembly doesn't have that safeguard, for example. It's also the job of the type system to ensure that you don't call private functions on a class. That's another safety feature. Java's type system is too anemic to enforce a lot of interesting constraints effectively, but in many other languages (including C++), the type system can be used to enforce far more wide-ranging rules. In C++, template metaprogramming gives you a lot of tools for prohibiting "bad" code. For example: class myclass : boost::noncopyable { ... }; enforces at compile-time that the class can not be copied. The following will produce compile errors: myclass m; myclass m2(m); // copy construction isn't allowed myclass m3; m3 = m; // assignment also not allowed Likewise, we can ensure at compile-time that a template function only gets called on types which fulfill certain criteria (say, they must be random-access iterators, while bilinear ones aren't allowed, or they must be POD types, or they must not be any kind of integer type (char, short, int, long), but all other types should be legal. A textbook example of template metaprogramming in C++ implements a library for computing physical units. It allows you to multiply a value of type "meter" with another value of the same type, and automatically determines that the result must be of type "square meter". Or divide a value of type "mile" with a value of type "hour" and get a unit of type "miles per hour". Again, a safety feature that prevents you from getting your types mixed up and accidentally getting your units mixed up. You'll get a compile error if you compute a value and try to assign it to the wrong type. trying to divide, say, liters by meters^2 and assigning the result to a value of, say, kilograms, will result in a compile error. Most of this requires some manual work to set up, certainly, but the language gives you the tools you need to basically build the type-checks you want. Some of this could be better supported directly in the language, but the more creative checks would have to be implemented manually in any case.
1,214,796
1,214,856
Dev-C++ include file paths FLTK(Fast Light Toolkit)
When I compile and run programs in Bloodshed I save everything into a a folder labeled C++ in my username folder. When I downloaded FLTK, extracted it to the C++ folder, then tried to run a program using header files from FLTK, it was unable to find the files. My guess is that when the compiler looks for the header files it's only looking in the C++ folder, and the FLTK header files are embedded in folders that are inside of the C++ folder. I googled around for a way to somehow have file paths that include looks into when it looks for the specified header file, but I couldn't find anything. Does anyone with experience using Bloodshed know how to do this?
Most people here probably don't use DevC++, having been warned off it by people like me. DevC++ has lots of problems and is no longer being developed. You should consider switching to Code::Blocks, which is better in just about every way.
1,214,805
1,215,593
windows: load a filter driver while windows is running
Is it possible to install a keyboard filter driver(like ctrl2cap) while windows is running and not having to reboot? I tried it once with a driver loader but I got a BSOD. If it is possible what was I doing wrong? What can I do next time to not get a BSOD? Also, if it is possible, could I do it with c++? Thanks for the help!
The simple answer is you cannot dynamically load a filter driver. You need to specify a load order when you install the filter driver. I assume the filter driver is layered on top of kbdclass. As kbdclass is already loaded this is not possible.
1,214,876
1,214,910
guidelines on usage of size_t and offset_t?
This is probably a C++ 101 question: I'm curious what the guidelines are for using size_t and offset_t, e.g. what situations they are intended for, what situations they are not intended for, etc. I haven't done a lot of portable programming, so I have typically just used something like int or unsigned int for array sizes, indexes, and the like. However, I gather it's preferable to use some of these more standard typedefs when possible, so I'd like to know how to do that properly. As a follow-up question, for development on Windows using Visual Studio 2008, where should I look to find the actual typedefs? I've found size_t defined in a number of headers within the VS installation directory, so I'm not sure which of those I should use, and I can't find offset_t anywhere.
You are probably referring to off_t, not offset_t. off_t is a POSIX type, not a C type, and it is used to denote file offsets (allowing 64-bit file offsets even on 32-bit systems). C99 has superceded that with fpos_t. size_t is meant to count bytes or array elements. It matches the address space.
1,215,055
1,215,150
Why is the use of typedef in this template necessary?
When I compile this code in Visual Studio 2005: template <class T> class CFooVector : public std::vector<CFoo<T>> { public: void SetToFirst( typename std::vector<CFoo<T>>::iterator & iter ); }; template <class T> void CFooVector<T>::SetToFirst( typename std::vector<CFoo<T>>::iterator & iter ) { iter = begin(); } I get these errors: c:\home\code\scantest\stltest1\stltest1.cpp(33) : error C2244: 'CFooVector<T>::SetToFirst' : unable to match function definition to an existing declaration c:\home\code\scantest\stltest1\stltest1.cpp(26) : see declaration of 'CFooVector<T>::SetToFirst' definition 'void CFooVector<T>::SetToFirst(std::vector<CFoo<T>>::iterator &)' existing declarations 'void CFooVector<T>::SetToFirst(std::_Vector_iterator<_Ty,_Alloc::rebind<_Ty>::other> &)' If I add a typedef to the CFooVector template, I can get the code to compile and work: template <class T> class CFooVector : public std::vector<CFoo<T>> { public: typedef typename std::vector<CFoo<T>>::iterator FooVIter; void SetToFirst( FooVIter & iter ); }; template <class T> void CFooVector<T>::SetToFirst( FooVIter & iter ) { iter = begin(); } My question is, why does the typedef work when using the bare 'typename std::vector>::iterator' declaration did not work?
This compiles as well and reveals the source of VC++ confusion -- allocator type. Apparently outside of the class VS selects different default. Or maybe it can't recognize them to be the same. Compiles on VS2008 (as is) and VS2003 (with space between >>) template <class T> class CFoo { public: T m_t; }; template <class T> class CFooVector : public std::vector<CFoo<T>> { public: void SetToFirst(typename std::vector<CFoo<T>, typename CFooVector::_Alloc>::iterator & iter); }; template <class T> void CFooVector<T>::SetToFirst( typename std::vector<CFoo<T>, typename CFooVector::_Alloc>::iterator & iter ) { iter = begin(); } GCC 3.4 wanted this->begin() and space, but otherwise it can compile the code without explicit allocator type... Definitely looks like MS compiler not as smart as it should be...
1,215,186
1,215,204
Do the Qt database modules support remote databases through a network connection?
I'm profiling some APIs to see which one is suitable for this project. I want my Qt app to connect to a database over an internet connection. Can Qt do this with the client application alone or do I need to write a server app to sit on the database server and transact the queries?
You can perfectly well connect to databases over TCP/IP as long as the database engine supports that (most do!). See the example in the docs, it has a db.setHostName("acidalia"); to connect to a PostgreSQL database on that host...
1,215,402
1,215,441
Difference between event object and condition variable
What is the difference between event objects and condition variables? I am asking in context of WIN32 API.
Event objects are kernel-level objects. They can be shared across process boundaries, and are supported on all Windows OS versions. They can be used as their own standalone locks to shared resources, if desired. Since they are kernel objects, the OS has limitations on the number of available events that can be allocated at a time. Condition Variables are user-level objects. They cannot be shared across process boundaries, and are only supported on Vista/2008 and later. They do not act as their own locks, but require a separate lock to be associated with them, such as a critical section. Since they are user- objects, the number of available variables is limited by available memory. When a Conditional Variable is put to sleep, it automatically releases the specified lock object so another thread can acquire it. When the Conditional Variable wakes up, it automatically re-acquires the specified lock object again. In terms of functionality, think of a Conditional Variable as a logical combination of two objects working together - a keyed event and a lock object. When the Condition Variable is put to sleep, it resets the event, releases the lock, waits for the event to be signaled, and then re-acquires the lock. For instance, if you use a critical section as the lock object, SleepConditionalVariableCS() is similar to a sequence of calls to ResetEvent(), LeaveCriticalSection(), WaitForSingleObject(), and EnterCriticalSection(). Whereas if you use a SRWL as the lock, SleepConditionVariableSRW() is similar to a sequence of calls to ResetEvent(), ReleaseSRWLock...(), WaitForSingleObject(), and AcquireSRWLock...().
1,215,665
1,216,098
C version of C++ std::map
Is there a C library version of the C++ std::map in a standard library?
std::map is not a hash table. Therefore, my suggestion: Red-Black Tree C Code The following C files implement balanced binary trees using the red-black paradigm. I have written these functions in a very general manner so that the key can be anything at all. Each node of the balanced binary tree must contain a key and a pointer to info. The user defines what data-type the key is and provides a comparison function for the keys. The info can also be any kind of data type. (Disclaimer: haven't tried it myself.)
1,215,688
1,216,329
Read Something After a Word in C++
I'm building a simple interpreter of a language that i'm developing, but how i can do a cout of something that is after a word and in rounded by "", like this: #include <iostream> #include <fstream> #include <string> #include <cstdlib> using namespace std; int main( int argc, char* argv[] ) { if(argc != 2) { cout << "Error syntax is incorrect!\nSyntax: " << argv[ 0 ] << " <file>\n"; return 0; } ifstream file(argv[ 1 ]); if (!file.good()) { cout << "File " << argv[1] << " does not exist.\n"; return 0; } string linha; while(!file.eof()) { getline(file, linha); if(linha == "print") { cout << text after print; } } return 0; } And how i can remove the "" when printing the text. Here is the file example: print "Hello, World" Read my post in the middle of the answers! Thanks
I'm assuming what you want is to identify quoted strings in the file, and print them without the quotes. If so, the below snippet should do the trick. This goes in your while(!file.eof()) loop: string linha; while(!file.eof()) { getline(file, linha); string::size_type idx = linha.find("\""); //find the first quote on the line while ( idx != string::npos ) { string::size_type idx_end = linha.find("\"",idx+1); //end of quote string quotes; quotes.assign(linha,idx,idx_end-idx+1); // do not print the start and end " strings cout << "quotes:" << quotes.substr(1,quotes.length()-2) << endl; //check for another quote on the same line idx = linha.find("\"",idx_end+1); } }
1,215,777
1,215,781
Writing a graphical Z80 emulator in C or C++
I want to take an interest in writing my own simple emulator for the Z80 processor. I have no experience with this type of programming. I am mostly fine with using C-based languages as they are the ones I know best. What do I need to accomplish this and what are some good tutorials/references that could aid me in this project? I would also like a tutorial for coding a ROM-dumping application for my TI-84 Plus calculator so I can use its ROM with this emulator.
Perhaps start by looking at these: A good tutorial can be found here: Independent Z80 Assembly Guide Z80 DOCUMENTATION The Undocumented Z80 Documented v0.91 (pdf) The Complete Z80 Instruction Reference Z80 Microprocessor Instruction Set Summary
1,215,838
1,215,844
C++: Default values for template arguments other than the last ones?
I have my templated container class that looks like this: template< class KeyType, class ValueType, class KeyCompareFunctor = AnObnoxiouslyLongSequenceOfCharacters<KeyType>, class ValueCompareFunctor = AnObnoxiouslyLongSequenceOfCharacters<ValueType> > class MyClass { [...] } Which means that when I instantiate an object of this class, I can do it several different ways: MyClass<MyKeyType, MyValueType> myObject; MyClass<MyKeyType, MyValueType, MyCustomKeyCompareFunctor> myObject; MyClass<MyKeyType, MyValueType, MyCustomKeyCompareFunctor, MyCustomValueCompareFunctor> myObject; Those are all good. The problem comes when I want to instantiate a MyClass that uses a non-default version of the ValueCompareFunctor argument, but I still want to use the default value of the KeyCompareFunctor argument. Then I have to write this: MyClass<MyKeyType, MyValueType, AnObnoxiouslyLongSequenceOfCharacters<MyKeyType>, MyCustomValueCompareFunctor> myObject; It would be much more convenient if I could somehow omit the third argument and just write this: MyClass<KeyType, ValueType, MyCustomValueCompareFunctor> myObject; Since the MyCustomValueCompareFunctor works only on objects of type MyValueType and not on objects of type MyKeyType, it seems like the compiler could at least theoretically work out what I meant here. Is there a way to do this in C++?
In general, both in templates and functions or methods, C++ lets you use default for (and thereby omit) only trailing parameters -- no way out. I recommend a template or macro to shorten AnObnoxiouslyLongSequenceOfCharacters<MyKeyType> to Foo<MyKeyType> -- not perfect, but better than nothing.
1,216,194
1,216,250
How to Filter calls in NOKIA N73
I am am new to mobile app development. But i would like to know if this is possible to intercept incoming calls on my N73 using code like Java or C++? My second question is if this is possible then can we prevent the phone from ringing with a specified phone number from a black listed contact??? I've seen a lot of apps doing this task but i am interested in knowing if this is feasible & how this is accomplished. Thanks in Advance.
In C++ you can use CTelephony from etel3rdparty. Use NotifyChange() to subscribe to EVoiceLineStatusChange events. On an EStatusRinging event you can call GetCallInfo() to retrieve the remote party information, including phone number, and then decide whether to reject the call or let it keep ringing. As far as I know, the CTelephony API does not have a direct method of rejecting a call but you can achieve almost the same with AnswerIncomingCall() followed by HangUp(). Your executable will need the NetworkServices capability. A more hackish way to reject the call could be to use RWsSession to simulate pressing the red key (end key): call SimulateRawEvent() to send TRawEvent::EKeyDown and EKeyUp events on EStdKeyNo, with some delay between the events. In this case your executable will also need the SwEvent capability.
1,216,360
1,216,373
How to use the C++ Sockets Library
I'd like to do some network socket programming in C++ and have found the C++ Sockets library. First, is this a good way to go in C++? Normally in C, I'd use some of the stuff beej describes in his tutorial. Second, how do I compile the examples given on the site? I can't figure it out from their installation/configuration guide. So I download the tar.gz to my Linux box, then what? To have a specific example, how do I compile and run the DisplaySocket example? Thanks. EDIT: Thank you for the quick answers. A comment though. I'm not really looking into "understanding" network programming as I think I do that well enough already. I want to know if there's anything in particular to take advantage of in C++, and - if "the C++ Sockets Library" is a good choice - how to use it.
That's not "the" C++ sockets library, it's "a" C++ sockets library. Boost.asio has another (http://www.boost.org/doc/libs/1_39_0/doc/html/boost_asio.html). (Community Wiki since I can't actually help you with your question - I've never compiled the code you ask about, so I don't know at what point you might have tripped over a problem).
1,216,588
1,217,246
Invoking methods in QThread's context
In my application there's the main thread and a worker thread (QThread). From the main thread I'd like to invoke a method of my worker thread and have it run in the thread's context. I've tried using QMetaObject::invokeMethod and give it the QueuedConnection option but it's not working. I've also tried emitting signals from the main thread (which is connected to the worker thread's slot) but that also failed. Here's a snippet of roughly what I tried: class Worker : public QThread { Q_OBJECT public: Worker() { } void run() { qDebug() << "new thread id " << QThread::currentThreadId(); exec(); } public slots: void doWork() { qDebug() << "executing thread id - " << QThread::currentThreadId(); } }; Using the QMetaObject way: int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qDebug() << "main thread id - " << QThread::currentThreadId(); Worker worker; worker.start(); QMetaObject::invokeMethod(&worker, "doWork", Qt::QueuedConnection); return a.exec(); } Using the signal way: class Dummy : public QObject { Q_OBJECT public: Dummy() { } public slots: void askWork() { emit work(); } signals: void work(); }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qDebug() << "main thread id - " << QThread::currentThreadId(); Worker worker; worker.start(); Dummy dummy; QObject::connect(&dummy, SIGNAL(work()), &worker, SLOT(doWork()), Qt::QueuedConnection); QTimer::singleShot(1000, &dummy, SLOT(askWork())); return a.exec(); } Both ways result in the main thread id being printed in the QThread doWork. Also, I thought of implementing a simple producer-consumer but if this works, is there any reason why not to do it this way?
The problem was that the receiver (the QThread) 'lives' in the main thread and thus the main thread's event loop is the one that executes the slot. from Qt's docs: With queued connections, the slot is invoked when control returns to the event loop of the thread to which the object belongs. The slot is executed in the thread where the receiver object lives. So the solution I found so far was to create an object inside the thread's run() and use its slots instead. That way the receiver's owner is the thread and then the slot is called in the threads context.
1,216,750
1,216,758
How can I simulate interfaces in C++?
Since C++ lacks the interface feature of Java and C#, what is the preferred way to simulate interfaces in C++ classes? My guess would be multiple inheritance of abstract classes. What are the implications in terms of memory overhead/performance? Are there any naming conventions for such simulated interfaces, such as SerializableInterface?
Since C++ has multiple inheritance unlike C# and Java, yes you can make a series of abstract classes. As for convention, it is up to you; however, I like to precede the class names with an I. class IStringNotifier { public: virtual void sendMessage(std::string &strMessage) = 0; virtual ~IStringNotifier() { } }; The performance is nothing to worry about in terms of comparison between C# and Java. Basically you will just have the overhead of having a lookup table for your functions or a vtable just like any sort of inheritance with virtual methods would have given.
1,217,056
1,217,085
C++ main() in a large OOP project
This may be a short & simple question, but I've never found a satisfying answer to it: What code does the main() function usually consist of in a large C++ project? Would it be an incorrect assumption to think that it is usually just initializing a (wrapping) class object and calling a function inside of it to set things off? Why is main() not a method in the first place? Is it to preserve backwards-compatibility with C?
In my code, it's basically a constructor call, possibly a method call, and some exception handling. This is the main for own of my projects (headers and comments omitted, and formatting messed up by SO, as usual): int main( int argc, char * argv[] ) { int result = 0; try { CLIHandler ch( argc, argv ); result = ch.ExecCommand(); } catch( const Exception & ex ) { result = ExceptionHandler::HandleMyError( ex ); } catch( const std::exception & ex ) { result = ExceptionHandler::HandleOtherError( ex ); } catch( ... ) { result = ExceptionHandler::HandleUnknownError(); } return result; }
1,217,173
1,217,177
How to have a char pointer as an out parameter for C++ function
I'm a newbie to C++. I'm trying to have a char pointer as an out parameter for a function. But the changes made in the function are not reflected in the main function. What am I doing wrong? void SetName( char *pszStr ) { char* pTemp = new char[10]; strcpy(pTemp,"Mark"); pszStr = pTemp; } int _tmain(int argc, _TCHAR* argv[]) { char* pszName = NULL; SetName( pszName ); cout<<"Name - "<<*pszName<<endl; delete pszName; return 0; }
Your pointer is being copied onto the stack, and you're assigning the stack pointer. You need to pass a pointer-to-pointer if you want to change the pointer: void SetName( char **pszStr ) { char* pTemp = new char[10]; strcpy(pTemp,"Mark"); *pszStr = pTemp; // assign the address of the pointer to this char pointer } int _tmain(int argc, _TCHAR* argv[]) { char* pszName = NULL; SetName( &pszName ); // pass the address of this pointer so it can change cout<<"Name - "<<*pszName<<endl; delete pszName; return 0; } That will solve your problem. However, there are other problems here. Firstly, you are dereferencing your pointer before you print. This is incorrect, your pointer is a pointer to an array of characters, so you want to print out the entire array: cout<<"Name - "<<pszName<<endl; What you have now will just print the first character. Also, you need to use delete [] to delete an array: delete [] pszName; Bigger problems, though, are in your design. That code is C, not C++, and even then it's not standard. Firstly, the function you're looking for is main: int main( int argc, char * argv[] ) Secondly, you should use references instead of pointers: void SetName(char *& pszStr ) { char* pTemp = new char[10]; strcpy(pTemp,"Mark"); pszStr = pTemp; // this works because pxzStr *is* the pointer in main } int main( int argc, char * argv[] ) { char* pszName = NULL; SetName( pszName ); // pass the pointer into the function, using a reference cout<<"Name - "<<pszName<<endl; delete pszName; return 0; } Aside from that, it's usually better to just return things if you can: char *SetName(void) { char* pTemp = new char[10]; strcpy(pTemp,"Mark"); return pTemp; } int main( int argc, char * argv[] ) { char* pszName = NULL; pszName = SetName(); // assign the pointer cout<<"Name - "<<pszName<<endl; delete pszName; return 0; } There is something that makes this all better. C++ has a string class: std::string SetName(void) { return "Mark"; } int main( int argc, char * argv[] ) { std::string name; name = SetName(); // assign the pointer cout<<"Name - "<< name<<endl; // no need to manually delete return 0; } If course this can all be simplified, if you want: #include <iostream> #include <string> std::string get_name(void) { return "Mark"; } int main(void) { std::cout << "Name - " << get_name() << std::endl; } You should work on your formatting to make things more readable. Spaces inbetween your operators helps: cout<<"Name - "<<pszName<<endl; cout << "Name - " << pszName << endl; Just like spaces in between English words helps, sodoesspacesbetweenyouroperators. :)
1,217,196
1,217,202
c++ memory allocation question
im trying to create an array: int HR[32487834]; doesn't this only take up about 128 - 130 megabytes of memory? im using MS c++ visual studios 2005 SP1 and it crashes and tells me stack overflow.
While your computer may have gigabytes of memory, the stack does not (by default, I think it is ~1 MB on windows, but you can make it larger). Try allocating it on the heap with new [].
1,217,236
1,217,293
C++ Fast way to convert between image formats
Ive got some in memory images in various simple formats, which I need to quickly convert to another format. In cases where the target format contains an alpha channel but the source does not, alpha should be taken as its full value (eg 0xFF for an 8bit target alpha channel). I need to be able to deal with various formats, such as A8R8G8B8, R8G8B8A8, A1R4G4B4, R5G6B5, etc. Conversion of pixels between any of these formats is simple, however I don't want to have to manually code every single combination, I also don't want to have a 2 pass solution of converting to a common format (eg A8R8G8B8) before converting again to the final format both for performance reasons, and that if I want to use a higher definition format, say A16B16G16R16 or a floating point I'd either loose some data converting to the intermediate format, or have to rewrite everything to use a different higher definition format... Ideally id like some sort of enum with values for each format, and then a single method to convert, eg say enum ImageFormat { FMT_A8R8G8B8,//32bit FMT_A1R4G4B4,//16bit FMT_R5G6B5,//16bit FMT_A32R32G32B32F,//128bit floating point format ... }; struct Image { ImageFormat Format; size_t Width, Height; size_t Pitch; void *Data; }; Image *ConvertImage(ImageFormat *targetFormat, const Image *sourceImage);
You might want boost::gil.
1,217,302
1,217,320
Which is more secure OFB or CFB?
I'm working a small project, using AES encryption and wanted to use it in streaming mode, which is considered a more "suitable" mode for socket usage? OFB or CFB? I've been reading about it and can't really decide, so any ideas are highly appreciated. I'll be using OpenSSL/C++.
Both OFB and CFB are solid if unexciting cipher modes (compared with, say, 'Infinite Garble Extension', IGE, which at least sounds more exciting) - either will serve you well. Choose one and stick with it. And, if Bruce Schneier's blog is correct, use AES-128 (rather than either AES-192 or AES-256).
1,217,471
1,217,502
Using libxml2 in Visual Studio 2008 and Windows XP
I have a weird problem when running an application that uses GNOME's libxml2 under Visual Studio 2008 (VS2008-SP1) and Windows XP. I have two C++ projects: Project A (a library) Project B (an application that depends on Project A) Both under one VS solution. Project A is statically compiled with libxml2.lib. I've added dependencies to the library in both projects A and B. Solution compiles perfectly. The only thing is, when I run it, I am getting the following error under Windows XP: "This application has failed to start because libxml2.dll was not found. Re-installing the application may fix this problem". I have tried this in two different Windows XP SP3 installations. And the weirdest thing is that it runs perfectly fine on Windows Vista, and I don't think it should be looking for DLL since it's statically compiled. Right? Any ideas?
Considering that libxml2 is Gnome based project, I'm guessing it doesn't come by default on any Windows installation. I'm betting the reason it works on Vista is that you have a different program installed on Vista which happens to include that library. Hence it works there by accident and not design. I agree with Richie. The best way to tackle this problem is to get out DependencyWalker and see what dependency is failing on XP but not Vista. This will lead you to your problem.
1,217,575
1,217,669
Undefined Reference to class function issue
I've scoured the internet and my own intellect to answer this basic question, however, much to my own dismay I've been unable to find a solution. I'm normally pretty good about multiple header files however I have hit a wall. The problem is a function that I've declared in a header and defined in its proper namespace in the source file. I'm developing on windows using Bloodshed. /////////////////////////////// // class Matrix4x3.h /////////////////////////////// #ifndef _MATRIX4X3_H #define _MATRIX4X3_H class Matrix4x3{ public: //set to identity void identity(); }; #endif /////////////////////////////// // class Matrix4x3.cpp /////////////////////////////// #include <assert.h> #include <math.h> #include "Matrix4x3.h" . . . void Matrix4x3::identity(){ //calculations here... } ////////////// Main //////////////// #include <cstdlib> #include <iostream> #include "../Matrix4x3.h" using namespace std; int main(int argc, char *argv[]) { Matrix4x3 a; a.identity(); cin.get(); return EXIT_SUCCESS; } I use Bloodshed, and it displays a list of class members and methods when I use the constructed object, however it tells me that the method dipicted above hasn't been referenced come time to compile. If anyone has a response I would be very appreciative.
If you compile using the IDE, look for some button like "add file to project" or something like this, to add the Matrix4x3.cpp file to your project, so that when you build it, the IDE will put the translated result to the linker and all functions are resolved. Currently, it looks like you don't tell the IDE about that cpp file, and so that function definition is never considered.
1,217,603
1,218,503
I can't understand the usage of the normal class libraries of the Java
I'm a beginner at Java Programming. I have the experience that I used DX library for before in C++. The DX library worked with simple functions, but the library of the JAVA does not work with functions. How can I understand Java Class libraries?
Not functions, but methods of Objects. That's a big difference, and the key to OO. Simple example: String x = new String("abcdef"); String y = x.substring(2); Note the idea you start by getting a reference to an object of a particular type, here x is a String. You then can ask x to do lots of different things, such extract substrings. The full set of what you can do is documented in the String class. So a way to approach things is to say What type of object do I need? A touch of googling tends to help here. How do I create it - sometimes it's just new Class(), sometimes another class makes them for you. The class documentation typically tells you how. Now what can I do with it? Read the method documentation. As has been pointed out, the online tutorials will help. Take the time to work through some. IDEs (Ecplise is free for example) will give you "help" offering menus of availble methods when you have an object. Very often for each new thing you want to do there are useful code snippets.
1,217,777
1,217,784
Convert LPCOLESTR to BSTR?
Any ideas on how to make a BSTR out of an LPCOLESTR? Silly thing to get hung up on..
An LPCOLESTR is just a const wchar_t*, so you can use SysAllocString() to create a BSTR: LPCOLESTR olestr = ...; BSTR bstr = SysAllocString(olestr); Be sure to call SysFreeString() when you're done with your BSTR. See also the MSDN documentation on BSTRs
1,217,796
1,218,056
Does a "pure" IDispatch interface require a proxy/stub DLL?
..for an out-of-process-server, or can I call a dispatch interface without registering a proxy/stub? The interface in question is very high level, so performance is a non-issue, and I could make the whole thing registration-free, which is a big plus
I'm pretty sure you don't need to provide a custom proxy/stub dll if you limit your interface(s) to automation-compatible types. In that case, the system can use the automation marshaler and doesn't need any additional help. I believe the automation-compatible types are the types that can fit into a VARIANT, e.g. simple POD types, BSTRs, and the like. I found this KB article which has some discussion of the automation marshaler, although it's not specifically targeted at your question. It does list the compatible types, at the very least. It also mentions that you need to specifically identify the automation marshaler in the registration for your component, but in my experience this isn't necessary - your mileage may vary. Lastly, you may need to implement IProvideClassInfo as well; I usually use the implementation provided by ATL.
1,217,923
1,217,931
interrupt program in debugger when c++ exception is thrown
How can I make gdb interrupt (like in breakpoint) the program at the point where an exception is thrown, and interrupt again on rethrows and beginnings of the relevant catch blocks?
Try catch throw and catch catch.
1,218,014
1,218,594
Provide program arguments when debugging with Code::Blocks
I cant seem to work out how to add program arguments to the launch command for the codeblocks debugger. Any one know how to do this?
I found it. Project --> Set programs arguments (i was looking all over project settings like visual studio has it)
1,218,133
1,218,145
Parsing XML Encoded in UTF-8
I am working with a Wikipedia XML dump that is encoded in UTF-8. Right now, I am reading in everything as std::string, so when I std::cout to the screen, foreign characters are displayed as jibberish. The actual parsing process only looks for ASCII characters though, but when I write the parsed file to disk, I want to preserve the foreign characters. In other words, I want the output to have the same encoding as the input. Is it OK to use std::string, or am I going to have to use something like ICU? The libraries I have looked at seem overly complicated. Is there something quick I can use to do this?
UTF-8 is the default encoding for XML documents. Just write it to your file. There is no point in converting it to Unicode and back again. If it is accidentally dumped to your screen, avert your gaze :-) Removing ASCII characters like '{' will not cause a problem. UTF-8 is designed so that no byte in a multi-byte character is in the range 0-127 and thus can't be confused with an ASCII character.
1,218,355
1,218,361
How to convert Win32 HRESULT to int return value?
I'm writing a Windows console application in C++ and would like to return zero on success and a meaningful error code on failure (i.e., S_OK should return 0, and E_OUTOFMEMORY should return a different return value than E_FAIL and so on). Is the following an okay approach?: int wmain(int argc, wchar_t *argv[]) { HRESULT hr = DoSomething(); return (int) hr; } Or is there a better way? Maybe a standard Win32 API function or macro that I'm forgetting or failing to find?
HRESULT is just a 32-bit integer, with each code being a different value, so what you are doing is what you want.
1,218,648
1,218,685
"Ch++" or "ch+1" in C++?
While reading "C++ Primer Plus 5th edition", I saw this piece of code: cin.get(ch); ++ch; cout << ch; So, this will lead to display the following character after ch. But, If I did it that way: cin.get(ch); cout << ch+1; Now, cout will think ch is an int(try typecasting). So, why cout does so? And why if I added 1 to a char it will produce a number?. And why there's a difference between: ch++, and ch + 1.
The reason this occurs is the type of the literal 1 is int. When you add an int and a char you get an int, but when you increment a char, it remains a char. Try this: #include <iostream> void print_type(char) { std::cout << "char\n"; } void print_type(int) { std::cout << "int\n"; } void print_type(long) { std::cout << "long\n"; } int main() { char c = 1; int i = 1; long l = 1; print_type(c); // prints "char" print_type(i); // prints "int" print_type(l); // prints "long" print_type(c+i); // prints "int" print_type(l+i); // prints "long" print_type(c+l); // prints "long" print_type(c++); // prints "char" return 0; }
1,218,699
1,218,709
Error when passing an object by reference
So I have a problem.... I've a method void MainWindow::loadItems(const ArticleStore& store) { } that I try to call like this inside the MainWindow class ArticleStore store(); loadItems(store) And I get this error mainwindow.cpp:15: error: no matching function for call to ‘MainWindow::loadItems(ArticleStore (&)())’ mainwindow.h:19: note: candidates are: void MainWindow::loadItems(const ArticleStore&) ArticleStore definition: class ArticleStore { public: ArticleStore(); }; So the question is what went wrong?
It's because ArticleStore store(); is interpreted by the compiler as a function declaration. That's explain why compiler is looking for ‘MainWindow::loadItems(ArticleStore (&)())’ You must write instead: Article store; // With no parenthesis
1,218,800
1,218,967
Eclipse CDT 5.x and cmake 2.6.x
According to what I see, cmake 2.6.x supports CDT 4.x. We already have CDT 6.x. Is CDT 5.x and cmake 2.6.x are compatible at least? Thanks Dima
Yes, it is. The eclipse CDT 4.x project generated by cmake is compatible with next versions. I use them everyday, and work like a charm: cmake: version 2.6-patch 2 (Ubuntu 8.10) eclipse: version 3.4.1 CDT: version 5.0.1 I have also tried to import those projects with CDT 6 and all it keep working. Would be really bad if you were not be able to reuse projects from old versions. Backward compatibility is really important for serious applications.
1,218,807
1,218,854
Counting the total of same running processes in C++
I'm looking for a way to detect the # of running processes that has same process name. In example, I ran notepad three times. notepad.exe notepad.exe notepad.exe So it will return 3. I currently have these code to detect a running process, but not counting its running process quantity. #include <iostream> #include <windows.h> #include <tlhelp32.h> #include <tchar.h> bool IsProcessRunning(const char *ProcessName); int main() { char *notepadRunning = (IsProcessRunning("notepad.exe")) ? "Yes" : "No"; std::cout << "Is Notepad running? " << notepadRunning; return 0; } bool IsProcessRunning(const char *ProcessName) { PROCESSENTRY32 pe32 = { sizeof(PROCESSENTRY32) }; HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(Process32First(hSnapshot, &pe32)) { do { if(_tcsicmp(pe32.szExeFile, ProcessName) == 0) { CloseHandle(hSnapshot); return true; } } while(Process32Next(hSnapshot, &pe32)); } CloseHandle(hSnapshot); return false; } Any kind of help would be appreciated :) Thanks.
You are using the correct API, namely CreateToolhelp32Snapshot, Process32First and Process32Next. And as you are doing, you should be using the szExeFile member from the struct PROCESSENTRY32. You are returning from your function when you find a match currently though. Instead you should be incrementing a counter and NOT returning. And return an int with the process count instead of a bool. Also be sure not to do CloseHandle(hSnapshot); until the end of the function after you have the count. Also make sure to first acquire the privilege SeDebugPrivilege before enumerating, that way you will get all processes across all sessions and users. To acquire the privilege so you get all sessions: acquirePrivilegeByName(SE_DEBUG_NAME);// SeDebugPrivilege Where acquirePrivilegeByName is defined as: BOOL acquirePrivilegeByName( const TCHAR *szPrivilegeName) { HANDLE htoken; TOKEN_PRIVILEGES tkp; DWORD dwerr; //---------------- adjust process token privileges to grant privilege if (szPrivilegeName == NULL) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } if (!LookupPrivilegeValue(NULL, szPrivilegeName, &(tkp.Privileges[0].Luid))) return FALSE; tkp.PrivilegeCount = 1; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &htoken)) return FALSE; if (!AdjustTokenPrivileges(htoken, FALSE, &tkp, 0, NULL, NULL) || GetLastError() != ERROR_SUCCESS) // may equal ERROR_NOT_ALL_ASSIGNED { dwerr = GetLastError(); CloseHandle(htoken); SetLastError(dwerr); return FALSE; } CloseHandle(htoken); SetLastError(ERROR_SUCCESS); return TRUE; } //acquirePrivilegeByName()
1,218,876
1,218,878
Problem with using OpenGL's VBO
I just tried to render the first redbook example ( the white Quad ) by using VBOs. It works fine with immediate mode and vertex arrays. But when using VBOs the screen stays black. I think i must have missed something important. init: unsigned int bufIds[2]; glGenBuffers( 2, bufIds ); GLfloat vertices[] = { 0.25, 0.25, 0.0, 0.75, 0.25, 0.0, 0.75, 0.75, 0.0, 0.25, 0.75, 0.0 }; glBindBuffer( GL_ARRAY_BUFFER, bufIds[0] ); glBufferData( GL_ARRAY_BUFFER, 12, vertices, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glClearColor( 0, 0, 0, 1 ); glColor3f( 1, 1, 1 ); glOrtho( 0.0, 1.0, 0.0, 1.0, -1.0, 1.0 ); renderloop for VBO (not working): glClear( GL_COLOR_BUFFER_BIT ); glEnableClientState( GL_VERTEX_ARRAY ); glBindBuffer( GL_ARRAY_BUFFER, bufIds[0] ); glVertexPointer( 3, GL_FLOAT, 0, 0 ); glDrawArrays( GL_QUADS, 0, 12 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glDisableClientState( GL_VERTEX_ARRAY ); renderloop for vertex arrays (working): glClear( GL_COLOR_BUFFER_BIT ); glEnableClientState( GL_VERTEX_ARRAY ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glVertexPointer( 3, GL_FLOAT, 0, vertices ); glDrawArrays( GL_QUADS, 0, 12 ); glDisableClientState( GL_VERTEX_ARRAY );
argh i just figured it out by trying to read back the contents of the buffer: i need to allocate the buffer with 12 * sizeof( GLfloat ) instead of only 12 glBufferData( GL_ARRAY_BUFFER, 12 * sizeof( GLfloat ), vertices, GL_STATIC_DRAW ); my read back code GLfloat vertices2[12]; glBindBuffer( GL_ARRAY_BUFFER, bufIds[0] ); glGetBufferSubData ( GL_ARRAY_BUFFER, 0, 12 * sizeof( GLfloat ), vertices2 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); for ( int i = 0; i < 4; i ++ ) { LOG_DEBUG << "point " << i << ": " << vertices2[ i * 3 + 0 ] << " / " << vertices2[ i * 3 + 1 ] << " / " << vertices2[ i * 3 + 2 ]; }
1,218,914
2,352,136
Eclipse C++ compilation warning problem
Here a code to demonstrate an annoying problem: class A { public: A(): m_b(1), m_a(2) {} private: int m_a; int m_b; }; This is an output on Console view: make all Building file: ../test.cpp Invoking: GCC C++ Compiler g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"test.d" -MT"test.d" -o"test.o" "../test.cpp" ../test.cpp: In constructor 'A::A()': ../test.cpp:9: warning: 'A::m_b' will be initialized after ../test.cpp:8: warning: 'int A::m_a' ../test.cpp:3: warning: when initialized here Finished building: ../test.cpp The problem is that in Problems view I'll see 3 separate warnings (lines in output containing warning word), while indeed there're 4 lines in output describing a one problem. Is there're something I'm missing? Additional question. Maybe it's in Eclipse spirit, but is there a way to make Console view clickable as most IDE does (e.g. Visual Studio, emacs ...) Thanks Dima
According to the last comment on this bug report you should be able to click on the console view to jump to code in CDT 7.0. It might be worth checking out the milestone builds to see if the grouping of error messages is better. If not raising a bug to attempt to group related messages would be a good idea.
1,218,947
1,218,960
Convert a String in C++ Code
I'm learning C++ and developing a project to practice, but now i want to turn a variable(String) in code, like this, the user have a file that contains C++ code, but i want that my program reads that file and insert it into the code, like this: #include <iostream> #include <fstream> #include <string> #include <cstdlib> using namespace std; int main( int argc, char* argv[] ) { ifstream file(argv[ 1 ]); if (!file.good()) { cout << "File " << argv[1] << " does not exist.\n"; return 0; } string linha; while (!file.eof()) { getline(file, linha); if (linha.find("code") != string::npos) { size_t idx = linha.find("\""); //find the first quote on the line while ( idx != string::npos ) { size_t idx_end = linha.find("\"",idx+1); //end of quote string quotes; quotes.assign(linha,idx,idx_end-idx+1); // do not print the start and end " strings cout << quotes.substr(1,quotes.length()-2) << endl; //check for another quote on the same line idx = linha.find("\"",idx_end+1); } } } return 0; } And here is a file exmaple: code "time_t seconds;\n seconds = time (NULL);\n cout << seconds/3600;" But when i run the program it don't covert the string into code, but it prints exactly what is in the quotes. Thanks!
You're doing cout right? So obviously it gets displayed. Maybe what you are trying to do is some code injection in a running process like this http://www.codeproject.com/KB/DLL/code_injection.aspx
1,219,005
1,219,022
const pointers in STL containers
Hello fellow C++ programmers. I have, what I hope to be, a quick question about STL containers: std::list<std::string> l; This statement compiles fine when used in some C++ sourcefile (with the appropriate includes). But std::list<const std::string> m; or std::list<std::string * const> n; fails to compile when using gcc (gcc version 4.0.1 (Apple Inc. build 5484)). However, using the Visual Studio 2008 C++ compiler, no complaints arise. A little research unearths that elements in STL containers have to be Assignable. Is there a STL bug in the VC implementation (I'd say: 'unlikely') or do they use another concept of Assignable?
Technically, container elements do have to be assignable, however in std::list, list nodes are very rarely moved around, so once constructed they don't need to be copied (OK) or assigned (would cause an error). Unless a compiler goes out of its way to test assignability, it's likely that instantiating many list operations won't actually cause a compile error, even if it's not technically legal.
1,219,007
1,219,014
C++ Template Metaprogramming - Is it possible to output the generated code?
I would like to debug some templated code to understand it better. Unfortunately I'm new to template metaprogramming and it IS hard for me to get in. When I try to output the preprocessed source files I get 125 000 lines of code :/ So is there a way I can see the generated Code? (The library I'm using is SeqAn)
No it isn't. The preprocessor has nothing to do with template processing, which is performed by the compiler. Templates do not generate C++ code, any more than a function call does - they are an integral part of the C++ language itself.
1,219,112
1,219,184
C++ Getting the size of a type in a macro conditional
Is there some way to do something like this in c++, it seems sizeof cant be used there for some reason? #if sizeof(wchar_t) != 2 #error "wchar_t is expected to be a 16 bit type." #endif
I think things like BOOST_STATIC_ASSERT could help.
1,219,607
1,219,618
Why do we need a pure virtual destructor in C++?
I understand the need for a virtual destructor. But why do we need a pure virtual destructor? In one of the C++ articles, the author has mentioned that we use pure virtual destructor when we want to make a class abstract. But we can make a class abstract by making any of the member functions as pure virtual. So my questions are When do we really make a destructor pure virtual? Can anybody give a good real time example? When we are creating abstract classes is it a good practice to make the destructor also pure virtual? If yes..then why?
Probably the real reason that pure virtual destructors are allowed is that to prohibit them would mean adding another rule to the language and there's no need for this rule since no ill-effects can come from allowing a pure virtual destructor. Nope, plain old virtual is enough. If you create an object with default implementations for its virtual methods and want to make it abstract without forcing anyone to override any specific method, you can make the destructor pure virtual. I don't see much point in it but it's possible. Note that since the compiler will generate an implicit destructor for derived classes, if the class's author does not do so, any derived classes will not be abstract. Therefore having the pure virtual destructor in the base class will not make any difference for the derived classes. It will only make the base class abstract (thanks for @kappa's comment). One may also assume that every deriving class would probably need to have specific clean-up code and use the pure virtual destructor as a reminder to write one but this seems contrived (and unenforced). Note: The destructor is the only method that even if it is pure virtual has to have an implementation in order to instantiate derived classes (yes pure virtual functions can have implementations). struct foo { virtual void bar() = 0; }; void foo::bar() { /* default implementation */ } class foof : public foo { void bar() { foo::bar(); } // have to explicitly call default implementation. };
1,219,693
1,219,707
Can a C++ dll compiled using Visual Studio 2008 be used with Visual Studio 2005?
I'm going to be working with a C++ library written in plain C++ (not .NET and without MFC). The library is available compiled using both Visual Studio 2005 / Intel Fortran 9.1 and VS 2008 / Intel Fortran 10.1. Obviously I'm going to grab the binaries for VS 2008 since that's the environment on my computer but I'm curious if there are reasons why a straight C++ library wouldn't be compatible between VS 2005 and 2008. I'd assume that the name-mangling would be the same but maybe there are other reasons. I haven't used C++ in a long time so I'm a little rusty when it comes to these things.
The biggest issue you will run into is the usage of the CRT. If the CRT (C RunTime) is statically linked into the DLL, you shouldn't have any issues. However if the CRT is dynamically linked into the project you may run into trouble. Visual Studio 2005 and 2008 use different versions of the CRT and they cannot easily be loaded togeter. But if one or both of the DLL's statically links the CRT you should be in decent shape.
1,219,821
1,219,832
Syntax error in resource file. I don't understand
I have a .rc file: #include "MainWindowResource.h" MAINWINDOW_MENU MENU DISCARDABLE BEGIN POPUP "&File" BEGIN MENUITEM "&New\tCtrl+N", MAINWINDOW_MENU_FILE_NEW MENUITEM "&Open\tCtrl+O", MAINWINDOW_MENU_FILE_OPEN MENUITEM "&Save\tCtrl+S", MAINWINDOW_MENU_FILE_SAVE MENUITEM "&Save As\tCtrl+Shift+S", MAINWINDOW_MENU_FILE_SAVEAS MENUITEM SEPARATOR MENUITEM "&Print\tCtrl+P", MAINWINDOW_MENU_FILE_PRINT MENUITEM "Print Pre&view\tCtrl+Shift+P", MAINWINDOW_MENU_FILE_PRINTPREVIEW MENUITEM SEPARATOR MENUITEM "E&xit\tAlt+F4", MAINWINDOW_MENU_FILE_EXIT END POPUP "&Edit" POPUP "&View" POPUP "&Tools" POPUP "&Help" END Now my compiler (MinGW) says this: C:\DOCUME~1\RADEKS~1\BUREAU~1\C__~1\LIQUID~1\MAINWI~1.RC|23|syntax error| ||=== Build finished: 1 errors, 0 warnings ===| Line 23 is this line: POPUP "&View" I don't understand what's wrong with my code. Can anyone help me plz? Thanks.
What is MAINWINDOW_FILE_EXIT defined to be? You might find it has some bogus text as part of its definition, or a missing quote if it's a string. Edit: You probably need BEGIN and END even for an empty POPUP.
1,219,825
1,256,203
Build Managment: Eclipse project vs Eclipse Managed Make project
I am developing under Windows, and using Eclipse with CDT to develop C++ applications. Now, for build management I can create a normal C++ project and Eclipse will completely manage the build (calling the g++ compiler with proper arguments), or I can create a Managed Make C++ project and Eclipse will manage the Makefile then call make on that Makefile (when building the project) which in turn will complete the build process. Is there any advantage of using one of these approaches and not the other? EDIT: I am not talking about Managed Make vs Standard Make, rather I am talking about Make vs Eclipse. Yesterday I tried compiling a C++ project under eclipse on a system that doesn't include Make at all, and the project compiled fine, meaning that eclipse can manage the build completely on it's own, which bring the original question into focus: do I need Make?; I can use eclipse alone. That's my question...
One consideration is, do you want to require that developers who work with your project must install and use Eclipse? It's not a value judgement about Eclipse, rather an assumption as to your audience and how familiar they are with your chosen tool. If a C++ programmer is familiar with Java/Eclipse it may not be a problem. If they aren't familiar with Eclipse, they are going to see Eclipse as an obstacle to getting their work done. You need to pay attention to your instructions for putting together a build environment from scratch AND keep it updated. You know developers, There will be some C++ die-hards who will curse your decision and rant about how you should have just done it with Make instead of making (heh) them install a whole new platform just to do a build.
1,219,827
1,219,833
Qt, Mouse skipping, not updating every pixel, mouseMoveEvent()
I working on a simple paint program. It seemed Qt (and KDE) would be a easy way to implement it. I find Qt quite easy to work with, but now I have hit a problem. When I draw something in my program the mouse skips if I move the mouse to fast. like this: It susposed to be like one long string. I'm using mouseMoveEvent() to draw a pixel to my image when the left mouse button is pressed down. I have called setMouseTracking(true); so the event should be called as long as I move the mouse. void camoMaker::mouseMoveEvent(QMouseEvent *ev) { if(ev->state()==Qt::LeftButton) { QPoint mPoint=ev->pos(); mPoint.setX(mPoint.x()-80); drawPoint(mPoint); } } camoMaker is the main widget. drawPoint() draws a pixel on both a internal QImage and using QPainter on a QWidget thats the drawing area. It seems to me that either mouseMoveEvent() isn't called for every pixel the mouse moves or that the mouse actually just skips some pixel. I understand that it might just how it works and not Qt fault but X11 or how the OS handle mouse position/input. If so how would I go about to fix it, should I try to interpolate from 2 points that gets registered?
Mouse events don't occur for each pixel as the mouse moves, on most operating systems. The message handlers (including KDE/linux) repeatedly show mouse movements, but pixels will often be skipped. You'll need to track the last pixel location, and either draw a line, or add extra points in between the last position and the current position.
1,219,879
1,753,264
Developing Console Like Apps For Palm OS
I'm learning C++, but i only develop console apps, because graphical C++ development is so much difficult, then i want to know if i can develop console like apps for Palm OS, what i want is this, compile this code for Palm OS for example: // ClientFille.cpp // Cria um arquivo sequencial. #include <iostream> using std::cerr; using std::cin; using std::cout; using std::endl; using std::ios; #include <fstream> // Fluxo de arquivos using std::ofstream; // Gera a saída do fluxo do arquivo #include <cstdlib> using std::exit; // Sai do protótipo de funcão int main() { // Construtor ofstream abre arquivo ofstream outClientFile( "Clients.dat", ios::out ); // Fecha o programa se não conseguir criar o arquivo if ( !outClientFile ) // Operador ! sobrecarregado { cerr << "File could not be opened" << endl; exit( 1 ); } // Fim do if cout << "Enter the account, name, and balance." << endl << "Enter end-of-file to end the input.\n? "; int account; char name[ 30 ]; double balance; // Lê conta, nome e saldo a partir de cin, então coloca no arquivo while ( cin >> account >> name >> balance ) { outClientFile << account << ' ' << name << ' ' << balance << endl; cout << "? "; } // Fim do while return 0; // Destruitor ofstream fecha o arquivo } // Fim de main Thanks!
The only built-in stdin/stdout interface on Palm OS is the secret "network console". I wrote about this in an old blog entry at http://palmos.combee.net/blog/HiddenIOConsole.html. However, there's no C++ binding for this, so you'd need to make your own stream classes that call into these functions, and the old version of the SDK you need is long forgotten on ACCESS's current website. You can probably find it in an old copy of CodeWarrior for Palm OS.
1,219,951
1,219,977
Win32API - How to get file name of process from process handle?
How can I get the file name of process from a process handle? I'm using Win32 C++ (Visual C++ Express Edition). Thanks.
Call GetModuleFileNameEx. Available as of Windows 2000. DWORD WINAPI GetModuleFileNameEx( __in HANDLE hProcess, __in_opt HMODULE hModule, __out LPTSTR lpFilename, __in DWORD nSize ); Use NULL for the second parameter to get the name of the EXE file.
1,220,223
1,220,271
are there any tutorials to help a proficient c++ programmer learn c?
I became a professional programmer in the era of object oriented code, and have years of experience programming in C++. I often work on large projects that have years of legacy code in a mix of c++ and c. I feel less comfortable working on pure c parts of systems. From programming in C++ I understand all the c syntax, but there's a hole in my knowledge about how to organise a complex c program without objects, and what constitutes best practise for managing memory that I would like to fill. I learnt c++ after working as a java programmer, and think a bit more c would make me a better c++ programmer, and a bit less of a java translated into c++ programmer
In terms of organization, looking at the POSIX APIs, especially pthreads will give you a good idea of how to organize C code. The basic rules of good C project organization are: Don't expose your structures. Use opaque types only. Use the library and data type names as prefixes for function names. Provide "create" and "destroy" functions for allocation/construction and destruction/deallocation. Pass in the opaque type as the first parameter to functions operating on that type. Implement the C APIs using either C or C++ (it's up to you). Obviously, use non-opaque types there.
1,220,265
1,220,277
Best practice for fetching a collection of items from an object?
I'm dealing specifically with C++, but this is really language-agnostic. Just to give some context into the problem... I have a tree/graph based structure where each node holds a collection of multiple items. I have a class which encapsulates some generic collection (list, map, vector, LinkedList, whatever). I want to be able to fetch all the items from that collection in the most efficient way possible without the client being able to edit the private collection. Here is a simplified example of what I have: class MyClass { public: // Basic constructors and such void AddItem(int item) { _myItems->push_back(item); } private: list<int>* _myItems; }; So obviously a getter which retrieves the pointer to _myItems does not work as this will allow the client to edit _myItems. Attempt 1: I could create a new list and return a pointer to that one instead... however I don't like that idea as the responsibility of creating and deleting now lie with different objects. Attempt 2: I'm thinking it would be best to create some CopyTo methods such as: void CopyItemsToList(list<int>* inList) { // copy the items to client list } This way, the client takes care of mem management and it is easy to extend this to allow more data structures. My concern with this approach is cost... The list can be very big, and the cost of copying the items could get large Attempt 3: Instead of keeping a pointer to a list in the class, just use a value type and return that (letting the copy constructor take care of it). But, this seems like the performance cost will be the same as #2... Anyways, any other way to go about this? Let me know what you guys think... Thanks.
The Iterator pattern is generally considered a proper method to expose a list of elements from a collection agnostic to the actual internal representation of the collection. You could create your iterator in such a way that it returns read-only (const) references, or make copies of items on the fly as they're requested instead of copying the entire list.
1,220,275
1,220,280
Where can I get information about the C/C++ linker in Visual Studio?
I'd like to learn more about C/C++ linker issues and troubleshooting in Visual Studio. I've had linker problems crop up from time to time and they are really annoying since you get such limited information from the linker error messages. I've seen a few not-so-detailed MSDN articles but nothing in depth. Where can I find a good source for linker information? Maybe a book, website or some in-depth blog posts? Are there useful utilities to aid linker troubleshooting out there? Browsing around with dumpbin is somewhat less than satisfying.
For a general understanding of linkers, read the book “Linkers and loaders”. You can read it online: http://www.iecc.com/linker/. I think that an in-depth look into Windows executables alone will be very useful: http://msdn.microsoft.com/en-us/magazine/cc301805.aspx http://msdn.microsoft.com/en-us/magazine/cc301808.aspx And of course, the documentation: http://msdn.microsoft.com/en-us/library/y0zzbyt4.aspx.
1,220,304
1,220,358
Does source incompatibility always imply binary incompatibility?
Any examples demonstrating where source compatibility is broken yet binary compatibility is maintained is welcome.
Old version: struct inner { int bar; } struct foo { struct inner i; }; void quux(struct foo *p); New version: struct inner2 { int bar; }; struct foo { struct inner2 i; }; void quux(struct foo *p); Broken code: struct foo x; struct inner *i = &x.i; i->bar = 42; quux(&x); Since the only difference is the name of the struct, and the inner struct's type name is erased during compilation, there's no binary incompatibility.
1,220,396
1,220,407
Keeping the contents of an array after its function call ends. (C++)
Lets say I have the following code. double *return_array(void) { double foo[2]; foo[0] = 5; foo[1] = 6; cout << foo << endl; cout << foo[0] << endl << foo[1] << endl; return foo; } double *bar = return_array() cout << bar << endl; cout << bar[0] << endl << bar[1] << endl; Now, bar and foo are still the same pointer but what was there has changed completely. How can I get around this? Basically, I need to pass 6 or 9 doubles from a function. What should I do?
Typically you would pass in your pre-allocated memory into the function: int barsize = 2; double *bar = new double[barsize]; fill_array( bar, barsize ); cout << bar << endl; cout << bar[0] << endl << bar[1] << endl; delete [] bar; void fill_array( double *foo, int foosize ) { if ( foosize < 2 ) return; foo[0] = 5; foo[1] = 6; cout << foo << endl; cout << foo[0] << endl << foo[1] << endl; } The rule I use is... always allocate and delete memory in the same spot. Or use a std::vector. They're nice =) I never use arrays anymore.
1,220,499
1,220,576
How is a "handshake" generally implemented with regards to Named Pipes
I need to implement a handshake type protocol in to a small Linux program that uses named pipes to communicate with other processes. I've searched for a general implementation pattern for a handshake type protocol when using named pipes but I've not been able to turn anything up... I simply can't believe that there isn't patterns to do this. Can someone point me to a possible resource? In full disclosure this is for homework but implementing this pattern isn't the homework. We need to solve a problem within the homework code and I believe this to be a possible solution. The homework is implemented in C++ -- but the languages doesn't matter to me. I just don't want to reinvent the wheel.... Update: I have a feeling that this might be implemented with signals. What I mean by handshake is that a child process reports to it's parent process that it is ready for work but does not proceed (even if there is something in the pipe) until the parent gives the go signal. In my working theory, I will have many child processes that need to report ready and wait for the go signal from the parent.
In typical usage, the processes rely on blocking to handshake. The writer process opens the pipe for writing, the reader process opens the pipe for reading, and whichever happens first blocks until the other process opens its side. This can be extended to use nonblocking IO on the reader side. Named pipes are most useful for one-to-one IPC. In your one-to-many situation, you should probably use a UNIX-domain socket instead.
1,220,507
1,220,514
Initialising a std::string from a character
There doesn't seem to be a standard constructor so I've taken to doing the following void myMethod(char delimiter = ',') { string delimiterString = 'x'; delimiterString[0] = delimiter; // use string version ... } Is there a better way to do this?
std::string has a constructor that will do it for you: std::string delimiterString(1, delimiter); The 1 is a size_t and denotes the number of repetitions of the char argument.
1,220,518
1,220,521
What is wrong with this usage of the new operator?
Is this allowed? Object::Object() { new (this) Object(0, NULL); }
Using new(this) will re-construct member variables. This can result in undefined behavior, since they're not destructed first. The usual pattern is to use a helper function instead: class Object { private: void init(int, char *); public: Object(); Object(int, char *); }; Object::Object() { init(0, NULL); } Object::Object(int x, char *y) { init(x, y); } void Object::init(int x, char *y) { /* ... */ }
1,220,826
1,221,064
Changing wallpaper on Linux programmatically
How would I change the wallpaper on a Linux desktop (using GNOME) within a C/C++ program? Is there a system API to do it?
Though the question was gnome-specific, there's also a way to deal with the wallpaper that is not depepndant on the higher layer toolkits. You should be able to deal with the root window (which the wallpaper is, in fact) by studying the source of xsetroot.c, the most interesting part of which I copypaste here: static void SetBackgroundToBitmap(Pixmap bitmap, unsigned int width, unsigned int height) { Pixmap pix; GC gc; XGCValues gc_init; gc_init.foreground = NameToPixel(fore_color, BlackPixel(dpy, screen)); gc_init.background = NameToPixel(back_color, WhitePixel(dpy, screen)); if (reverse) { unsigned long temp=gc_init.foreground; gc_init.foreground=gc_init.background; gc_init.background=temp; } gc = XCreateGC(dpy, root, GCForeground|GCBackground, &gc_init); pix = XCreatePixmap(dpy, root, width, height, (unsigned int)DefaultDepth(dpy, screen)); XCopyPlane(dpy, bitmap, pix, gc, 0, 0, width, height, 0, 0, (unsigned long)1); XSetWindowBackgroundPixmap(dpy, root, pix); XFreeGC(dpy, gc); XFreePixmap(dpy, bitmap); if (save_colors) save_pixmap = pix; else XFreePixmap(dpy, pix); XClearWindow(dpy, root); unsave_past = 1; }
1,220,839
1,246,863
Can Eclipse CDT do auto-complete when using typedefs?
For all my code Eclipse's autocomplete function is working fine, except when I use a typedef. Example code (someclass.hh): typedef std::vector<int> IntVector; class SomeClass { void sort_int_vector(IntVector &iv) { iv.//eclipse auto complete does not work. (ctrl-space) } } How can I configure Eclipse to do auto-complete in this case? Or is this not possible? I use the Ganymede C/C++ (CDT) package for Linux 64-bit
This works for me using Galileo, I would have expected this to be working for a couple of releases now. Check that the CDT is able to find the appropriate include file. You can check the Includes under the project explorer. If it isn't finding your includes, check your project properties -> C/C++ General -> Paths and Symbols. You can add paths to places to find the headers. It Just worked for me, the new project wizard set up paths to the cygwin I have on my path.
1,220,974
1,221,127
Does MemoryDC occupied memory or the memory on video card?
I am using the following code to create a compatible DC: m_pDC=new CDC(); VERIFY(m_pDC->CreateCompatibleDC(sampleDC); CBitmap bitmap; if (bitmap.CreateCompatibleBitmap(sampleDC, rect.Width(), rect.Height())) { m_pOldBitmap = m_pDC->SelectObject(&bitmap); } My question is does CDC CBitmap occupied memory ? If it is using memory, why does it get bad result when rect.width and rect.height are large. (There are enough memory). Someone said it is using memory on video card. Is it true. I am not very sure about it.
Memory in CreateCompatibleBitmap are allocated from a system-wide pool that's typically limited to about 200 Megabytes on 32-bit versions of Windows. Since WinNT4.0 CreateBitmap() API allocates the bitmap in kernel-mode paged memory. In WinNT4 it was impossible to create bitmaps greater than 48 MB. What was your limit?
1,221,185
1,221,238
Identical build on different systems
I have 3 build machines. One running on windows 2000, one with XP SP3 and one with 64bit Windows Server 2008. And I have a native C++ project to build (I'm building with visual studio 2005 SP1). My goal is to build "exactly" the same dll's using these build machines. By exactly I mean bit by bit (except build timestamp of course). With win2k and winxp I'm getting identical dll's. But they differ from dll built with win2008 server. I've managed to get almost identical dll's, but there are some differences. After disassembling the files I found out that function order is not the same (3 functions are in different order). Does anyone know what could be the reason for that? And a side question: In vcbuild.exe I've found a switch /ORDER. Which takes function order file as input. Anyone knows how that file should look like?
You might think that compiling is purely deterministic (identical inputs give identical output, every time) but this need not be the case. For example, consider the optimiser - this is going to need some memory to work in, probably more for higher optimisation methods. If on one machine a memory allocation fails (because the machine has less memory) then the compiler could omit that specific optimisation, resulting in different code being emitted. There are a lot of similar situations, so you may be putting a lot of effort into something that is not doable. Why do you need the DLLs to be bitwise identical, anyway?
1,221,244
1,221,262
C++ Real time console app, simultaneous input and output
I'm writing a quick server app for something so don't really want to write a full GUI. However the problem is that the main part of the server, however the console window will only allow input or output at a time. Many games ive played that have a console in them (usually needs activating in some way or another) they solved this problem by separating the input and output, such that the bottom line is dedicated to entering input commands, while the rest is used for output like a normal console window. Is it possible to do something like that with a minimal amount of work (ie without having to write my own console window from scratch), and in a cross platform way? Ideally id like to still use the normal command prompt somehow for the case where the server is running on a system without all the GUI stuff installed, although I guess a simple GUI client that could connect with the server would be fine as well. By cross platform I mean Windows and Linux support is required. Although if I went the client GUI route id also require Mac on top of that.
Sounds like you should have a look at curses ncurses pdcurses
1,221,300
1,221,362
C++ error detection in Visual Studio 2005
Coming from a different development environment (Java, mostly) I'm trying to make analogies to habits I'm used to. I'm working with a C++ project in Visual Studio 2005, the project takes ~10 minutes to compile after changes. It seems odd that if I make a small syntactical error, I need to wait a few good minutes to get a feedback on that from the compiler, when running the entire project build. Eclipse gave me the habit that if I make some small change I will immediately get a compiler error with an underline showing the error. Seems reasonable enough that VS should be able to do this. Is this something I can enable in VS or do I need an external plug-in for this?
The feature you are asking for will be available in Visual Studio 2010. Here is a detailed link of the feature details that will be available. For now, as others have suggested, you can use Visual Assist which can help a little bit. These are called Squiggles BTW.
1,221,902
1,221,913
Programs compiles in g++ but exits with linker errors in gcc
I'm trying out the solution to a question about specialized template classes. This code with a compiles fine in g++, but throws up linker errors when compiled with gcc. What's the cause of these errors ? $ g++ traits2.cpp $ gcc traits2.cpp /tmp/ccI7CNCY.o: In function `__static_initialization_and_destruction_0(int, int)': traits2.cpp:(.text+0x36): undefined reference to `std::ios_base::Init::Init()' traits2.cpp:(.text+0x3b): undefined reference to `std::ios_base::Init::~Init()' /tmp/ccI7CNCY.o:(.eh_frame+0x11): undefined reference to `__gxx_personality_v0' collect2: ld returned 1 exit status The traits2.ccp file contains the aforementioned solution with an emtpy main() function: #include <iostream> using namespace std; // A default Traits class has no information template<class T> struct Traits { }; // A convenient way to get the Traits of the type of a given value without // having to explicitly write out the type template<typename T> Traits<T> GetTraits(const T&) { return Traits<T>(); } template <int major, int minor> struct A { void f() { cout << major << endl; } }; // Specialisation of the traits for any A<int, int> template<int N1, int N2> struct Traits<A<N1, N2> > { enum { major = N1, minor = N2 }; }; template <> struct A<4,0> { void f() { cout << "Specialized:" << GetTraits(*this).major << endl; } }; int main(int argc, char * argv[] ) { /* A<4,0> p; A<1,2> p2; p.f(); p2.f(); */ return 1; }
When you compile with gcc, the C++ libraries are not linked in by default. Always build C++ code with g++.
1,222,264
1,238,715
C++ mysql and boost asio header conflict
There seems to be a conflict with the windows headers between the mysql c-api and boost::asio. If I include mysql first I get: boost/asio/detail/socket_types.hpp(27) : fatal error C1189: #error : WinSock.h has already been included #if defined(BOOST_WINDOWS) || defined(__CYGWIN__) # if defined(_WINSOCKAPI_) && !defined(_WINSOCK2API_) # error WinSock.h has already been included # endif // defined(_WINSOCKAPI_) && !defined(_WINSOCK2API_) If I include boost::asio first I get: include\config-win.h(24) : warning C4005: '_WIN32_WINNT' : macro redefinition /* Defines for Win32 to make it compatible for MySQL */ #ifdef __WIN2000__ /* We have to do this define before including windows.h to get the AWE API functions */ #define _WIN32_WINNT 0x0500 #else /* Get NT 4.0 functions */ #define _WIN32_WINNT 0x0400 #endif Is there some way around this, and why is mysql trying to force the windows version and boost trying to enforce that it include winsock its self anyway?
The macro redefinition is only a warning. Your code should still compile and link. I think your code will even work without any problem.
1,222,296
1,222,438
Building a vector from components contained in another vector type
I have a code that looks something like this: struct First { int f1; int f2; }; struct Second { First s1; int s2; }; std::vector < Second > secondVec; Second sec; sec.s1 = First(); secondVec.push_back(sec); secondVec.push_back(sec); std::vector < First > firstVec; firstVec.reserve(secondVec.size()); for (std::vector < Second >::iterator secIter = secondVec.begin(); secIter != = secondVec.end(); ++secIter) { firstVec.push_back(secIter->s1); } I'd like to replace this ugly for loop with a simple stl function that could perhaps perform the equivalent process. I was thinking that maybe std::transform could help me here, but I'm unsure as to how this could be written. I'd also be interested if boost has anything to offer here.
If you have TR1 or Boost available, you could try this: std::transform(secondVec.begin(), secondVec.end(), std::back_inserter(firstVec), std::tr1::bind(&Second::s1, _1));
1,222,340
1,225,309
Aspect ratios - how to go about them? (D3D viewport setup)
Allright - seems my question was as cloudy as my head. Lets try again. I have 3 properties while configuring viewports for a D3D device: - The resolution the device is running in (full-screen). - The physical aspect ratio of the monitor (as fraction and float:1, so for ex. 4:3 & 1.33). - The aspect ratio of the source resolution (source resolution itself is kind of moot and tells us little more than the aspect ratio the rendering wants and the kind of resolution that would be ideal to run in). Then we run into this: // -- figure out aspect ratio adjusted VPs -- m_nativeVP.Width = xRes; m_nativeVP.Height = yRes; m_nativeVP.X = 0; m_nativeVP.Y = 0; m_nativeVP.MaxZ = 1.f; m_nativeVP.MinZ = 0.f; FIX_ME // this does not cover all bases -- fix! uint xResAdj, yResAdj; if (g_displayAspectRatio.Get() < g_renderAspectRatio.Get()) { xResAdj = xRes; yResAdj = (uint) ((float) xRes / g_renderAspectRatio.Get()); } else if (g_displayAspectRatio.Get() > g_renderAspectRatio.Get()) { xResAdj = (uint) ((float) yRes * g_renderAspectRatio.Get()); yResAdj = yRes; } else // == { xResAdj = xRes; yResAdj = yRes; } m_fullVP.Width = xResAdj; m_fullVP.Height = yResAdj; m_fullVP.X = (xRes - xResAdj) >> 1; m_fullVP.Y = (yRes - yResAdj) >> 1; m_fullVP.MaxZ = 1.f; m_fullVP.MinZ = 0.f; Now as long as g_displayAspectRatio equals the ratio of xRes/yRes (= adapted from device resolution), all is well and this code will do what's expected of it. But as soon as those 2 values are no longer related (for example, someone runs a 4:3 resolution on a 16:10 screen, hardware-stretched) another step is required to compensate, and I've got trouble figuring out how exactly. (and p.s I use C-style casts on atomic types, live with it :-) )
I'm assuming what you want to achieve is a "square" projection, e.g. when you draw a circle you want it to look like a circle rather than an ellipse. The only thing you should play with is your projection (camera) aspect ratio. In normal cases, monitors keep pixels square and all you have to do is set your camera aspect ratio equal to your viewport's aspect ratio: viewport_aspect_ratio = viewport_res_x / viewport_res_y; camera_aspect_ratio = viewport_aspect_ratio; In the stretched case you describe (4:3 image stretched on a 16:10 screen for example), pixels are not square anymore and you have to take that into account in your camera aspect ratio: stretch_factor_x = screen_size_x / viewport_res_x; stretch_factor_y = screen_size_y / viewport_res_y; pixel_aspect_ratio = stretch_factor_x / stretch_factor_y; viewport_aspect_ratio = viewport_res_x / viewport_res_y; camera_aspect_ratio = viewport_aspect_ratio * pixel_aspect_ratio; Where screen_size_x and screen_size_y are multiples of the real size of the monitor (e.g. 16:10). However, you should simply assume square pixels (unless you have a specific reason no to), as the monitor may report incorrect physical size informations to the system, or no informations at all. Also monitors don't always stretch, mine for example keeps 1:1 pixels aspect ratio and adds black borders for lower resolutions. Edit If you want to adjust your viewport to some aspect ratio and fit it on an arbitrary resolution then you could do like that : viewport_aspect_ratio = 16.0 / 10.0; // The aspect ratio you want your viewport to have screen_aspect_ratio = screen_res_x / screen_res_y; if (viewport_aspect_ratio > screen_aspect_ratio) { // Viewport is wider than screen, fit on X viewport_res_x = screen_res_x; viewport_res_y = viewport_res_x / viewport_aspect_ratio; } else { // Screen is wider than viewport, fit on Y viewport_res_y = screen_res_y; viewport_res_x = viewport_res_y * viewport_aspect_ratio; } camera_aspect_ratio = viewport_res_x / viewport_res_y;