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,469,815
1,576,600
Trying to make SDL widget in QT4 using SDL_WINDOWID, but can't get widget to show
I'm trying to create an SDL drawing canvas inside of a simple QT4 window, following the information provided in the SDL wiki and in another question on this site. The project is an NES emulator using QT and SDL that a friend and I decided we wanted to try creating. Currently, I have a main_window class that will contain the SDL widget, menus that I set up, and probably other stuff as the project develops. The SDL widget I'm creating is called rom_canvas and inherits from QWidget. So far, I'm able to set the SDL_WINDOWID environment variable and I seem to be able to interact with the widget in that I can set and get its geometry and see that it is in fact "visible", but nothing actually shows up in the window. I don't have any experience with QT4 and SDL until now and don't have a ton of C++ experience, so I could be missing something obvious. Here's the rom_canvas class: #include "rom_canvas.hpp" #include <iostream> #include <cstdlib> #include <QString> rom_canvas::rom_canvas(QWidget *parent) : QWidget(parent) { parent->setAttribute(Qt::WA_PaintOnScreen); parent->setAttribute(Qt::WA_OpaquePaintEvent); // setAttribute(Qt::WA_PaintOnScreen); // setAttribute(Qt::WA_OpaquePaintEvent); setUpdatesEnabled(false); // a hack I found online to get the SDL surface to appear in our own window QString id; id.setNum(parent->winId()); setenv("SDL_WINDOWID", id.toAscii().data(), 1); SDL_InitSubSystem(SDL_INIT_VIDEO); resize(320, 240); // change constants later sdl_screen = SDL_SetVideoMode(320, 240, DEFAULT_BPP, SDL_SWSURFACE); if(!sdl_screen) std::cout << "couldn't create screen" << std::endl; SDL_LockSurface(sdl_screen); SDL_FillRect(sdl_screen, NULL, 0x00FF0000); SDL_UnlockSurface(sdl_screen); SDL_UpdateRect(sdl_screen, 0, 0, 0, 0); } rom_canvas::~rom_canvas() { // do NOT release sdl_screen here; that's done when SDL_Quit() is called in main(). } // this method is a protected slot void rom_canvas::test() { std::cout << "rom_canvas test" << std::endl; SDL_LockSurface(sdl_screen); SDL_FillRect(sdl_screen, NULL, 0x00FF0000); SDL_UnlockSurface(sdl_screen); SDL_UpdateRect(sdl_screen, 0, 0, 0, 0); } And here's the main_window constructor: main_window::main_window(QWidget *parent) : QMainWindow(parent) { canvas = new rom_canvas(this); setCentralWidget(canvas); canvas->setGeometry(100, 100, 100, 100); canvas->show(); canvas->update(); // Add File Menu open_action = new QAction(tr("&Open..."), this); open_action->setShortcuts(QKeySequence::Open); open_action->setStatusTip(tr("Open a new ROM")); connect(open_action, SIGNAL(triggered()), this, SLOT(select_rom())); exit_action = new QAction(tr("E&xit"), this); exit_action->setStatusTip(tr("Exit nesT")); connect(exit_action, SIGNAL(triggered()), /*QApplication::instance()*/canvas, SLOT(/*quit()*/test())); // Remember to change this back!! file_menu = menuBar()->addMenu(tr("&File")); file_menu->addAction(open_action); file_menu->addAction(exit_action); rom_dir = QDir::homePath(); } The code's a bit messy since I've been trying things to get this to work. Any help is of course greatly appreciated.
I guess you already know, but the SDL_WINDOWID trick probably isn't portable - I am pretty sure it won't work on Mac. I am curious what you want SDL for, in this scenario - if you simply want a pixel-addressable image buffer (or several), use QPixmap / QImage and stick to pure Qt. Or if you want the SDL sprite features, I'd suggest having SDL composite to an in-memory buffer attached to a QImage, and then draw that to a Qt widget. (Or use QImages as sprites, and use the OpenGL QPainter backend) Internally, Qt works pretty hard to use platform-native code to do image format conversion, so even though this sounds fairly copy-heavy, I think it will be sufficiently fast, and much more robust and portable than the SDL_WINDOWID trick.
1,469,947
1,470,026
How to use cross platform C++ with a WPF C# GUI
I'm currently in a project that need to work both on Mac and Windows. We are using standard portable C++ for all the application logic. However, since we want the app to feel totally native on both platform, the GUI will be written with C#/WPF for Windows and Objective-C/Cocoa for Mac. However, for the windows part, I am wondering what is the best way to use the C++ code with C#. C# is managed, and I know that we can use managed C++ too. However I worry that using C++ inside the CLR may introduce unexpected bugs, or that we will need to put an awful lot of #ifdef WIN32 everywhere in the C++ code to make it work both with the managed CLR and the unmanaged environnement of Mac OS X (note that we sure expect to put some ifdef, but we'd like to keep it under control if possible). So basically, what is the best way to use the C++ code with the C# code? Right now, I'm thinking of three solutions 1- Compile the C++ as C++/CLI and directly use the classes and function from C#. 2- Compile and wrap the C++ in an unmanaged win32 dll and call it from C# using DllImport 3- Wrap the C++ in a COM wrapper and use the .NET COM Interop to link it with C# Which one is the best way? Or, if there is a better solution, what is it?
C++/CLI has several restrictions over standard C++ that don't always make it easy to recompile standard C++ as C++/CLI. Keep in mind that you'll have to distinguish 'managed' and 'unmanaged' pointers, for starters. As these are using different symbols, you've got your first set of #ifdefs right there. And then you get to ref and value classes and all that sort of fun. You can however use C++/CLI to bridge the gap between native code and the .NET world. The last time I did something along the lines of what you're planning to do, I used C++/CLI to write the bridging layer that did the necessary translation and conversion work between .NET types and classes and the native world. The C++/CLI layer can obviously be used from any .NET language. You can't always use (2) - this depends very much on the data types you're trying to exchange between the two worlds. The .NET marshalling code is pretty good at dealing with C PODs but anything more complicated and you've got a problem. (3) is overkill IMHO and introduces another point of failure, plus you're then doing .NET <-> COM <-> native instead of the simpler .NET <-> native if you created your own bridging code. Not to mention that you add complication to your code that won't benefit the other OS you're targeting, namely OS X.
1,470,009
1,470,113
How do you call a managed (C#) function from C++?
I have a C# DLL file project (my_cs_dll.dll) which defines a static class with a static member function. namespace Foo { public static class Bar { public static double GetNumber() { return 1.0; } } } I also have a C++ DLL project which is using /clr. #using <my_cs_dll.dll> double get_number_from_cs() { return Foo::Bar::GetNumber(); } I've added a reference to 'my_cs_dll.dll' in the C++ project Common Properties references section (copy local/copy dependencies are both True). And I've also added the path to 'my_cs_dll.dll' in the C++ project Configuration Properties C/C++ General 'Resolve#using References' section. Everything builds without error, however at runtime I keep getting a 'System.IO.FileNotFound' exception from the system claiming it can't find the my_cs_dll.dll assembly. Both DLL files are definitely present in the same directory from which I'm running. I have tried all sorts of variations on the settings mentioned above and read everything I could find on manged/unmanaged interop, but I can't seem to get my brain around what is wrong... I'm using Visual Studio 2008 and .NET 3.5.
It sounds like your C# assembly is not being resolved at runtime. Is your C# dll in the same directory as (or a subdirectory of) your executable? It's been a while since I did this, but my recollection is that unless your assembly is installed in the GAC, it must be in the directory (or a subdirectory) where your executable is located, as opposed to the location of the dll that's using it. This has to do with the .NET security features. If you are still having problems, you can try using resolving the assembly yourself. In your clr-enabled C++ project, try adding the following: using namespace System; using namespace System.Reflection; void Resolve() { AppDomain::CurrentDomain->AssemblyResolve += gcnew ResolveEventHandler(OnAssemblyResolve); } Assembly ^OnAssemblyResolve(Object ^obj, ResolveEventArgs ^args) { #ifdef _DEBUG String ^path = gcnew String(_T("<path to your debug directory>")); #else String ^path = gcnew String(_T("<path to your release directory>")); #endif array<String^>^ assemblies = System::IO::Directory::GetFiles(path, _T("*.dll")); for (long ii = 0; ii < assemblies->Length; ii++) { AssemblyName ^name = AssemblyName::GetAssemblyName(assemblies[ii]); if (AssemblyName::ReferenceMatchesDefinition(gcnew AssemblyName(args->Name), name)) { return Assembly::Load(name); } } return nullptr; } You may have to tweak the code a little bit to get it to compile in your project. In my case, I made the two functions static methods of a class in my clr-enabled project. Just make sure you call the Resolve() function early on in your code, i.e., before you try to call get_number_from_cs(). While using COM is an option, it is not necessary. You're on the right path with your current approach. If you want some hand-holding, take a look at this CodeProject example. It's the one I following to get my unmanaged application to use my managed assemblies.
1,470,171
1,753,191
Controlling mouse in linux
Basically I'm currently using the wiiuse library to get the wiimote working on linux. I want to now be able to control the mouse through the IR readings. Can somebody point me in the right direction as to how to approach this? I know of uinput but there doesn't seem to be a lot of tutorials/guides on the web. I'm working with c/c++ so a library in c/c++ would be helpful. Cheers.
In the end I decided to just draw "cursor" objects on the screen and use setup each input device to control a separate "cursor" object. This seemed the best idea as we were short on time.
1,470,217
1,470,306
Usage of D in the Field
I have tried to find some information on D. I do especially like this comparison with C++ to get an overview on what it is. Now I am asking myself: how often D is used in the field, and how much of a viable alternative is it to C++?
I think D is a great language, but what people might hold back from using it is that it is (afaik) not compatible with c++ libraries. So all libraries you can use have to be written in C or D. So if you are a C++ developer switching to D isn't so much fun.
1,470,528
1,470,576
Whereto put "plugins" in linux
I am currently developing/hacking an image analyzing/transforming tool. The filters therein will be loaded at runtime using dlopen&co. My question is where do *nix tools usually put plugins (*.so files) when installed? bin/program lib/program/plugins/thisandthat.so maybe? Secondly how do I use it and where do I put it during development without installing it. (this is probably the tricky part) I want to avoid shell-scripts if possible. thanks in regard Ronny
The layout seems sensible. You can, for instance, look in current directory, look up environment variable or command line switch during development. It depends on the details of your development environment and workflow.
1,470,530
1,470,690
Does c/c++ have a delay function?
Does c/c++ have a delay/wait/sleep function?
C++ does not have a sleep function. But most platforms do. On Linux you have sleep() and usleep(). On Windows you have Sleep(). You just have to include the appropriate headers to get access to them.
1,470,605
1,470,693
abstract an Interface `ISingleton` to be base class
I have 3 interface classes IVideo , IAudio , IGPIO and three other classes that will implement those interface: Video_impl , Audio_impl , GPIO_impl. Things is simple so far. But then ,I want all those object to be singleton. Here are the questions: Is it a good idea to abstract an Interface ISingleton , so that Video_impl , Audio_impl , GPIO_impl (or IVideo , IAudio , IGPIO ?) can inherit from it? I was thinking of implement it in following way. Is it recommended? I think there must be better ways. //Isingleton.hpp template <class T> class ISingleton { public: virtual T *getInstance() = 0; }; class IGPIO { public: virtual int SelectAudioInput() = 0; }; class GPIO_impl : public IGPIO, public ISingleton<IGPIO> { public: IGPIO *getInstance(); int SelectAudioInput() ; private: IGPIO *instance; };
I would recommend reading Alexandrescu's "Modern C++ Design". In it, among many other things, he designs a fully-fledged singleton template and thinks through many of the issues, such as when it should be destroyed, whether it should resurrect after being destroyed because it is needed during the destruction of other singletons, and all that good stuff.
1,470,654
1,470,728
Define a symbol in another namespace
Here is my problem: in a header I define a structure template type_to_string, which aims at defining a string corresponding to a given type argument: namespace foo { template <typename T> struct type_to_string { static const char * value; }; } template <typename T> const char * foo::type_to_string<T>::value = "???"; I also define a default value for the string. Now, I'd want to use a macro for defining new types: #define CREATE_ID(name) \ struct name; \ \ template<> \ const char * foo::type_to_string<name>::value = #name; The problem is that I'd like the macro to be usable in namespaces, as in: namespace bar { CREATE_ID(baz) } which is not possible because type_to_string<T>::value must be defined in a namespace enclosing foo. Here is the compilation errors I get: [COMEAU 4.3.10.1] error: member "foo::type_to_string<T>::value [with T=bar::baz]" cannot be specialized in the current scope [VISUAL C++ 2008] error C2888: 'const char *foo::type_to_string<T>::value' : symbol cannot be defined within namespace 'bar' with [ T=bar::baz ] Strangely, GCC 4.3.5 (MinGW version) doesn't produce any errors. Does anyone know a workaround for this, maybe by using some lookup rules I'm not aware of (i.e. declaring type_to_string in the macro so that each namespace has its own version, or something like that)?
According to C++ Standard 14.7.3/2: An explicit specialization shall be declared in the namespace of which the template is a member, or, for member templates, in the namespace of which the enclosing class or enclosing class template is a member. An explicit specialization of a member function, member class or static data member of a class template shall be declared in the namespace of which the class template is a member. Such a declaration may also be a definition. If the declaration is not a definition, the specialization may be defined later in the name- space in which the explicit specialization was declared, or in a namespace that encloses the one in which the explicit specialization was declared. You could write something like the following: #define DECL_ID(name) \ struct name; #define CREATE_ID(name) \ template<> \ const char * foo::type_to_string<name>::value = #name; namespace bar { namespace bar2 { DECL_ID(baz) } } CREATE_ID(bar::bar2::baz) Or #define CREATE_ID(ns, name) \ namespace ns { struct name; } \ \ template<> \ const char * foo::type_to_string<ns::name>::value = #name; CREATE_ID(bar, baz) The third option is superposition of first two. It allows to have unqualified name in value (if it is required): #define DECL_ID(name) \ struct name; #define CREATE_ID(ns, name) \ template<> \ const char * foo::type_to_string<ns::name>::value = #name; namespace bar { namespace bar2 { DECL_ID(baz) } } CREATE_ID(bar::bar2, baz)
1,470,716
1,470,740
How do I abort a MATLAB m-file function from C/C++?
I deployed a MATLAB project into a DLL, to be called from C++, and it works just fine. Happy days. But what happens when the user asks to cancel an operation? I tried creating a global variable named UserAborted. I initialize it to 0 before running the long function in MATLAB. I also wrote the following two functions: function AbortIfUserRequested global UserAborted if (UserAborted == 1) error('User Abort'); end end function UserAbortLongFunction global UserAborted UserAborted = 1; end I call upon AbortIfUserRequested in every iteration of the loop in my long function. I also exported UserAbortLongFunction. I expected that pretty soon after called UserAbortLongFunction, the long function would reach a call to AbortIfUserRequested, and throw an error. Instead, the long function keeps running until the end, and only then does the value of UserAborted get changed. All I want to do is abort that long function when the user asks me to! Is there any way to do that?
Matlab needs to provide callback functions to show execution progress and possibly halt it. A Google search shows lots of people wanting this but no implementation from Mathworks.
1,470,741
1,470,959
Intel Inspector reports a data race in my spinlock implementation
I made a very simple spinlock using the Interlocked functions in Windows and tested it on a dual-core CPU (two threads that increment a variable); The program seems to work OK (it gives the same result every time, which is not the case when no synchronization is used), but Intel Parallel Inspector says that there is a race condition at value += j (see the code below). The warning disappears when using Critical Sections instead of my SpinLock. Is my implementation of SpinLock correct or not ? It's really strange, because all the used operations are atomic and have the proper memory barriers and it shouldn't lead to race conditions. class SpinLock { int *lockValue; SpinLock(int *value) : lockValue(value) { } void Lock() { while(InterlockedCompareExchange((volatile LONG*)lockValue, 1, 0) != 0) { WaitABit(); } } void Unlock() { InterlockedExchange((volatile LONG*)lockValue, 0); } }; The test program: static const int THREADS = 2; HANDLE completedEvents[THREADS]; int value = 0; int lock = 0; // Global. DWORD WINAPI TestThread(void *param) { HANDLE completed = (HANDLE)param; SpinLock testLock(&lock); for(int i = 0;i < 1000*20; i++) { for(int j = 0;j < 10*10; j++) { // Add something to the variable. testLock.Lock(); value += j; testLock.Unlock(); } } SetEvent(completed); } int main() { for(int i = 0; i < THREADS; i++) { completedEvents[i] = CreateEvent(NULL, true, false, NULL); } for(int i = 0; i < THREADS; i++) { DWORD id; CreateThread(NULL, 0, TestThread, completedEvents[i], 0, &id); } WaitForMultipleObjects(THREADS, completedEvents, true, INFINITE); cout<<value; }
Parallel Inspector's documentation for data race suggests using a critical section or a mutex to fix races on Windows. There's nothing in it which suggests that Parallel Inspector knows how to recognise any other locking mechanism you might invent. Tools for analysis of novel locking mechanisms tend to be static tools which look at every possible path through the code, Parallel Inspector's documentation implies that it executes the code once. If you want to experiment with novel locking mechanisms, the most common tool I've seen used in academic literature is the Spin model checker. There's also ESP, which might reduce the state space, but I don't know if it's been applied to concurrent problems, and also the mobility workbench which would give an analysis if you can couch your problem in pi-calculus. Intel Parallel Inspector doesn't seem anything like as complicated as these tools, but rather designed to check for commonly occurring issues using heuristics.
1,471,104
1,471,113
Does malloc/new return memory blocks from Cache or RAM?
I wanted to know whether malloc/new returns memory blocks from Cache or RAM. Thanks in advance.
You are abstracted of all that when living as a process in the OS, you only get memory. You shouldn't worry ever about that, the OS will manage all that for you and the memory unit will move things from one to another. But you still see a single virtual memory layout.
1,471,109
1,599,437
C/C++ Libraries for reading from Universal Disk Format devices or files
Are there any good free C/C++ libraries that enable reading from common devices with filesystems such as UDF, and ISO9660 and extracting files/metadata etc.? So far all I've been able to find is GNUs libcdio which is promising, and some "Magic UDF" which has so many hits I'm disgusted, pushes other results in Google, and comes with a pretty extreme looking price tag. Cross-platform support is preferable (personal preference of course), and Windows compatibility is an unfortunate requirement. The less restrictive the license, the better, I have yet to investigate how compatible libcdio's GPLv3 license is. Note this question is still open, I'll accept another answer if someone locates such a library.
After extensive investigation, I ended up rolling my own solution to perform the operations on UDF that I required. I'm unable to open the source, in all it was about 800 lines of C++. However here are several links which got me through: The reference standard on which UDF is built Universal Disk Format specification 2.60 Brief introduction to UDF Wikipedia Page UDF Verifier tool (you must sign up for access to this) A few words of warning: Previous experience implementing ISO9660/ECMA-119 helped me significantly. Knowledge of how block devices operate and interface with the operating system is helpful. Information surrounding the physical layout and separation of sessions is somewhat mythical and difficult to grok.
1,471,219
1,471,231
How to write a launching program in C++ or C# for Windows Vista
How do I write a program in C++ or C# that launches applications on Windows Vista? For example launching Dreamweaver CS 4 ("C:\Program Files\Adobe\Adobe Dreamweaver CS4\Dreamweaver.exe) and place it on top with the BringWindowToTop-function?
In c# Process.Start("c:\whatever\somefile.exe", <commandline args>); should do it
1,471,222
1,471,233
Storage of variables in memory
If I have a list of global variables like this... int a; char b; float c[10]; double d[3]; and I have an identical sequence of variables listed inside a class... class test_type { int a; char b; float c[10]; double d[3]; } is it guaranteed that the arrangement of all the variables in memory are identical. i.e. is 'b' guaranteed to be stored immediately after 'a' in both the globals list and the class list? EDIT: I ask because I wanted to A) copy the data from one to the other as a "job lot" and B) I wanted to check for any differences between them as a job lot. If the answer to the main question is "no" then does anyone have any suggestions as to how I get round the problem, preferably leaving existing code as unaltered as possible.
No. I don't think the C++ standard guarantees anything about the memory layout of global variables.
1,471,333
1,471,406
casting a pointer in Run Time [non-trivial Scnerio]
I have to fix a typical memory leak, Problem is like that : typedef std::map<unsigned long,Response> mapType; class Response { public: void *dataPtr; unsigned long tag; } class anyClass { public:: DataType x; } From client i am getting a map of Type mapType , Which has Response object as map->second , As Response object contain a void Pointer. Please note : Response Class do not know what type of data has been set to void pointer, Also i can't modify Response class to do so , As it is a legacy code and has a great impact :( Now using map->first ,that i call as Tag, Using this tag at run time using this tag i come to know about a class anyClass. Now Response::dataPtr is smae as anyClass::DataType But: as class anyClass is one out of N type, So anyClass::DataType differs for each class which i come to know only at runtime. Please guide me how i can cast a void pointer to type same to anyClass::DataType and can free it
Given that you mention "legacy" code, but may have some freedom to modify, I would likely suggest that whatever interface provided you the map be extended to include a free-ing function. Then it could apply the same type logic as when it created the object in the first place. If that is impossible, then you will likely end up with a case statement and some re-interpret casts like the following pseudo-code: switch (type ) { case Type1: delete reinterpret_cast<Type1Class*>(ptr); break; case Type2: ... Good Luck
1,471,353
1,471,378
What's the C++ equivalent of UINT32_MAX?
In C99, I include stdint.h and that gives me UINT32_MAX as well as uint32_t data type. However, in C++ the UINT32_MAX gets defined out. I can define __STDC_LIMIT_MACROS before including stdint.h, but this does not work if someone is including my header after already including stdint.h themselves. So in C++, what is the standard way of finding out the maximum value representable in a uint32_t?
Not sure about uint32_t, but for fundamental types (bool, char, signed char, unsigned char, wchar_t, short, unsigned short, int, unsigned int, long, unsigned long, float, double and long double) you can use the numeric_limits templates via #include <limits>. cout << "Minimum value for int: " << numeric_limits<int>::min() << endl; cout << "Maximum value for int: " << numeric_limits<int>::max() << endl; If uint32_t is a #define of one of the above than this code should work out of the box cout << "Maximum value for uint32_t: " << numeric_limits<uint32_t>::max() << endl;
1,471,370
1,471,671
Normalizing from [0.5 - 1] to [0 - 1]
I'm kind of stuck here, I guess it's a bit of a brain teaser. If I have numbers in the range between 0.5 to 1 how can I normalize it to be between 0 to 1? Thanks for any help, maybe I'm just a bit slow since I've been working for the past 24 hours straight O_O
Others have provided you the formula, but not the work. Here's how you approach a problem like this. You might find this far more valuable than just knowning the answer. To map [0.5, 1] to [0, 1] we will seek a linear map of the form x -> ax + b. We will require that endpoints are mapped to endpoints and that order is preserved. Method one: The requirement that endpoints are mapped to endpoints and that order is preserved implies that 0.5 is mapped to 0 and 1 is mapped to 1 a * (0.5) + b = 0 (1) a * 1 + b = 1 (2) This is a simultaneous system of linear equations and can be solved by multiplying equation (1) by -2 and adding equation (1) to equation (2). Upon doing this we obtain b = -1 and substituting this back into equation (2) we obtain that a = 2. Thus the map x -> 2x - 1 will do the trick. Method two: The slope of a line passing through two points (x1, y1) and (x2, y2) is (y2 - y1) / (x2 - x1). Here we will use the points (0.5, 0) and (1, 1) to meet the requirement that endpoints are mapped to endpoints and that the map is order-preserving. Therefore the slope is m = (1 - 0) / (1 - 0.5) = 1 / 0.5 = 2. We have that (1, 1) is a point on the line and therefore by the point-slope form of an equation of a line we have that y - 1 = 2 * (x - 1) = 2x - 2 so that y = 2x - 1. Once again we see that x -> 2x - 1 is a map that will do the trick.
1,471,644
1,472,210
Dllimport can't import an old Borland dll
I have a lot of legacy code which I currently compile using an antiquated install of Borland C++ 3.0. There's a rules engine in this code that I'd like to extract and use in a C# .NET application. The thing is, if I extract the rules engine into it's own DLL, I want to be able to call this DLL from both the existing legacy code which I don't have time to port, and from the C# .NET app. If I build a DLL using the old Borland compiler, I can't work out how to reference it from the C# .Net project. DllImport fails with a BadImageFormatException. Googling on this exception indicates that most people encounter this problem when compiling a 64-bit capable program and loading something 32-bit into it. Thing is, I'm reasonably sure I'm generating 16-bit DLLs, and there seems to be no workaround for this. I can download the newer Borland 5 compiler which has a 32-bit compiler and linker, but I'm still getting the same issue, so perhaps I have something wrong there too. This is my C# calling code [DllImport( "C:\\NSDB\\BorlandDLL\\BorlandDLL.dll", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl )] static extern int Version(); public frmHelpAbout() { InitializeComponent(); lblIssueVersion.Text = + Version(); } This is my DLL code int Version() { return 93; } My compiler flags and linker flags are all complete guesswork - I'm hoping that this is my main problem I noticed my DLL code is not decorated with anything like __stdcall, extern "C" or whatever. I can't seem to find the correct set of symbols that Borland C++ 3.0 understands to force the kind of calling conventions I need. So, the questions: 1) Will DllImport ever be able to work with code generated from Borland C++ 3.0 1b) If not, will I be able to port the code to work with the Borland C+ 5.5.1 compiler, and get DllImport to work with that? 2) Can I turn the problem around? If I ported the DLL code into .NET, would I ever be able to get the old Borland code to call it? 3) Do you have any other innovative solutions that will let me simply extract the code I need from this old Borland project?
As far as I know, DllImport will only work for unmanaged dlls that are the same word size as the .Net app. E.g. DllImport in a 64-bit .Net app will only work on 64-bit dlls, a 32-bit .Net app can only load 32-bit dlls, etc. I also don't think it's possible to get DllImport to load a 16-bit dll. Some possible solutions come to mind: Steve mentioned using COM. If you want to keep your .Net app in 64-bit, you could use COM to make things work like this: recompile your C code as a 32-bit dll, use .Net to write a 32-bit COM wrapper for that dll, then have your 64-bit .Net app call the 32-bit COM server, which would in turn call your 32-bit dll. MSDN has some info on interoperating with unmanaged code. Compile both your dll and .Net app for 32-bits. DllImport should be able to load the dll then. (You might need to wrap your C code in extern "C", and run the TDUMP or DUMPBIN utilities on the dll to check for name mangling). If you have all of the C source code, can you just forget about the Borland compiler and build the code with Visual Studio's C++ compiler?
1,471,721
1,471,765
Using dynamic multi-dimensional arrays in c++
I am making a C++ program that checks if given aray is a latin square. I need to use a dynamic multi-dimensional array that stores given latin square. But I cant pass the array to a function that does the checking... Currently I have such code for calling the function: int squaretest(int **p, int n, int sum) { //some code }; And this code is for creating the array: int main() { //some code. n - length of one row, sum - sum of elements in one row. int a; int **lsquare; lsquare = new int*[n]; for (int i=0;i<=n-1;i++) for (int j=0;j<=n-1;j++) { cin >>a; lsquare[i][j] = a; } blocktest(lsquare,n,sum); //some code }; The code compiles (i am using Geany IDE and G++ compiler) but when I run it in terminal, after the first imput, that has to be stored in block[0][0] I get Segmentation fault error. What's wrong with my code and what is the correct sollution?
To be able to do that.. You actually need to do this: int **lsquare = new int*[n]; for (int i=0; i<n; ++i) lquare[i] = new int[n]; for (int i=0; i<n; i++) for (int j=0; j<n; j++) cin >> lsquare[i][j]; blocktest(lsquare,n,sum); The better system would be to do: int *lsquare = new int[n*n]; for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) cin >> lsquare[i + j*n]; blocktest(lsquare, n, sum);
1,471,800
1,471,828
Getting rid of error C2243
Is it possible to getting rid of error C2243? class B {}; class D : protected B {}; D d; B *p = &d; // conversion from 'D *' to 'B &' exists, but is inaccessible I had this error in my app and at the end I've managed to compile it by making an explicit conversion: D d; B *p = (B*)&d; I can't understand why by making class D inherited protected from B makes the implicit conversion inaccessible. I tried to avoid explicit conversion by creating a operator B() in class D in order to make the conversion accessible: class B {}; class D : protected B { public: operator B() {return *this;} }; But there is no way. Any other solution to avoid explicit conversion?
If you want to allow conversion, you should be using public inheritance. Using protected or private inheritance, you are declaring that the fact that the derived type inherits from the base class is a detail that should not be visible from the outside: that's why you are getting that error. You should regard non-public inheritance only as a form of composition with the added possibility to override methods.
1,471,816
1,489,049
Finding type of break in icu::BreakIterator
I'm trying to understang how to use icu::BreakIterator to find specific words. For example I have following sentence: To be or not to be? That is the question... Word instance of break iterator would put breaks there: |To| |be| |or| |not| |to| |be|?| |That| |is| |the| |question|.|.|.| Now, not every pair of break points is actual word. In derived class icu::RuleBasedBreakIterator there is a "getRuleStatus()" that returns some kind of information about break, and it gives "Word status at following points (marked "/")" |To/ |be/ |or/ |not/ |to/ |be/?| |That/ |is/ |the/ |question/.|.|.| But... It all depends on specific rules, and there is absolutely no documentation to understand it (unless I just try), but what would happend with different locales and languages where dictionaries are used? what happens with backware iteration? Is there any way to get "Begin of Word" or "End of Word" information like in Qt QTextBoundaryFinder: http://qt.nokia.com/doc/4.5/qtextboundaryfinder.html#BoundaryReason-enum? How should I solve such problem in ICU correctly?
Have you tried the ICU documentation? It appears to explain everything you are asking about including handling of internationalisation, reverse iteration, and the rules, both default and how to create your own custom set. They also have code snippets to help.
1,472,048
1,472,075
How to append a char to a std::string?
The following fails with the error prog.cpp:5:13: error: invalid conversion from ‘char’ to ‘const char*’ int main() { char d = 'd'; std::string y("Hello worl"); y.append(d); // Line 5 - this fails std::cout << y; return 0; } I also tried, the following, which compiles but behaves randomly at runtime: int main() { char d[1] = { 'd' }; std::string y("Hello worl"); y.append(d); std::cout << y; return 0; } Sorry for this dumb question, but I've searched around google, what I could see are just "char array to char ptr", "char ptr to char array", etc.
y += d; I would use += operator instead of named functions.
1,472,123
1,472,579
Qt signals and slots, threads, app.exec(), and related queries
[related to this question] I wrote this piece of code to understand how qt signals and slots work. I need someone to explain the behaviour, and to tell me if I'm right about my own conclusions. My program: connectionhandler.h #ifndef CONNECTIONHANDLER_H #define CONNECTIONHANDLER_H #include <QTcpServer> class ConnectionHandler : public QObject { Q_OBJECT public: ConnectionHandler(); public slots: void newConn(); private: QTcpServer *server; }; #endif // CONNECTIONHANDLER_H connectionhandler.cpp #include "connectionhandler.h" #include <QTextStream> ConnectionHandler::ConnectionHandler() { server = new QTcpServer; server->listen(QHostAddress::LocalHost, 8080); QObject::connect(server, SIGNAL(newConnection()),this, SLOT(newConn())); } void ConnectionHandler::newConn() { QTextStream out(stdout); out << "new kanneksan!\n"; out.flush(); } main.cpp #include <QCoreApplication> #include "connectionhandler.h" int main(int argc, char* argv[]) { QCoreApplication app(argc,argv); ConnectionHandler handler; return app.exec(); } Now, running this program sends it into an infinite loop looking for new connections. Observation: if I don't call app.exec(), the program returns immediately (as it should). Question: why? Question: if I had connected the slot as a queued connection, when would the slot invocation be performed? Question: if app.exec() is an infinite loop of sorts, how does the newConnection() signal ever get emitted? Big Question: Is their any "second thread" involved here? (I expect a no, and a stunningly elegant explanation :) ) Thanks, jrh PS: who else has this nested parenthesis syndrome? like "(.. :))" or "(.. (..))"?
If you don't call app.exec() then the program hits the end of your main() and ends. (Why? There's no more code to execute!) app.exec() is an infinite loop of the following style: do { get event from system handle event } while (true); If you use a queued connection, then the event is added to your event queue, and it will be performed at some point in the future during the app.exec() loop. There is no second thread in your program. Events are delivered asynchronously by the OS, which is why it appears that there's something else going on. There is, but not in your program.
1,472,330
1,472,402
Encapsulated boost thread_group. Questions about ids and synchronization
I´m using a class that encapsulates a thread_group, and have some questions about it class MyGroup{ private: boost::this_thread::id _id; boost::thread::thread_group group; int abc; //other attributes public: void foo(); }; In the class constructor, i launch N threads for (size_t i=0;i<N;i++){ group.add(new boost::thread(boost::bind(&foo,this))); } void foo(){ _id = boost::this_thread::get_id(); //more code. abc++ //needs to be sync? } So, here are my questions. Do class attributes need to be synchronized? Do every thread get a different id? For example, if I have void bar(){ this->id_; } will this result in different ids for each thread, or the same for everyone? Thanks in advance !
Yes, shared data access must be protected even if you use thread creation helpers as boost. In the end they all will execute the same code at the same time, and there is nothing a library can do to put protection around a variable you own and you manage. If this->_id prints the current thread id then yes, it will print different values while different threads access it.
1,473,107
1,473,252
most effective row removal strategy for QStandardItemModel
I have a QStandardItemModel with several 100,000 records of data, and a QSortFilterProxyModel on top of it for filtering and sorting capabilities. I want to remove a substantial number of records, say 100,000, based on the value of one of the columns. The current implementation iterates over the source model, tests for the value in the appropriate column, and calls removeRow. This turns out to be an extremely slow approach, I don't know why (I've already turned off the signalling of the source model and the sortfilterproxymodel). What is a more efficient approach? Can the QSortFilterProxyModel help, e.g. by creating a selection of records to be deleted, and using removeRows? Thanks, Andreas
QAbstractItemModel::removeRows() is a candidate, provided that the rows are contiguous. If the model is sorted by the column you are using to do the removal test, then you should be able to use this.
1,473,183
1,473,232
What is the best way to find wide string headaches such as L"%s"?
Here is an example of one of the headaches I mean: We have a multiplatform project that uses mostly Unicode strings for rendering text to the screen. On windows in VC++ the line: swprintf(swWideDest, LEN, L"%s is a wide string", swSomeWideString); compiles fine and prints the wide string into the other wide string. However, this should really be: swprintf(swWideDest, LEN, L"%ls is a wide string", swSomeWideString); Without replacing the '%s' with a '%ls' this will not work on other platforms. As testing in our environment on Windows is easier, quicker, and far simpler to debug. These kind of bugs can easily go unnoticed. I know that the best solution is to write correct code in the first place, but under pressure simple mistakes are made, and in this particular case, the mistake can easily go unnoticed for a long time. I suspect there are many variations on this sort of bug, that we are yet to enjoy. Does anyone have a nice and neat way of finding these kind of bugs? : D
As none of the functions of *printf family are typesafe you either search for probable errors via regular expressions and fix them manually use another approach that is typesafe, maybe based on stringstreams or boost.format
1,473,353
1,473,389
Debugging C++ template class in VS 2008
I'm learning C++ and using VS C++ 2008 Express. I have a simple project with 2 code files. One is for my Class and the other is "_tmain()". My class file is using: template <typename T> code. The program seems to run fine, but I can't step into my class file code in c++ view. I have to look at the assembly code. I can step into _tmain() just fine, but when I try F11 to step into my class methods, there is "no source code available". Any ideas on this one? Thanks, M3NTA7
Maybe you just forgot to active debug information (happens if you create an empty project). This can (at least in VS2005) be activated via the Projects Properties -> Configuration Properties -> Linker -> Generate Debug Info.
1,473,487
1,473,833
Debugging MMC (Unmanaged c++)?
I work on a legacy MMC application and one thing I have noticed is that once in awhile when closing the MMC, an error will be reported. "MMC has detected an error in a snap-in. It is recommended that you shut down and restart MMC". How can I debug this? The error is not displayd until you close the console and if you try to attach a debugger, it just exits instantly. Any thoughts?
Why not run the MMC under debugger? Clearly there is something wrong (Unhandled exception probably) with the shutdown code of the snapin. Just run mmc.exe under your favorite debugger and tell the debugger to stop on all exception. attach your snapin exit and wait for the crash. You can try to run ProcDump which can create dump files on Unhandled exception.
1,473,520
1,473,775
how to call a C# dll from unmanaged c++ using IDispatch?
I have a C# dll that I need to call from unmanaged C++. The main problem that I have is that my c++ code corresponds to an excel add-in, that can be installed for excel 2003 and excel 2007, when I install my add-in in excel 2007, and I try to call my C# dll, it works just fine, but for some reason that I still haven't been able to find, in excel 2003 it crashes, excel show me a Runtime Error message, and when debugging my c++ code I can see that the code fails when trying to create an instance of my C# dll, it says that the class is not registered even if I registered with regasm. this is my C# code: namespace ManagedDLL { [ Guid("3C80EE60-D9B8-4daf-89BE-6C7B748F613C"), InterfaceType( ComInterfaceType.InterfaceIsDual), ComVisible(true) ] public interface ICalculator { [DispId(1)] int main(string args, IntPtr _handle); }; [ Guid("5134F342-5B7F-4db2-94F0-F450610419CF"), ProgId("myapp.CCOMEntryPoint"), ClassInterface(ClassInterfaceType.None), ComDefaultInterface(typeof(ICalculator)), ComVisible(true) ] public class COMEntryPoint : ICalculator { public int main(string args, IntPtr _handle) { string[] _args = args.Split(new char[] { ':' }); Program.handle = _handle; return Program.Main(_args); } } } and in C++ what I do is to import the .tlb file that is generated when I use regasm to register my C# dll, like this: \#import "..\bin\release\ManagedDLL.tlb" raw_interfaces_only using namespace ManagedDLL; . . . int callMyDll() { long handle = 0, result = 0; BSTR args; HRESULT hr = CoInitialize(NULL); ICalculatorPtr pICalc(__uuidof(COMEntryPoint)); pICalc->main(bstrStr, handle, &result); return result; } But as I mentioned before, this code doesn't work for excel 2003, so my questions are: I'm I doing something wrong in the way in which I declare my C# dll that is causing me problems in excel 2003? Just as it is now, can my C# dll be considered an ActiveX object? How can I call my C# dll in another way from c++? like using IDIspatch for example Thanks
I've had a similar problem before. I wasn't calling C# from C++, but the concept is the same. I had to load a .NET dll into a host application via COM, which looks like what you are trying to do. The problem was the host application (in your case excel) was loading the .NET runtime 1.1. Our dll was compiled for .NET 2.0. It could be that Excel 2003 is loading the 1.1 runtime and 2007 loads a more recent version. Check out this forum this: Excel selects wrong .NET runtime. You could also test this by using MSBee to target the 1.1 runtime and then try load your dll in Excel 2003.
1,473,921
1,473,980
optimizing branching by re-ordering
I have this sort of C function -- that is being called a zillion times: void foo () { if (/*condition*/) { } else if(/*another_condition*/) { } else if (/*another_condition_2*/) { } /*And so on, I have 4 of them, but we can generalize it*/ else { } } I have a good test-case that calls this function, causing certain if-branches to be called more than the others. My goal is to figure the best way to arrange the if statements to minimize the branching. The only way I can think of is to do write to a file for every if condition branched to, thereby creating a histogram. This seems to be a tedious way. Is there a better way, better tools? I am building it on AS3 Linux, using gcc 3.4; using oprofile (opcontrol) for profiling.
It's not portable, but many versions of GCC support a function called __builtin_expect() that can be used to tell the compiler what we expect a value to be: if(__builtin_expect(condition, 0)) { // We expect condition to be false (0), so we're less likely to get here } else { // We expect to get here more often, so GCC produces better code } The Linux kernel uses these as macros to make them more intuitive, cleaner, and more portable (i.e. redefine the macros on non-GCC systems): #ifdef __GNUC__ # define likely(x) __builtin_expect((x), 1) # define unlikely(x) __builtin_expect((x), 0) #else # define likely(x) (x) # define unlikely(x) (x) #endif With this, we can rewrite the above: if(unlikely(condition)) { // we're less likely to get here } else { // we expect to get here more often } Of course, this is probably unnecessary unless you're aiming for raw speed and/or you've profiled and found that this is a problem.
1,473,977
1,473,987
Hanging else problem?
What is the "hanging else" problem? (Is that the right name?) Following a C++ coding standard (forgot which one) I always use brackets (block) with control structures. So I don't normally have this problem (to which "if" does the last(?) else belong), but for understanding possible problems in foreign code it would be nice with a firm understanding of this problem. I remember reading about it in a book about Pascal many years ago, but I can't find that book.
Which if does the else belong to? if (a < b) if (c < d) a = b + d; else b = a + c; (Obviously you should ignore the indentation.) That's the "hanging else problem". C/C++ gets rid of the ambiguity by having a rule that says you can't have an-if-without-an-else as the if-body of an-if-with-an-else.
1,473,983
1,474,510
Is there a way to figure out the top callers of a C function?
Say I have function that is called a LOT from many different places. So I would like to find out who calls this functions the most. For example, top 5 callers or who ever calls this function more than N times. I am using AS3 Linux, gcc 3.4. For now I just put a breakpoint and then stop there after every 300 times, thus brute-forcing it... Does anyone know of tools that can help me? Thanks
I wrote call logging example just for fun. A macro change the function call with an instrumented one. include <stdio.h>. int funcA( int a, int b ){ return a+b; } // instrumentation void call_log(const char*file,const char*function,const int line,const char*args){ printf("file:%s line: %i function: %s args: %s\n",file,line,function,args); } #define funcA(...) \ (call_log(__FILE__, __FUNCTION__, __LINE__, "" #__VA_ARGS__), funcA(__VA_ARGS__)). // testing void funcB(void){ funcA(7,8); } int main(void){ int x = funcA(1,2)+ funcA(3,4); printf( "x: %i (==10)\n", x ); funcA(5,6); funcB(); } Output: file:main.c line: 22 function: main args: 1,2 file:main.c line: 24 function: main args: 3,4 x: 10 (==10) file:main.c line: 28 function: main args: 5,6 file:main.c line: 17 function: funcB args: 7,8
1,474,416
1,474,421
C++ Passing a class as a parameter
I'm wondering if it's possible to pass a class as a parameter in c++. Not passing a Class Object, but the class itself which would allow me to use this class like this. void MyFunction(ClassParam mClass) { mClass *tmp = new mClass(); } The above is not real code, but it hopefully explains what I'm trying to do in an example.
You can use templates to accomplish something similar (but not exactly that): template<class T> void MyFunction() { T *tmp = new T(); } and call it with MyFunction<MyClassName>(). Note that this way, you can't use a "variable" in place of T. It should be known at compile time.
1,474,417
1,474,448
Typedef a template class without specifying the template parameters
I'm trying to typedef either an unordered_map or std::map depending whether there are TR1 libraries available. But I don't want to specify the template parameters. From what i've read so far, typedef'ing templates without arguments is not possible until official c++0x standard is available. So does anyone know an elegant workaround for this? #ifdef _TR1 #include <unordered_map> typedef std::tr1::unordered_map MyMap; //error C2976: too few template arguments #else #include <map> typedef std::map MyMap; //error C2976: too few template arguments #endif
The way I've seen this done is to wrap the typedef in a template-struct: template<typename KeyType, typename MappedType> struct myMap { #ifdef _TR1 typedef std::tr1::unordered_map<KeyType, MappedType> type; #else typedef std::map<KeyType, MappedType> type; #endif }; Then in your code you invoke it like so: myMap<key, value>::type myMapInstance; It may be a little more verbose than what you want, but I believe it meets the need given the current state of C++.
1,474,790
1,474,819
How to read-write into/from text file with comma separated values
How do I read data from a file if my file is like this with comma separated values 1, 2, 3, 4, 5\n 6, 7, 8, 9, 10\n \n and after reading the file, I want to write the data back into other file as same format above. I can get total number of lines, using string line; while(!file.eof()){ getline(file,line); numlines++; } numline--; // remove the last empty line but how can I know total number of digits in a row/line ?? I also have vector of ints to store the data. So, I want to read the first line and then count total number of elements in that line, here 5 (1,2,3,4,5) and store them in array/vector, and read next line and store them in vector again and so on till I reach EOF. Then, I want to write the data to file, again, I guess this will do the job of writing data to file, numOfCols=1; for(int i = 0; i < vector.size(); i++) { file << vector.at(i); if((numOfCols<5) file << ",";//print comma (,) if((i+1)%5==0) { file << endl;//print newline after 5th value numOfCols=1;//start from column 1 again, for the next line } numOfCols++; } file << endl;// last new line So, my main problem is how to read the data from file with comma separated values ?? Thanks
Step 1: Don't do this: while(!file.eof()) { getline(file,line); numlines++; } numline--; The EOF is not true until you try and read past it. The standard pattern is: while(getline(file,line)) { ++numline; } Also note that std::getline() can optionally take a third parameter. This is the character to break on. By default this is the line terminator but you can specify a comma. while(getline(file,line)) { std::stringstream linestream(line); std::string value; while(getline(linestream,value,',')) { std::cout << "Value(" << value << ")\n"; } std::cout << "Line Finished" << std::endl; } If you store all the values in a single vector then print them out using a fixed width. Then I would do something like this. struct LineWriter { LineWriter(std::ostream& str,int size) :m_str(str) ,m_size(size) ,m_current(0) {} // The std::copy() does assignement to an iterator. // This looks like this (*result) = <value>; // So overide the operator * and the operator = to LineWriter& operator*() {return *this;} void operator=(int val) { ++m_current; m_str << val << (((m_current % m_size) == 0)?"\n":","); } // std::copy() increments the iterator. But this is not usfull here // so just implement too empty methods to handle the increment. void operator++() {} void operator++(int) {} // Local data. std::ostream& m_str; int const m_size; int m_current; }; void printCommaSepFixedSizeLinesFromVector(std::vector const& data,int linesize) { std::copy(data.begin(),data.end(),LineWriter(std::cout,linesize)); }
1,474,894
1,474,953
Why isn't the [] operator const for STL maps?
Contrived example, for the sake of the question: void MyClass::MyFunction( int x ) const { std::cout << m_map[x] << std::endl } This won't compile, since the [] operator is non-const. This is unfortunate, since the [] syntax looks very clean. Instead, I have to do something like this: void MyClass::MyFunction( int x ) const { MyMap iter = m_map.find(x); std::cout << iter->second << std::endl } This has always bugged me. Why is the [] operator non-const?
For std::map and std::unordered_map, operator[] will insert the index value into the container if it didn't previously exist. It's a little unintuitive, but that's the way it is. Since it must be allowed to fail and insert a default value, the operator can't be used on a const instance of the container. http://en.cppreference.com/w/cpp/container/map/operator_at
1,474,990
2,213,169
How do you use a variable stored in a boost spirit closure as input to a boost spirit loop parser?
I would like to use a parsed value as the input to a loop parser. The grammar defines a header that specifies the (variable) size of the following string. For example, say the following string is the input to some parser. 12\r\nTest Payload The parser should extract the 12, convert it to an unsigned int and then read twelve characters. I can define a boost spirit grammar that compiles, but an assertion in the boost spirit code fails at runtime. #include <iostream> #include <boost/spirit.hpp> using namespace boost::spirit; struct my_closure : public closure<my_closure, std::size_t> { member1 size; }; struct my_grammar : public grammar<my_grammar> { template <typename ScannerT> struct definition { typedef rule<ScannerT> rule_type; typedef rule<ScannerT, my_closure::context_t> closure_rule_type; closure_rule_type header; rule_type payload; rule_type top; definition(const my_grammar &self) { using namespace phoenix; header = uint_p[header.size = arg1]; payload = repeat_p(header.size())[anychar_p][assign_a(self.result)]; top = header >> str_p("\r\n") >> payload; } const rule_type &start() const { return top; } }; my_grammar(std::string &p_) : result(p_) {} std::string &result; }; int main(int argc, char **argv) { const std::string content = "12\r\nTest Payload"; std::string payload; my_grammar g(payload); if (!parse(content.begin(), content.end(), g).full) { std::cerr << "there was a parsing error!\n"; return -1; } std::cout << "Payload: " << payload << std::endl; return 0; } Is it possible to tell spirit that the closure variable should be evaluated lazily? Is this behaviour supported by boost spirit?
This is much easier with the new qi parser available in Spirit 2. The following code snippet provides a full example that mostly works. An unexpected character is being inserted into the final result. #include <iostream> #include <string> #include <boost/version.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/qi_repeat.hpp> #include <boost/spirit/include/qi_grammar.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> using boost::spirit::qi::repeat; using boost::spirit::qi::uint_; using boost::spirit::ascii::char_; using boost::spirit::ascii::alpha; using boost::spirit::qi::_1; namespace phx = boost::phoenix; namespace qi = boost::spirit::qi; template <typename P, typename T> void test_parser_attr( char const* input, P const& p, T& attr, bool full_match = true) { using boost::spirit::qi::parse; char const* f(input); char const* l(f + strlen(f)); if (parse(f, l, p, attr) && (!full_match || (f == l))) std::cout << "ok" << std::endl; else std::cout << "fail" << std::endl; } static void straight_forward() { std::string str; int n; test_parser_attr("12\r\nTest Payload", uint_[phx::ref(n) = _1] >> "\r\n" >> repeat(phx::ref(n))[char_], str); std::cout << "str.length() == " << str.length() << std::endl; std::cout << n << "," << str << std::endl; // will print "12,Test Payload" } template <typename P, typename T> void test_phrase_parser(char const* input, P const& p, T& attr, bool full_match = true) { using boost::spirit::qi::phrase_parse; using boost::spirit::qi::ascii::space; char const* f(input); char const* l(f + strlen(f)); if (phrase_parse(f, l, p, space, attr) && (!full_match || (f == l))) std::cout << "ok" << std::endl; else std::cout << "fail" << std::endl; } template <typename Iterator> struct test_grammar : qi::grammar<Iterator, std::string(), qi::locals<unsigned> > { test_grammar() : test_grammar::base_type(my_rule) { using boost::spirit::qi::_a; my_rule %= uint_[_a = _1] >> "\r\n" >> repeat(_a)[char_]; } qi::rule<Iterator, std::string(), qi::locals<unsigned> > my_rule; }; static void with_grammar_local_variable() { std::string str; test_phrase_parser("12\r\nTest Payload", test_grammar<const char*>(), str); std::cout << str << std::endl; // will print "Test Payload" } int main(int argc, char **argv) { std::cout << "boost version: " << BOOST_LIB_VERSION << std::endl; straight_forward(); with_grammar_local_variable(); return 0; }
1,475,016
1,475,038
How do I automatically clean up code in C++?
I'm working as a TA in an introductory programming class, and the students tend to submit their programs as either one line, or without any indentation. Is there any tool that allows me to insert indents and things like that automatically? (We're using C++ and VisualStudio)
Select the entire file (Ctrl-A) and then hit Ctrl-K Ctrl-F, which is essentially format the entire document. EDIT: Of course in Visual Studio IDE
1,475,021
1,475,045
Normal looking button with c++ / win32
I'm trying to make a button but it always looks like windows 95 flat button. How do I make it look vista style? hWndEdit = CreateWindowA("button", "Test", WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON, 100, 20, 140, 20, hWnd, NULL, NULL, NULL); Where ami I going wrong? Thanks
It can only look Vista style in Vista, mind you. Your application must also embed a manifest as per http://msdn.microsoft.com/en-us/library/aa289524(v=VS.71).aspx to enable visual styles.
1,475,415
1,490,594
Having trouble building c++ project in Eclipse CDT in OS X for a silly reason
I'm trying to build a very simple c++ program in eclipse and I'm getting a very silly error: **** Internal Builder is used for build **** g++ -O0 -g3 -Wall -c -fmessage-length=0 -oMyFirst.o ../MyFirst.cpp g++ -oLinkedLists MyFirst.o ld: unknown option: -oLinkedLists collect2: ld returned 1 exit status Build error occurred, build is stopped Time consumed: 403 ms. The problem is that g++ in osx does not like the -o flag in the "g++ -oLinkedLists MyFirst.o" command right next to the executable file name... Does anybody know how to either configure g++ to accept that or how to configure the builder in eclipse such that there's a space between the -o flag and and file name like this: "g++ -o LinkedLists MyFirst.o"? Thx in advance!
Mark actually pointed me in the right direction but what I had to do to make it work was to go to: Project >> Properties >> C/C++ Build >> Tool Chain Editor I then changed the "Current toolchanin" select box to "MacOSX gcc" and that fixed it :)
1,475,662
1,475,726
How to get Process in windows mobile
i want to get the running process in .net compact framework windows mobile.. i want to kill the running process.. but i know process.GetProcessesByName() function is present in desktop, but for mobile its not supported i think so.. please let me know how to kill the presently running process in c# windows mobile. Thanks
Hey i found answer here it is Process.GetCurrentProcess().Kill(); .net CF is crazy :-)
1,475,782
1,477,583
Qt4.5: Implicitly shared QImage: are methods like .bits() always copying (documentation unclarity)
I am writing a Qt application that has to handle big QImage s. QImage uses implicit sharing, which means it reference counts an internal data pointer. Whenever the refcount is > 1 the object counts as "shared" and any even only potentially data modifying call issues a deep copy of the image data. In short: I don't want deep copies to happen. I make a number of calls like setPixel(), bits() etc. that can trigger a copy. The documentation sometimes reads as if certain calls would always trigger a deep copy (detach call) even if I try my hardest to keep the refcount at 1. Like here: QImage::setPixel() So I want to know: Is the doc only formulated a bit clumsily and these calls are reliably copying only shared objects (as in refcount > 1)? Can I ask an object what it's current refcount is, for debugging reasons and the like? Can I force Qt not to implicitly share specific objects/instances (<- well here my educated guess is "no")
Operations that could modify the shared instance will detach. setPixel detaches. Try QImage::isDetached() which does a return d && d->ref == 1;. By using a debugger, you can get to the actual refcount. Other than passing by reference/shared pointer no.
1,475,940
1,475,967
Qt library MainWindow destructor
Im new to the Qt library and i was going through the demonstrations. I came across this class without a destructor.... this is the cpp file https://docs.huihoo.com/qt/4.5/demos-mainwindow-mainwindow-cpp.html and here is the .h file https://docs.huihoo.com/qt/4.5/demos-mainwindow-mainwindow-h.html the constructor uses the new operator but the class doesn't have a destructor. Am I missing something?
Yes you are. Qt provides parent-child relationship. When a QObject is deleted, it deletes all of its children automatically. In the line below, a QTextEdit is created with this pointer as its parent. center = new QTextEdit(this); So, when the parent (MainWindow) is deleted, center is automatically deleted too. Take a look at the QObject documentation.
1,475,992
1,476,004
C++ thinks '<<' is not a member of class, but it is
I have to write a simple log class, that would write the output to a file. I want it to work with overloading the << operator, so I can do this: MyLog log("C:\\log.txt"); log<<"Message"; But Visual C++ tells me: "error C2039: '<<' : is not a member of 'MyLog' " I don't know what I am doing wrong. Here is the code: MyLog.h #pragma once #include <iostream> #include <conio.h> #include <fstream> using namespace std; class MyLog { private: ofstream logfile; public: MyLog(char* filename); friend MyLog& operator<<(MyLog& l,char*msg); }; MyLog.cpp #include "MyLog.h" MyLog::MyLog(char* filename) { logfile.open(filename); } MyLog& MyLog::operator<<(MyLog& l,char*msg) { cout<<msg; return l; } Does anyone know what is wrong?
You have declared the free function MyLog& operator<<(MyLog& l,char* msg) to be a friend of the MyLog class. It is not a member of the class itself, so your definition of the function should start with this: MyLog& operator<<(MyLog& l,char* msg) { //...
1,476,794
1,477,158
Cocoa counterpart to Windows' SetTimer
Is there any equivalent function on OS X to SetTimer in Windows? I'm using C++. So I'm writing a plugin for some software, and I need to have a function called periodically. On Windows I just pass the address of the function to SetTimer() and it will be called at a given interval. Is there an easy way to do this on OS X? It should be as minimalistic as possible. I didn't really find anything non-fancy on the web, there was something about a huge framework and another solution using a second thread that is sleeping the other time, but I think there should be an easier way.
Consider using the Boost Asio library. The class deadline_timer works on all platforms. Just use bind to attach a function to async_wait and call expires_from_now. io_service io; deadline_timer timer(io); void handler() { static int second_counter = 0; cout << second_counter++ << endl; timer.expires_from_now(posix_time::seconds(1)); timer.async_wait(bind(&handler)); } int main(int argc, char* argv[]) { handler(); io.run(); } It'll take a little time to get your head around Asio (especially since the documentation is...patchy) but it's well worth learning.
1,477,072
1,477,134
Behavior of C++ after destruction
I have an object that reads from a socket continuously like below: void CSocketReader::ReadComplete ( ) { messageProcessor->ResponseReceived ( response ); read (); } void CSocketReader::read() { socket.read(response); } My problem is, depending on the response and on the protocol that I am executing the ResponseReceived method could lead to deletion of the CSocketReader object. When the ResponseReceived method returns the object the this pointer points to would have been deleted ( but for some reason not known to me the this pointer is not NULL even after its deleted!! ). Next the read method executes and the program crashes within read. How can I reliably detect that the method that's been executing on an object has been deleted. Please help.
How can I reliably detect that the method that's been executing on an object has been deleted. You can't set a 'bool amDeleted' flag inside the object itself (because after it's deleted that flag/memory may be reused/overwritten by something else). The only reliable way to do it (that I can think of) would be like this ... class Foo { //have a static set of all valid Foo instance pointers typedef std::set<Foo*> Set; static Set s_set; public: Foo() { s_set.insert(this); } //ditto in every other Foo constructor, including the copy constructor ~Foo() { s_set.remove(this); } private: static bool exists(Foo* foo) { return s_set.find(foo) != s_set.end(); } }; [... or a thread-safe Set if Foo is being constructed/run/destroyed off more than one thread].
1,477,145
1,477,177
Reducing code duplication between operator= and the copy constructor
I have a class that requires a non-default copy constructor and assignment operator (it contains lists of pointers). Is there any general way to reduce the code duplication between the copy constructor and the assignment operator?
There's no "general way" for writing custom copy constructors and assignment operators that works in all cases. But there's an idiom called "copy-&-swap": class myclass { ... public: myclass(myclass const&); void swap(myclass & with); myclass& operator=(myclass copy) { this->swap(copy); return *this; } ... }; It's useful in many (but not all) situations. Sometimes you can do better. A vector or a string could have a better assignment which reuses allocated storage if it was large enough.
1,477,197
1,477,543
How to change an object's interface based on its state?
Given a fairly complex object with lots of state, is there a pattern for exposing different functionality depending on that state? For a concrete example, imagine a Printer object. Initially, the object's interface lets you query the printer's capabilities, change settings like paper orientation, and start a print job. Once you start a print job, you can still query, but you can't start another job or change certain printer settings. You can start a page. Once you start a page, you can issue actual text and graphics commands. You can "finish" the page. You cannot have two pages open at once. Some printer settings can be changed only between pages. One idea is to have one Printer object with a large number of methods. If you call a method at an inappropriate time (e.g., try to change the paper orientation in the middle of a page), the call would fail. Perhaps, if you skipped ahead in the sequence and start issuing graphics calls, the Printer object could implicitly call the StartJob() and StartPage() methods as needed. The main drawback with this approach is that it isn't very easy for the caller. The interface could be overwhelming, and sequence requirements aren't very obvious. Another idea is to break things up into separate objects: Printer, PrintJob, and Page. The Printer object exposes the query methods and a StartJob() method. StartJob() returns a PrintJob object that has Abort(), StartPage(), and methods for changing just the changeable settings. StartPage() returns a Page object that offers an interface for making the actual graphics calls. The drawback here is one of mechanics. How do you expose the interface of an object without surrendering control of that object's lifetime? If I give the caller a pointer to a Page, I don't want them to delete it, and I can't give them another one until they return the first. Don't get too hung up on the printing example. I'm looking for the general question of how to present different interfaces based on the object's state.
How do you expose the interface of an object without surrendering control of that object's lifetime? If I give the caller a pointer to a Page Just to address this point in particular, aside from the rest of the question. You seem to be talking about an API that looks a bit like this: Page *Printer::newPage(); I would recommend against that, and in favour of a constructor that looks like this: Page::Page(Printer &); That is, do not allocate a Page object in the printer, return it to the caller, and then have to worry about object lifecycle. Instead, surrender control of the lifecycle of objects as a matter of principle, to give your users flexibility. You want the user to start a page, draw stuff to it, then finish the page. So let them do exactly that: create a Page object, draw stuff, see whether it worked, perhaps provide flush and cancel functions, perhaps even also blockUntilDonePrinting and getFailureCode and so on. Then when they're done with the Page they destroy it (or, more likely, they just let it fall out of scope), and then they can create another. If you do need factories: Page *PageFactory::newPage(Printer &); Either way, have the Page itself know what to do with a Printer in order to print things. A Printer is not the same thing as a factory for Pages. Well, actually, it literally is in the real world, but that doesn't mean it should be in software too, since our Page object is not actually a physical page, it's the process of drawing a page. If our Page object just represented a page, then it wouldn't need to interact with the printer object at all - we could construct our Pages, serialise them to postscript, and then worry about how the Printer prints them. Anyway, the Printer could serve double-duty as a PageFactory, but there are two separate concerns here: (1) manage access to a hardware resource that prints things, and (2) manage the workflow of users creating printable objects in software. Printer doesn't need to do both, so you could separate them. Likewise for any object with states - separate the object itself (having two or more states), from a session or workflow which progresses through those states. I don't want them to delete it It's perfectly fine for an API to say, "the user must not delete the referand of the pointer returned by newPage, but instead must call Printer::close(Page *) with the pointer as a parameter". But as I say in C++, unlike C, you don't have to create APIs like that. I can't give them another one until they return the first. I would try to design out this restriction (print queue, anybody?), so that although only one Page is actually printing at any one time, multiple Pages can be created and simultaneously communicate with the Printer driver. But printing is just the example. If a Page really does require exclusive use of the Printer throughout the Page's life (as for example would be the case if we were talking about Mutex and MutexSession rather than Printer and Page), then the Printer should have an API (perhaps public, perhaps accessed via friend, according to whether the Page implementation is intended to be unique for the Printer implementation). Page uses this to acquire exclusive access (call it the "printer token"). If you try to create a Page when another one already exists with the same Printer, then that fails (or blocks, or whatever is appropriate for the problem domain).
1,477,199
1,481,426
transparent icons on toolbar draw ugly borders
I'm trying to set transparent icons in a QAction, which is then added to a Menu and a toolbar. I'm styling the application with a style sheet. The icon transparency works, but the icons are being drawn on the toolbar with what looks like a 1px black border on the left and top edges of the icons. Now, all my icons are stored in one large image file (PNG, with transparency) - they're saved in one large strip. To extract them into a single QIcon, I do this: // load icon strip: QPixmap large; large.load(":/icons/tb_icons_l.png", "PNG", Qt::OrderedAlphaDither); QSize largeSize(large.width() / ICON_COUNT, large.height()); // create individual icon pixmap QPixmap iconLarge(largeSize); // fill with transparent pixels: iconLarge.fill(QColor(0,0,0,0)); // copy pixel data from icon strip to image: { QPainter p(&iconLarge); p.setBackgroundMode(Qt::TransparentMode); p.drawPixmap(0,0,large, largeSize.width() * i, 0, largeSize.width(), largeSize.height()); // 'i' is the icon index. } return QIcon(iconLarge); I know the problem is in the few lines above, since when I load icons from individual files instead this all works perfectly ( no black border). Has anyone else seen anything like this before? Can anyone suggest some changes that will remove the unsightly black border? The border is definitely part of the image, rather than part of the toolbar button itself.
First of all, I think you're doing things in an unnecessarily complicated way by having them all in one image. However... What version of Qt are you running? On what platform? At one point about 6-12 months ago (I think), I encountered a bug with drawing one transparent image on top of another transparent image as QPixmaps. Some of the pixels turned other colors, somewhat randomly as far as I could tell. This was on Linux, with either Qt4.4 or 4.5 (I can't remember). Whichever one it was, I submitted a bug report, and it was acknowledged as a regression and fixed in the next bug-fix release. That means if you aren't running with the latest version, you might do well to update to the latest. (The work-around was to draw onto a QImage, then convert it to a QPixmap when needed.) Alternately, you could try a test where you get rid of the indexing, and just load an image that you know the size of into the painter, to see if you can simplify your code and still reproduce the problem.
1,477,239
1,477,283
LPTHREAD_START_ROUTINE / array of classes
I wrote some test code like this which compiled and worked fine... void threadtest() { HANDLE hThrd; DWORD threadId; int i; for (i = 0;i < 5;i++) { hThrd = CreateThread( NULL, 0, ThreadFunc, (LPVOID)i, 0, &threadId ); } // more stuff } DWORD WINAPI ThreadFunc(LPVOID n) { // stuff return 0; } Then I wanted to modify the code to put the ThreadFunc inside a class and then declare an array of those classes. I thought the code should look like this: class thread_type { public: DWORD WINAPI ThreadFunc(LPVOID n) { // stuff return 0; } }; void threadtest() { HANDLE hThrd; DWORD threadId; int i; thread_type *slave; slave = new thread_type[5]; for (i = 0;i < 5;i++) { hThrd = CreateThread( NULL, 0, slave[i].ThreadFunc, (LPVOID)i, 0, &threadId ); } // more stuff } Unfortunately the compiler complains about the line slave[i].ThreadFunc, I think I may need some special casting but all the permutations I try involving "::" and "&" seem to fail (I'm quite new to C++). The real code has some additional complications which I haven't included for clarity, but I think they are irrelevant.
The following explains the difference between a pointer to a function and a pointer to a member function C++ FAQ Lite. See section 33.2 which explains why what you are doing is a bad idea.
1,477,602
1,477,703
C++ Circular declaration
I have a couple of cases of circular declaration in my class delaractions in my main (global) header. #include <cstdlib> #include <iostream> using namespace std; enum piece_t {BLACK, WHITE, EMPTY, WALL}; //wall is area out side of board (board array is 21x21 but only 19x19 is playable) enum dir_t {ABOVE,BELOW,LEFT, RIGHT}; //shall i overload ! or - operatior? !LEFT==RIGHT? struct nextPoint_t //should be implimented with references, but need to practice pointer { point_t* above; point_t* below; point_t* left; point_t* right; }; class point_t { private: piece_t mType; //what sort of point this is int mLiberties; nextPoint_t mAdjacent; // points to adjacent points bool mLibertiesCounted; // keeps track of if liberties have been counted, for mCountLiberites() (sets), is reset by mUpdateLiberites(); int mCountLiberties(); //counts this point's liberites, by calling count on mAdjacent points etc. void mSetPos(int xPos, int yPos, board_t theBoard); //sets up mAdjacent to point to adjacent points, void mSetStructureLiberties(int numLibs); // Sets this squares liberites then calls this on all adjacent squares public: point_t ();// parameterless constructor, for arrays void mSetUp(int xPos, int yPos, board_t theBoard);// sets up mType then calles setPos iFF not WALL type point_t (int xPos, int yPos, board_t theBoard); //constructor, takes it's position in the grid as a parameter void mUpdateLiberties(); // calles countLiberties then, updates liberites on whole of connected structure, by operating pon all conencted points }; class board_t { private: point_t mArray [21][21]; public: board_t(); //constructor, sets up board by operating on the point_t's }; Don't worry about the comments there for my reading, I know what I mean. I thought I could fix it with forward declarations, but they don't seem to work, it just thinks I'm redeifining the classes
The forward references in your code seems to be to board_t and point_t, which is resolved by forward declaring them. Since you reference board_t in member function declarations of point_t, you cannot define the member functions right away in point_t. Their definitions have to appear after board_t is defined. So you have to either move the definition of the functions into the cpp file, or you have to move their definition in the header after definition of board_t whichever suites you more. point_t is only used as a pointee type in nextPoint_t, so we don't have the same problem for it here: class point_t; // used by nextPoint_t class board_t; // used by point_t struct nextPoint_t //should be implimented with references, but need to practice pointer { point_t* above; // goes without problems - doesn't need definition of point_t point_t* below; point_t* left; point_t* right; }; class point_t { private: piece_t mType; int mLiberties; nextPoint_t mAdjacent; bool mLibertiesCounted; int mCountLiberties(); void mSetPos(int xPos, int yPos, board_t theBoard); void mSetStructureLiberties(int numLibs); public: point_t (); void mSetUp(int xPos, int yPos, board_t theBoard); point_t (int xPos, int yPos, board_t theBoard); void mUpdateLiberties(); }; class board_t { private: point_t mArray [21][21]; public: board_t(); }; Definition at the end of the header looks like // define it either inline in the header, or non-inline in a cpp file inline void point_t::mSetPos(int xPos, int yPos, board_t theBoard) { /* some work... */ } // same for mSetUp... Nonetheless i would recommend you to use const references to pass the board to point_t's member functions, but this is not a requirement for your code to work. Declarations go fine with incomplete parameter types.
1,478,003
1,478,049
How to detect whether a monitor is widescreen in Windows
I need a way to programatically detect whether the monitor is wide or not, in Windows. GetSystemMetrics returns the size of the desktop, which sort of works, but if an user has a widescreen monitor at, say, 1024x768, I'll incorrectly classify it as non-wide. GetDeviceCaps has similar problems with HORZRES and VERTRES, and even HORZSIZE AND VERTSIZE give incorrect results when a non-wide resolution is used in a wide monitor. Is there any way to detect this reliably?
You might be able to get the actual physical size through EDID. See here: How to obtain the correct physical size of the monitor?
1,478,092
1,478,119
C++ pragma GCC system_header directive
What this C++ directive do: "#pragma GCC system_header"?
I googled and got this: #pragma GCC system_header This pragma takes no arguments. It causes the rest of the code in the current file to be treated as if it came from a system header. Section 2.7 System Headers. More info on System headers 2.7. System Headers The header files declaring interfaces to the operating system and runtime libraries often cannot be written in strictly conforming C. Therefore, GCC gives code found in system headers special treatment. All warnings, other than those generated by #warning (Chapter 5 Diagnostics), are suppressed while GCC is processing a system header. Macros defined in a system header are immune to a few warnings wherever they are expanded. This immunity is granted on an ad-hoc basis, when we find that a warning generates lots of false positives because of code in macros defined in system headers. Normally, only the headers found in specific directories are considered system headers. These directories are determined when GCC is compiled. There are, however, two ways to make normal headers into system headers. The -isystem command line option adds its argument to the list of directories to search for headers, just like -I. Any headers found in that directory will be considered system headers. All directories named by -isystem are searched after all directories named by -I, no matter what their order was on the command line. If the same directory is named by both -I and -isystem, the -I option is ignored. GCC provides an informative message when this occurs if -v is used. There is also a directive, #pragma GCC system_header, which tells GCC to consider the rest of the current include file a system header, no matter where it was found. Code that comes before the #pragma in the file will not be affected. #pragma GCC system_header has no effect in the primary source file. On very old systems, some of the pre-defined system header directories get even more special treatment. GNU C++ considers code in headers found in those directories to be surrounded by an extern "C" block. There is no way to request this behavior with a #pragma, or from the command line.
1,478,330
1,478,344
C++ STL map with a custom class as second type
I'd like to create a map with an int and my own custom class. Is there a way to do this? map<int, MyClass> myMap; If not, how do I go about accomplishing this? Basically, I want an id(or preferably an enum) to point to my own custom class. In most other languages, this would be a simple hash.
#include <map> std::map<int, MyClass> myMap; MyClass foo; myMap[5] = foo; myMap[5].bar = 10; You do need MyClass to be default- and copy- constructible, so it can be created (if you use, e.g., myMap[5]) and copied into the map.
1,478,355
1,478,377
Programmatically block screen saver in Mac OSX
Is it possible to programatically ask Mac OS X not to turn on the screen saver while your application is active?
You want to use: UpdateSystemActivity(UsrActivity); Here is Apple's example code. Be aware this is deprecated for 64bit binaries, and I have not found a suitable replacement, but the struggle continues.
1,478,734
1,479,089
Matrix Circular Shift
Does anyone know an efficient way to right circular-shift a matrix? Btw, the matrix is binary but a method to solve a non-binary matrix is also fine. Right now, I'm thinking of implementing a circular array for the rows of my matrix and updating each row whenever a shift operation is required. Another method, I was considering was implementing a vector of pointers to columns (of the matrix) represented by vectors and swapping them around when a shift operation occurs. E.g. 1 2 3 4 5 6 7 8 9 Right-shift 3 1 2 6 4 5 9 7 8 Another problem arises with all these solutions if I need to shift the matrix down as well. To implement both operations efficiently, is completely beyond me. Down-shift 9 7 8 3 1 2 6 4 5
Something like this perhaps, class matrix { std::vector<bool> elements; int rows, cols, row_ofs, col_ofs; std::size_t index(int r, int c) { r = (r + row_ofs) % rows; c = (c + col_ofs) % cols; return std::size_t(r)*cols + c; // row major layout } public: matrix() : rows(0), cols(0) {} matrix(int r, int c) : elements(std::size_t(r)*c), rows(r), cols(c) {} int num_rows() const { return rows; } int num_cols() const { return cols; } std::vector<bool>::reference operator()(int r, int c) { return elements.at(index(r,c)); } bool operator()(int r, int c) const { return elements.at(index(r,c)); } void rotate_left() { col_ofs = (col_ofs+1 ) % cols; } void rotate_right() { col_ofs = (col_ofs+cols-1) % cols; } void rotate_up() { row_ofs = (row_ofs+1 ) % rows; } void rotate_down() { row_ofs = (row_ofs+rows-1) % rows; } }; (untested) Edit: Here's an alternative: Use std::deque<std::deque<T> > internally. ;-) Yes, it does support random access. A deque is not a list. Plus, you don't need to bother anymore with the modulo arithmetic.
1,479,100
1,479,106
How is if statement evaluated in c++?
Is if ( c ) the same as if ( c == 0 ) in C++?
No, if (c) is the same as if (c != 0). And if (!c) is the same as if (c == 0).
1,479,117
1,479,145
how to overload > operator for a queue
i have a priority queue and i have defined like this: priority_queue<Node*,vector<Node*>,greater<Node*>> myQueue; i have to add to queue on the basis of a parameter param and i have overloaded it like this bool Node::operator>(const Node& right) const { return param>right.param; } since the overload function doesnt take a pointer object, how should i change it so that my overloaded function is called. i am adding to queue this way: Node *myNode myQueue.add(myNode); i cant pass the myNode without making as pointer object. please guide .. @Sellibitze i have done something like this template<typename Node, typename Cmp = std::greater<Node> > struct deref_compare : std::binary_function<Node*,Node*,bool> { deref_compare(Cmp const& cmp = Cmp()) : cmp(cmp) {} bool operator()(Node* a, Node* b) const { return cmp(*a,*b); } private: Cmp cmp; }; typedef deref_compare<Node,std::greater<Node> > my_comparator_t; priority_queue<Node*,vector<Node*>,my_comparator_t> open; i am filled with errors.
You need to write your own functor for the comparison because you can't overload operator> for pointers. So, instead of greater you would be using your own dedicated class with the appropriate function call operator. This could be even done generically. template<typename T, typename Cmp = std::less<T> > struct deref_compare : std::binary_function<T const*,T const*,bool> { deref_compare(Cmp const& cmp = Cmp()) : cmp(cmp) {} bool operator()(T const* a, T const* b) const { return cmp(*a,*b); } private: Cmp cmp; }; typedef deref_compare<Node,std::greater<Node> > my_comparator_t; Edit1: I just realized you could do it even more generically, with iterators instead of pointers. ;-) Edit2: If you're not comfortable with the template and don't need this generalization you could just as well use struct my_node_ptr_compare { bool operator()(Node const* a, Node const* b) const { return *a > *b; } }; priority_queue<Node*,vector<Node*>,my_node_ptr_compare> foo;
1,479,161
1,479,189
VC++ CLI application 32 - 64 bit CString question
SO, I am in the process of resolving the port of a 32bit app to 64 bit. When I compile for x64 I see a warning come up for the line ` CString sig; sig = "something"; sig = sig.left(strlen(something defined)); <<<<<< ` So, I get the warning for the sig.left where it implicitly converts the strlen value to int. Since in x64 strlen returns the 64bit size_t, i am getting the warning. what are my options of fixing this.. any alternate method ? Thanks
strlen always returns size_t. However, size_t is a different width on 64bit and 32bit operating systems. CString.left, however, expects an int. Your code should be fine (provided your strings won't be too long to overrun an int value), but the compiler will warn you that you're causing this problem. You can ignore the warning by using a cast. If you wanted to be "safe", you could do so by adding checking. The required cast would be as simple as: CString sig; sig = "something"; sig = sig.left((int)strlen(something_defined));
1,479,291
1,479,300
Calculating the value of pi-what is wrong with my code
I'm doing another C++ exercise. I have to calculate the value of pi from the infinite series: pi=4 - 4/3 + 4/5 – 4/7 + 4/9 -4/11+ . . . The program has to print the approximate value of pi after each of the first 1,000 terms of this series. Here is my code: #include <iostream> using namespace std; int main() { double pi=0.0; int counter=1; for (int i=1;;i+=2)//infinite loop, should "break" when pi=3.14159 { double a=4.0; double b=0.0; b=a/static_cast<double>(i); if(counter%2==0) pi-=b; else pi+=b; if(i%1000==0)//should print pi value after 1000 terms,but it doesn't cout<<pi<<endl; if(pi==3.14159)//this if statement doesn't work as well break; counter++; } return 0; } It compiles without errors and warnings, but only the empty console window appears after execution. If I remove line” if(i%1000==0)” , I can see it does run and print every pi value, but it doesn’t stop, which means the second if statement doesn’t work either. I’m not sure what else to do. I’m assuming it is probably a simple logical error.
Well, i % 1000 will never = 0, as your counter runs from i = 1, then in increments of 2. Hence, i is always odd, and will never be a multiple of 1000. The reason it never terminates is that the algorithm doesn't converge to exactly 3.14157 - it'll be a higher precision either under or over approximation. You want to say "When within a given delta of 3.14157", so write if (fabs(pi - 3.14157) < 0.001) break or something similar, for however "close" you want to get before you stop.
1,479,419
1,482,280
how to fix the error c2118: negative subscript
Again, porting 32-bit app to 64-bit. I get the negative subscript error on the C_ASSERT statement mentioned below.. C_ASSERT (sizeof(somestruct) == some#define); I also read the http://support.microsoft.com/kb/68475 article but not sure if I know how to fix it in this case. Help is appreciated. Thanks in advance.
I'm guessing the C_ASSERT macro is defined something like this: #define C_ASSERT(x) typedef char C_ASSERT_ ## __COUNTER__ [(x) ? 1 : -1]; This is a compile-time assertion: if the compile-time expression x is true, then this expands to something like typedef char C_ASSERT_1[1]; which declares the typename C_ASSERT_1 to be an alias for the type char[1] (array of 1 char). Converely, if the expression x is false, it expands to typedef char C_ASSERT_1[-1]; which is a compiler error, since you can't have an array type of negative size. Hence, your problem is that the expression sizeof(somestruct) == some#define is false, i.e. the size of somestruct is NOT what your code is expecting. You need to fix this -- either change the size of somestruct, or change the value of some#define, making sure that this won't break anything.
1,479,498
1,479,525
How to subclass a templated base class?
I have the following data structures: struct fastEngine { ... } struct slowEngine { ... } template<typename T> class Car { T engine; vector<T> backupEngines; virtual void drive() = 0; } class FastCar : public Car<fastEngine> { virtual void drive() { // use the values of "engine" in some way } } class SlowCar : public Car<slowEngine> { virtual void drive() { // use the values of "engine" in some way } } Car* getCarFromCarFactory() { // 1 if (randomNumber == 0) return new FastCar(); else return new SlowCar(); } void main() { Car* myCar = getCarFromCarFactory(); // 2 myCar->drive(); } The compiler complains at locations 1 and 2 because it requires that I define Car* with template parameters. I don't care what templated version of Car I'm using, I just want a pointer to a Car that I can drive. The engine structs must be structs because they are from existing code and I don't have control over them.
You could create a non-templated base class that Car<T> inherits, e.g. struct ICar { virtual void drive() = 0; }; template <typename T> class Car : public ICar { // ... } int main() { // BTW, it's always `int main`, not `void main` ICar *myCar = getCarFromCarFactory(); myCar->drive(); }
1,479,886
1,479,973
I want to show off my C++ projects through a website
The problem is that, well, it's C++. The way I've created them makes it such that they've always been run via a terminal/console window and wait for user input or else simply take a sample input and run with that. The output has also always been to the terminal screen or sometimes to a file. I'm not quite sure how I could take all of that and integrate it with a website while leaving the source code as it is, if that's at all possible. I guess what I'm trying to aim for is to have whatever website I use behave like a terminal window that will accept user input and then send it off to run the C++ program in question and return with the output (whatever it may be), all with minimal modification to the source code. Either that or else set up a more automated kind of page where a user can just click 'Go' and the program will run using a sample input. When it comes to web I consider myself intermediate with HTML, CSS, PHP & MySQL, and a beginner with Javascript, so if this can be accomplished using those languages, that would be fantastic. If not, don't be afraid to show me something new though.
The easiest interaction model to bring to the web is an application that takes its input up front and produces its output on stdout. In this situation, as the unknown poster mentioned, you could use CGI. But due to the nature of CGI, this will only work (in the simplest sense) if all the information is collected from the user in one page, sent to the application and the results returned in one page. This is because each invocation of a page using CGI spawns a new indepdent process to serve the request. (There are other more efficient solutions now, such as FastCGI which keeps a pool of processes around.) If your application is interactive, in that it collects some information, presents some results, prints some options, collects some more user input, then produces more results, it will need to be adapted. Here is about the simplest possible CGI program in C++: #include <iostream> int main(int argc, char* argv[]) { std::cout << "Content-type: text/plain\n" << std::endl; std::cout << "Hello, CGI World!" << std::endl; } All it does is return the content type followed by a blank line, then the actual content with the usual boring greeting. To accept user input, you would write a form in HTML, and the POST target would be your application. It will be passed a string containing the parameters of the request, in the usual HTTP style: foo.cgi?QTY=123&N=41&DESC=Simple+Junk You would then need to parse the query string (which is passed to the program via the QUERY_STRING environment variable) to gather the input fields from the form to pass to your application. Beware, as parsing parameter strings is the source of a great number of security exploits. It would definitely be worthwhile finding a CGI library for C++ (a Google search reveals many) that does the parsing for you. The query data can be obtained with: const char* data = getenv("QUERY_STRING"); So at a minimum, you would need to change your application to accept its input from a query string of name=value pairs. You don't even need to generate HTML if you don't want to; simply return the content type as text/plain to begin with. Then you can improve it later with HTML (and change the content type accordingly). There are other more sophisticated solutions, including entire web frameworks such as Wt. But that would involve considerable changes to your apps, which you said you wished to avoid.
1,479,888
1,479,977
Call C++ class member function from C (Visual Studio)
I need to call a C++ member function from a C program. I created .cpp/.h wrapper files in the C code, wrapping the C++ member functions. i.e.- wrapper.cpp #include "wrapper.h" extern "C" { void wrap_member1() { Class::member1(); } void wrap_member2() { Class::member2(); } } and wrapper.h: #include <windows.h> #include <stdio.h> #include "../C++ class with members I need to call.h" extern "C" void wrap_member1(); extern "C" void wrap_member2(); My problem is when I complie: error C2061: syntax error : identifier 'Class' It points to the .h declaration of the C++ class as an error. Same result as if I did not have the wrapper files....? P.S. I also removed the "extern "C" " from the prototypes and received an error on the wrapper function: error C2732: linkage specification contradicts earlier specification for 'wrap_member1' Any advice?
There are two issues: One, you are including a C++ header file in a C header file. This means the C compiler gets C++ code. This is what causes the error you are experiencing. As Reed Copsey suggests, put the #include in the C++ source file instead of the C header file. Two, you are using extern "C" in the C header file. Wrap your statement in an #ifdef as such: #ifdef __cplusplus extern "C" { #endif /* Functions to export to C namespace */ #ifdef __cplusplus } #endif This will allow the file to be usable for both C and C++.
1,479,945
1,484,628
Setting thread priority in Linux with Boost
The Boost Libraries don't seem to have a device for setting a thread's priority. Would this be the best code to use on Linux or is there a better method? boost::thread myThread( MyFunction() ); struct sched_param param; param.sched_priority = 90; pthread_attr_setschedparam( myThread.native_handle(), SCHED_RR, &param); I don't have alot of Linux programming experience.
That's the basic template for how I would do it but after searching around I found next to no code examples so I guess the verdict is out on whether it is best or not. The problem is that boost::thread does not have a constructor that allows pthead attributes to be passed in at thread creation so you have to make changes after the thread starts. The only other way I know to get around that is through the process/thread schedule inheritance. Unless directed otherwise, new threads will inherit the schedule/priority of their creator so you could change the current thread before creating worker threads and then change back if you want. Seems awkward but it is an alternative. Here's a hack of an example that hopefully demostrates both. You may need to change policy and priority as appropriate and run as root. Be careful with the way you set the priority. Various restrictions apply. #include <iostream> #include <boost/thread/thread.hpp> #include <unistd.h> #include <sched.h> #include <cstdio> void* threadfunc() { sleep(5); } void displayAndChange(boost::thread& daThread) { int retcode; int policy; pthread_t threadID = (pthread_t) daThread.native_handle(); struct sched_param param; if ((retcode = pthread_getschedparam(threadID, &policy, &param)) != 0) { errno = retcode; perror("pthread_getschedparam"); exit(EXIT_FAILURE); } std::cout << "INHERITED: "; std::cout << "policy=" << ((policy == SCHED_FIFO) ? "SCHED_FIFO" : (policy == SCHED_RR) ? "SCHED_RR" : (policy == SCHED_OTHER) ? "SCHED_OTHER" : "???") << ", priority=" << param.sched_priority << std::endl; policy = SCHED_FIFO; param.sched_priority = 4; if ((retcode = pthread_setschedparam(threadID, policy, &param)) != 0) { errno = retcode; perror("pthread_setschedparam"); exit(EXIT_FAILURE); } std::cout << " CHANGED: "; std::cout << "policy=" << ((policy == SCHED_FIFO) ? "SCHED_FIFO" : (policy == SCHED_RR) ? "SCHED_RR" : (policy == SCHED_OTHER) ? "SCHED_OTHER" : "???") << ", priority=" << param.sched_priority << std::endl; } int main(int argc, char* argv[]) { int policy, res; struct sched_param param; if ((policy = sched_getscheduler(getpid())) == -1) { perror("sched_getscheduler"); exit(EXIT_FAILURE); } if ((res = sched_getparam(getpid(), &param)) == -1) { perror("sched_getparam"); exit(EXIT_FAILURE); } std::cout << " ORIGINAL: "; std::cout << "policy=" << ((policy == SCHED_FIFO) ? "SCHED_FIFO" : (policy == SCHED_RR) ? "SCHED_RR" : (policy == SCHED_OTHER) ? "SCHED_OTHER" : "???") << ", priority=" << param.sched_priority << std::endl; policy = SCHED_RR; param.sched_priority = 2; if ((res = sched_setscheduler(getpid(), policy, &param)) == -1) { perror("sched_setscheduler"); exit(EXIT_FAILURE); } boost::thread t1(&threadfunc); displayAndChange(t1); t1.join(); return 0; }
1,479,953
1,479,993
Porting 32 bit C++ code to 64 bit - is it worth it? Why?
I am aware of some the obvious gains of the x64 architecture (higher addressable RAM addresses, etc)... but: What if my program has no real need to run in native 64 bit mode. Should I port it anyway? Are there any foreseeable deadlines for ending 32 bit support? Would my application run faster / better / more secure as native x64 code?
x86-64 is a bit of a special case - for many architectures (eg. SPARC), compiling an application for 64 bit mode doesn't give it any benefit unless it can profitably use more than 4GB of memory. All it does is increase the size of the binary, which can actually make the code slower if it impacts on cache behaviour. However, x86-64 gives you more than just a 64 bit address space and 64 bit integer registers - it also doubles the number of general purpose registers, which on a register-deficient architecture like x86 can result in a significant performance increase, with just a recompile. It also lets the compiler assume that many extensions, like SSE and SSE2, are present, which can also significantly improve code optimisation. Another benefit is that x86-64 adds PC-relative addressing, which can significantly simplify position-independent code. However, if the app isn't performance sensitive, then none of this is really important either.
1,479,987
1,480,037
Linux runtime linker error
I'm working though the First Steps tutorial on the POCO Project site, and I've successfully built the library (Debian Linux, 2.6.26, gcc 4.3.2) under my home directory ~/Development/POCO with the shared libraries located in ~/Development/POCO/lib/Linux/x86_64/lib My problem is that any application I build that depends on these libraries can only be run from the shared library directory. ~/Development/POCO/lib/Linux/x86_64$ ldd ~/Development/Cloud/DateTimeSample/bin/Linux/x86_64/DateTime linux-vdso.so.1 => (0x00007fffe69fe000) libPocoFoundation.so.6 (0x00007fa8de44f000) libpthread.so.0 => /lib/libpthread.so.0 (0x00007fa8de233000) libdl.so.2 => /lib/libdl.so.2 (0x00007fa8de02f000) librt.so.1 => /lib/librt.so.1 (0x00007fa8dde26000) libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007fa8ddb1a000) libm.so.6 => /lib/libm.so.6 (0x00007fa8dd897000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007fa8dd680000) libc.so.6 => /lib/libc.so.6 (0x00007fa8dd32d000) /lib64/ld-linux-x86-64.so.2 (0x00007fa8de7e0000) And running DateTime from this directory would work as you would expect. However ~/Development/Cloud/DateTimeSample/bin/Linux/x86_64$ ldd DateTime linux-vdso.so.1 => (0x00007fff24dfe000) libPocoFoundation.so.6 => not found libpthread.so.0 => /lib/libpthread.so.0 (0x00007ffc1c7dd000) libdl.so.2 => /lib/libdl.so.2 (0x00007ffc1c5d9000) librt.so.1 => /lib/librt.so.1 (0x00007ffc1c3d0000) libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007ffc1c0c4000) libm.so.6 => /lib/libm.so.6 (0x00007ffc1be41000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007ffc1bc2a000) libc.so.6 => /lib/libc.so.6 (0x00007ffc1b8d7000) /lib64/ld-linux-x86-64.so.2 (0x00007ffc1c9f9000) so running the executable from any other directory results in error while loading shared libraries: libPocoFoundation.so.6: cannot open shared object file: No such file or directory Looking at the output from the make process, the directory is correctly specified g++ [blah] -L/home/npalko/Development/POCO/lib/Linux/x86_64 -lPocoFoundation I've tried setting LD_LIBRARY_PATH to /home/npalko/Development/POCO/lib/Linux/x86_64, but it has not changed anything. Any help would be greatly appreciated!
If you don't want to have to deal with the LD_LIBRARY_PATH variable, you can add the linker -rpath option to the gcc command line. In your case, this would be: gcc ... -Wl,-rpath=/home/npalko/Development/POCO/lib/Linux/x86_64 This effectively hardcodes that path in the executable, so it may or may not be suitable for your purposes.
1,480,085
1,480,093
What's going on with overriding and overloading here in C++?
This doesn't work: class Foo { public: virtual int A(int); virtual int A(int,int); }; class Bar : public Foo { public: virtual int A(int); }; Bar b; int main() { b.A(0,0); } It seems that by overriding Foo::A(int) with Bar::A(int) I have somehow hidden Foo::A(int,int). If I add a Bar::A(int,int) things work. Does anyone have a link to a good description of what's going on here?
Essentially, name lookup happens before overload resolution so the function A in your derived class overrides the virtual function in the base class but hides all other functions with the same name in any base classes. Possible solutions include adding a using Foo::A; directive into your derived class to make all the base class members called A visible in the derived class or using different names for functions with different signatures. See here as well.
1,480,090
1,480,340
Casting to an object with pointers
I have a class, Fixture, that I want to cast to a 3rd party library class, b2FixtureDef. Currently, my function looks like this: Fixture::operator b2FixtureDef() const { b2FixtureDef fd; fd.density = m_density; fd.friction = m_friction; fd.isSensor = m_isSensor; fd.restitution = m_restitution; fd.shape = &b2PolygonShape(m_polygon); // <-- the problem return fd; } Although this doesn't produce any compile-time errors, I expect this will be a problem: fd.shape is a pointer. I'm casting my polygon object, to their polygon object, and then saving that location in memory. If I'm not mistaken, this will become immediately invalid after that line finishes executing. So what's a nice workaround for this? I could use the new operator, but my class shouldn't really be allocating memory for some other class to clean up. I could actually store the b2PolygonShape in my class, but then I essentially have two copies of the same data (my polgon object, and their polygon object); I could get rid of mine, but it's a lot easier to work with, which is why I created it in the first place. I could remove the entire function and make other classes responsible for doing the conversion themselves, but that wouldn't be consistent with my other wrappers, and it isn't a very nice solution. Is there any happy middle ground I'm overlooking? Code now looks like this: Fixture::operator b2FixtureDef() const { b2FixtureDef fd; fd.density = m_density; fd.friction = m_friction; fd.isSensor = m_isSensor; fd.restitution = m_restitution; fd.shape = new b2PolygonShape(m_polygon); return fd; } And gets used like this: void Body::addFixture(const Fixture& fixture) { m_fixtures.append(fixture); b2FixtureDef fd = fixture; m_body->CreateFixture(&fd); delete fd.shape; } My goal was that I could just go m_body->CreateFixture(&fixture) and it would cast fixture to a b2FixtureDef and free up the resources by itself... but it doesn't look like that's possible with this stupid pointer dangling around.
A conversion operator always has to make a copy of everything, so that the result is valid even if the original object is freed. Which means that you need to make a copy of m_polygon as b2PolygonShape and assign a pointer to it to b2FixtureDef::shape. You can make a copy by implementing a copy constructor in b2PolygonShape or a conversion operator in whatever type m_polygon is. [...] b2FixtureDef::shape looks like a has-a relation, so the destructor of b2FixtureDef should free it anyway, doesn't it? Hmm, you say b2FixtureDef::shape is not freed automatically, what if you create a proxy class that has a b2FixtureDef as member and a conversion operator b2FixtureDef? When you create the proxy object you create b2PolygonShape on the heap and fill the b2FixtureDef members just like in your code. In the conversion operator you simply return the b2FixtureDef member and in the proxy destructor you free the b2PolygonShape: class FixtureProxy { b2FixtureDef m_Fixture; FixtureProxy(Fixture aFixture) {m_Fixture.Shape = new b2PolygonShape(aFixture.m_polygon);...} ~FixtureProxy() {delete m_Fixture.Shape} operator b2FixtureDef() const {return m_Fixture} } you then use it like this void Body::addFixture(const Fixture& fixture) { m_fixtures.append(fixture); m_body->CreateFixture(&b2FixtureDef(FixtureProxy(fixture))); }
1,480,394
1,480,404
C++ STL - iterate through everything in a sequence
I have a sequence, e.g std::vector< Foo > someVariable; and I want a loop which iterates through everything in it. I could do this: for (int i=0;i<someVariable.size();i++) { blah(someVariable[i].x,someVariable[i].y); woop(someVariable[i].z); } or I could do this: for (std::vector< Foo >::iterator i=someVariable.begin(); i!=someVariable.end(); i++) { blah(i->x,i->y); woop(i->z); } Both these seem to involve quite a bit of repetition / excessive typing. In an ideal language I'd like to be able to do something like this: for (i in someVariable) { blah(i->x,i->y); woop(i->z); } It seems like iterating through everything in a sequence would be an incredibly common operation. Is there a way to do it in which the code isn't twice as long as it should have to be?
You could use for_each from the standard library. You could pass a functor or a function to it. The solution I like is BOOST_FOREACH, which is just like foreach in other languages. C+0x is gonna have one btw. For example: #include <iostream> #include <vector> #include <algorithm> #include <boost/foreach.hpp> #define foreach BOOST_FOREACH void print(int v) { std::cout << v << std::endl; } int main() { std::vector<int> array; for(int i = 0; i < 100; ++i) { array.push_back(i); } std::for_each(array.begin(), array.end(), print); // using STL foreach(int v, array) // using Boost { std::cout << v << std::endl; } }
1,480,417
1,482,460
building objects from xml file at runtime and initializing, in one pass?
I have to parse the XML file and build objects representation based on that, now once I get all these data I create entries in various database for these data objects. I have to do second pass over that for value as in the first pass all I could do is build the assets in various databases. and in second pass I get the values for all the data and put it in the database. I have a feeling that this can be done in a single pass but I just want to see what are your opinions. As I am just a student who started with professional work, experienced ppl please help. Can someone who have ideas or done similar work, please provide some light on the topic so that I can think over the possibility of the work and get the prototype going based on your suggestion. Thanks a lot for your precious time, I honestly appreciate it.
You might be interested in learning several techniques of building XML parsers like DOM or SAX. As it is said in SAX description the only thing which requires second pass could be the XML validation but not the creating the tree.
1,480,430
1,480,436
Member initialization of a data structure's members
I just ran into an awkward issue that has an easy fix, but not one that I enjoy doing. In my class's constructor I'm initializing the data members of a data member. Here is some code: class Button { private: // The attributes of the button SDL_Rect box; // The part of the button sprite sheet that will be shown SDL_Rect* clip; public: // Initialize the variables explicit Button(const int x, const int y, const int w, const int h) : box.x(x), box.y(y), box.w(w), box.h(h), clip(&clips[CLIP_MOUSEOUT]) {} However, I get a compiler error saying: C:\Users\Alex\C++\LearnSDL\mouseEvents.cpp|56|error: expected `(' before '.' token| and C:\Users\Alex\C++\LearnSDL\mouseEvents.cpp|56|error: expected `{' before '.' token| Is there a problem with initializing member in this way and will I need to switch to assignment in the body of the constructor?
You can only call your member variables constructor in the initialization list. So, if SDL_Rect doesn't have a constructor that accepts x, y, w, h, you have to do it in the body of the constructor.
1,480,446
1,480,449
p2p communication using winsock
I am trying to achieve peer to peer communication using winsock but gethostbyaddr always return me NULL ,this thing works only on localhost, server_name is destination ip address server_name="<--ipaddress-->" struct sockaddr_in server; addr = inet_addr(server_name); cout<<"inet_addr(server_name) "<<addr<<endl; hp = gethostbyaddr((char *)&addr, 4, AF_INET); memset(&server, 0, sizeof(server)); memcpy(&(server.sin_addr), hp->h_addr, hp->h_length); server.sin_family = hp->h_addrtype; server.sin_port = htons(port); conn_socket = socket(AF_INET, socket_type, 0); connect(conn_socket, (struct sockaddr*)&server, sizeof(server)) We have already achieved p2p communication using python and it works perfectly fine on same port no and address .. thanks for any clue.. I do not have any idea how to do it in c++, in python we just used bind(---) , Can somebody show me code snippet how to achieve it.
Where are you getting server_name from? Are you sure it's a valid IP address? Also, check WSAGetLastError() to see specifically what's going wrong. Remember that not all hostnames have reverse DNS entries. It's perfectly legitimate for gethostbyaddr to fail on a real, valid IP address. If you're doing p2p, it's best not to rely on host names at all, except perhaps for diagnostic displays (and fall back to IP addresses if reverse lookups fail). Edit: With your new, expanded code sample, it's clear that you actually don't need gethostbyaddr at all. struct sockaddr_in server; memset((void*)&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_addr.S_un.S_long = inet_addr(server_name); server.sin_port = htons(port); conn_socket = socket(AF_INET, socket_type, 0); connect(conn_socket, (struct sockaddr*)&server, sizeof(server)) gethostbyaddr is only needed when you need the reverse DNS name of the server in question. inet_addr already gives you a suitable address to connect to.
1,480,490
8,849,082
Python interpreter as a c++ class
I am working on embedding python in to c++. In some peculiar case I require two separate instances of the interpreter in same thread. Can I wrap Python interpreter in to a c++ class and get services from two or more class instances?
I have used Py_NewInterpreter for different interpreters in different threads, but this should also work for several interpreters within one thread: In the main thread: Py_Initialize(); PyEval_InitThreads(); mainThreadState = PyEval_SaveThread(); For each interpreter instance (in any thread): // initialize interpreter PyEval_AcquireLock(); // get the GIL myThreadState = Py_NewInterpreter(); ... // call python code PyEval_ReleaseThread(myThreadState); // swap out thread state + release the GIL ... // any other code // continue with interpreter PyEval_AcquireThread(myThreadState); // get GIL + swap in thread state ... // call python code PyEval_ReleaseThread(myThreadState); ... // any other code // finish with interpreter PyEval_AcquireThread(myThreadState); ... // call python code Py_EndInterpreter(myThreadState); PyEval_ReleaseLock(); // release the GIL Note that you need a variable myThreadState for each interpreter instance! Finally the finish in the main thread: PyEval_RestoreThread(mainThreadState); Py_Finalize(); There are some restrictions with using several interpreter instances (they seem not to be totally independent), but in most cases this does not seem to cause problems.
1,480,525
1,480,534
C++ Collection of instances implementing a pure virtual class
I am working in cross platform C++, and have some classes defined like so: (heavily simplified for this example) class ExampleBase { public: ExampleBase( int blah ) : blah_test(blah) { } virtual void DoSomething( ) = 0; private: int blah_test; }; class ExampleImplementer : public ExampleBase { public: ExampleImplementer( ) : ExampleBase( 5 ) { } virtual void DoSomething( ) { /* unique implementation here */ } }; Originally I had only a single class, which I stored a bunch of instances of in a std::vector and passed around by const reference. But now I need to have a base class (that I want to keep pure virtual) and a number of polymorphic implementing classes. What is the best way to have a collection of any implementing instances, and still have leak free easy memory management like having a stack allocated std::vector? Obviously I can't have a std::vector< ExampleBase > now, since std::vector requires the class to be non-pure virtual (since it does internal allocation/copying etc.). I don't want users of my code to accidentally create instances of ExampleBase because that is wrong. I also want to steer clear from any possibilities of object slicing or any other nasties. An array of std::auto_ptr would do the job, but then I have to deal with initializing them all, looking for a "free slot", no iterators etc. It seems a bit crazy to do all of this wheel re-inventing. boost::ptr_vector looked promising, however it behaves a little weirdly in that when building on Linux it needs ExampleBase to be non-pure virtual - and I don't understand why... So boost::ptr_vector is out. This seems to be a simple, and probably really common situation. So what is the best way to do this? I am open to any other std or boost way of doing this: whichever is "best".
boost::ptr_vector is the way to go if you can have Boost. It should work for your scenario - if it does not, then something else is wrong, so please post the error message. Alternatively, you can go for std::vector< boost::shared_ptr<ExampleBase> >. This is less ideal, because that refcounting will add some overhead, especially when vector is resized, but otherwise a working solution. If your implementation supports TR1 (latest versions of g++ and MSVC), then you can use std::tr1::shared_ptr instead. This can actually be superior, because STL implementation is free to optimize based on some inner knowledge - for example, in MSVC, std::vector knows that it can use swap instead of copy constructor for std::tr1::shared_ptr, and does just that, avoiding constant refcount changes.
1,480,596
1,480,644
How do you get how much memory a program uses?
I have two programs, one in C++, the other in assembler. I want to compare how much memory they use when running respectively. How can I do this? I am doing the testing on Windows, but I also would like to know how to do it on Linux.
Run the program in one shell. Open another shell and run 'top' command. it will list running processes and home much memory they consume. you can, i guess, poll /proc/yourprocessid/stat to see how much memory it is using over time.
1,480,655
1,480,829
How can I, on some global keystroke, paste some text to current active application in linux with Python or C++
I want to write app, which will work like a daemon and on some global keystroke paste some text to current active application (text editor, browser, jabber client) I think i will need to use some low level xserver api. How i can do this with Python or C++ ?
You can use the xmacroplay utility from xmacro to do this under X windows I think. Either use it directly - send it commands to standard input using the subprocess module, or read the source code and find out how it does it! I don't think there are python bindings for it. From the xmacroplay website xmacroplay: Reads lines from the standard input. It can understand the following lines: Delay [sec] - delays the program with [sec] secundums ButtonPress [n] - sends a ButtonPress event with button [n] this emulates the pressing of the mouse button [n] ButtonRelease [n] - sends a ButtonRelease event with button [n] this emulates the releasing of the mouse button [n] ... snip lots more ... This is probably the command you are interested in String [max. 1024 long string] - Sends the string as single characters converted to KeyPress and KeyRelease events based on a character table in chartbl.h (currently only Latin1 is used...) There is also Xnee which does a similar thing.
1,480,916
1,480,962
How do I enable the SSE/SSE2 instruction set in Visual Studio 2008 (using CMake)?
In Visual Studio 2005 I went in: View --> Property Pages --> C/C++ --> Code Generation --> Enable Enhanced Instruction Set But in Visual Studio 2008? Thanks in advance
If you're looking for SSE/SSE2: Project > Properties > Configuration Properties > C/C++ > Code Generation > Enable Enhanced Instruction Set, or append /arch:SSE (or /arch:SSE2) in Command Line > Additional Options. You need to have a native project, and at least one .cpp file added to access this, though.
1,480,971
1,481,890
Is there a non-java, cross platform way to launch the associated application for a certain file type?
First, I found a couple of java specific questions and answers for this. I am looking for more "native", but cross platform solution, using C, C++, some kind of shell scripts, or, in my case, Qt. So the question is, are there standard, cross platform, ways to programmatically open the associated application for certain file types. Or at least to find out if there are associated applications and be able to locate and launch them? By cross platform I mean Windows, OSX and linux (gnome/kde). The use case is having a database with stored files as blobs that will be read on the three different targets.
I don't know of any cross-platform way. In Windows, there is the start command, which will launch the associated default application. (E.g. start foo.doc will launch the default Word document editor, start http://StackOverflow.Com/ the default web browser and start mailto:mail@example.com the default mail app.) In OS X there is the open command, which does the same thing. Linux is just an Operating System kernel. OS kernels don't know anything about "filetypes" or "MIME types" or "associated applications" or anything like that. Therefore, such a thing simply cannot exist for Linux. The Freedesktop Group has a specification for an xdg-open command, which works on all Freedesktop-compliant graphical desktops (be they Linux, FreeBSD, NetBSD, OpenBSD, DragonflyBSD, OpenSolaris or otherwise). However, it is obviously not guaranteed to work on non-Freedesktop systems and it is certainly not guaranteed to work on non-graphical systems. In all three cases, this is a command line application, not a C or C++ API, but you can obviously call it via system.
1,480,973
1,485,657
How can I make my char buffer more performant?
I have to read a lot of data into: vector<char> A 3rd party library reads this data in many turns. In each turn it calls my callback function whose signature is like this: CallbackFun ( int CBMsgFileItemID, unsigned long CBtag, void* CBuserInfo, int CBdataSize, void* CBdataBuffer, int CBisFirst, int CBisLast ) { ... } Currently I have implemented a buffer container using an STL Container where my method insert() and getBuff are provided to insert a new buffer and getting stored buffer. But still I want better performing code, so that I can minimize allocations and de-allocations: template<typename T1> class buffContainer { private: class atomBuff { private: atomBuff(const atomBuff& arObj); atomBuff operator=(const atomBuff& arObj); public: int len; char *buffPtr; atomBuff():len(0),buffPtr(NULL) {} ~atomBuff() { if(buffPtr!=NULL) delete []buffPtr; } }; public : buffContainer():_totalLen(0){} void insert(const char const *aptr,const unsigned long &alen); unsigned long getBuff(T1 &arOutObj); private: std::vector<atomBuff*> moleculeBuff; int _totalLen; }; template<typename T1> void buffContainer< T1>::insert(const char const *aPtr,const unsigned long &aLen) { if(aPtr==NULL,aLen<=0) return; atomBuff *obj=new atomBuff(); obj->len=aLen; obj->buffPtr=new char[aLen]; memcpy(obj->buffPtr,aPtr,aLen); _totalLen+=aLen; moleculeBuff.push_back(obj); } template<typename T1> unsigned long buffContainer<T1>::getBuff(T1 &arOutObj) { std::cout<<"Total Lenght of Data is: "<<_totalLen<<std::endl; if(_totalLen==0) return _totalLen; // Note : Logic pending for case size(T1) > T2::Value_Type int noOfObjRqd=_totalLen/sizeof(T1::value_type); arOutObj.resize(noOfObjRqd); char *ptr=(char*)(&arOutObj[0]); for(std::vector<atomBuff*>::const_iterator itr=moleculeBuff.begin();itr!=moleculeBuff.end();itr++) { memcpy(ptr,(*itr)->buffPtr,(*itr)->len); ptr+= (*itr)->len; } std::cout<<arOutObj.size()<<std::endl; return _totalLen; } How can I make this more performant?
If my wild guess about your callback function makes sense, you don't need anything more than a vector: std::vector<char> foo; foo.reserve(MAGIC); // this is the important part. Reserve the right amount here. // and you don't have any reallocs. setup_callback_fun(CallbackFun, &foo); CallbackFun ( int CBMsgFileItemID, unsigned long CBtag, void* CBuserInfo, int CBdataSize, void* CBdataBuffer, int CBisFirst, int CBisLast ) { std::vector<char>* pFoo = static_cast<std::vector<char>*>(CBuserInfo); char* data = static_cast<char*>CBdataBuffer; pFoo->insert(pFoo->end(), data, data+CBdataSize); }
1,481,041
1,481,069
Destructor for Singleton
Question : Should i write destructor for a singleton which has program scope (comes alive when program starts and dies when program ends) Detail : i am in a dilemma on "shall i write destructor for a singleton class or not ?" 1) This class has program scope 2) Class uses a lot of memory on heap, So releasing that will take time When user is exiting program, Response should be fast , So why to spend time in freeing memory occupied by this singleton , As memory will be released as program will end.
If it takes a long time to release memory, then don't do it. This may be a big and time-consuming issue, especially if releasing memory leads to numerous cache misses. OS will do the job (of course, if you are operating on the systems that actually does that). However, if your destructor does finalization of some resources (for example, unlocking a file or a piece of hardware), and you use "resource acquisition is initialization", you must ensure that the proper destructors are called (for example, those of static objects are called after your main() function returns). This holds if some of the objects allocated inside your singleton lock resources, too! In most cases, therefore, it's better to actually write a destructor for such an object and make it release memory optionally. SSS, who asked the question, decided not to write destructor at all. However, I'd like to argue a bit more that it's not the best solution. Not freeing a memory for a static object (let's call it "static") is a very subtle optimization that contradicts common sense and how people usually write programs. Your code, allocating memory and merely having no destructor, looks weird. Peers will think that the class is badly written, will tend to look bugs in it (while they're in the other class). Instead, you should conform to common coding standards which dictate that memory management in C++ should be correct. Do write a destructor and, only after it shows it has a significant boost not to deallocate, wrap the code for it not to be called. Intent to not release the memory must be explicit. MySingleton::~MySingleton() { #ifndef RELEASE // The memory will be released by OS when program terminates! delete ptr1; delete ptr2; #endif } or even MySingleton::~MySingleton() { // We don't do anything here. // The memory will be released by OS when program terminates! } but destructor is better to persist.
1,481,050
1,481,061
Where Does SYMBOL TABLE Reside?
I wanted to know where does SYMBOL TABLE reside. Is it in .obj files or an .exe file? Thanks in advance.
There's another similar SO Question. In the answers to this question, it mentions that the symbol table is in each .obj file.
1,481,216
1,481,244
C++ reference type recommended usage
I am programming in C++ more then 5 years, and have never met any place where reference of the variable is recommended to use except as a function argument (if you don't want to copy what you pass as your function argument). So could someone point cases where C++ variable reference is recommended (I mean it gives any advantage) to use.
As a return value of an opaque collection accessor/mutator The operator[] of std::map returns a reference. To shorten the text needed to reference a variable If you miss old-school with Foo do ... statement (that's Pascal syntax), you can write MyString &name = a->very->long_->accessor->to->member; if (name.upcase() == "JOHN") { name += " Smith"; } another example of this can be found in Mike Dunlavey's answer To state that something is just a reference References are also useful in wrapper objects and functors--i.e. in intermediate objects that logically contact no members but only references to them. Example: class User_Filter{ std::list<User> const& stop_list; public: Functor (std::list<User> const& lst) : stop_list(lst) { } public: bool operator()(User const& u) const { return stop_list.exists(u); } }; find_if(x.begin(),x.end(),User_Filter(user_list)); The idea here that it's a compile error if you don't initialize a reference in constructor of such an object. The more checks in compile time--the better programs are.
1,481,282
1,481,336
Poco C++ SAX parser: how to get element "inner text"?
I've been going over the Poco SAX parser header files a few times but I can't seem to find any info on how to obtain an element's inner text. For example: <description>This is the inner text.</description> Can anyone point me in the right direction?
Ok, found the solution myself. I needed to use implement the 'characters' method like this: void MyParser::characters(const Poco::XML::XMLChar ch[], int start, int length) { std::string innerText = std::string(ch + start, length); }
1,481,382
1,481,516
runtime error (SIGSEGV)
#include<iostream> #include<string> using namespace std; int main() { char arr[1000][80]; char output[1000][80]; int n,i,j; int num[1000]; cin>>n; for(i=0;i<n;i++) { cin>>num[i]; cin>>arr[i]; } for(i=0;i<n;i++) { for(j=(num[i]-1);j<(strlen(arr[i])-1);j++) { arr[i][j]=arr[i][j+1]; } arr[i][j]='\0'; cout<<"\n"<<(i+1)<<" "<<arr[i]; } return 0; } This is the code which while uploading on Spoj gives the above error. The same code runs fine on Borland C++.
Depending on the input you pass to this program, the variable n may be more than 1000, cin>>arr[i] may read more than 80 characters, and if num[i] <= 0 || num[i] >= 80 then you will index past the beginning or end of one of your strings. All of these problems exist because this code uses fixed-size arrays and doesn't do any bounds checking.
1,481,612
1,481,764
What is the difference between throw and throw with arg of caught exception?
Imagine two similar pieces of code: try { [...] } catch (myErr &err) { err.append("More info added to error..."); throw err; } and try { [...] } catch (myErr &err) { err.append("More info added to error..."); throw; } Are these effectively the same or do they differ in some subtle way? For example, does the first one cause a copy constructor to be run whereas perhaps the second reuses the same object to rethrow it?
Depending on how you have arranged your exception hierarchy, re-throwing an exception by naming the exception variable in the throw statement may slice the original exception object. A no-argument throw expression will throw the current exception object preserving its dynamic type, whereas a throw expression with an argument will throw a new exception based on the static type of the argument to throw. E.g. int main() { try { try { throw Derived(); } catch (Base& b) { std::cout << "Caught a reference to base\n"; b.print(std::cout); throw b; } } catch (Base& b) { std::cout << "Caught a reference to base\n"; b.print(std::cout); } return 0; } As written above, the program will output: Caught a reference to base Derived Caught a reference to base Base If the throw b is replace with a throw, then the outer catch will also catch the originally thrown Derived exception. This still holds if the inner class catches the Base exception by value instead of by reference - although naturally this would mean that the original exception object cannot be modified, so any changes to b would not be reflected in the Derived exception caught by the outer block.
1,481,616
1,481,622
Smart pointers in Qt
Like it has been written here Qt up to now has 8 specilized smart pointer classes. It looks like it is all you will ever need. However, in order to use any of these smart pointers your class must be derived from QObject which is not always convenient. Is there other implementations of smart pointers in Qt which work with arbitrary classes?
Many Qt classes are derived from QObject, and while some of the built in smart pointer classes are related to QObject (or QSharedData), the QSharedPointer and QScopedPointer templates appear to allow pointers to anything. Beyond that, you'll find some smart pointer templates in Boost: scoped_ptr - Simple sole ownership of single objects. Noncopyable. scoped_array - Simple sole ownership of arrays. Noncopyable. shared_ptr - Object ownership shared among multiple pointers. shared_array - Array ownership shared among multiple pointers. weak_ptr - Non-owning observers of an object owned by shared_ptr. intrusive_ptr - Shared ownership of objects with an embedded reference count.
1,481,677
1,481,796
How to provide a explicit specialization to only one method in a C++ template class?
I have a template class that looks something like this: template<class T> class C { void A(); void B(); // Other stuff }; template<class T> void C<T>::A() { /* something */ } template<class T> void C<T>::B() { /* something */ } What I want is to provide an explicit specialization for only A while retaining the default for B and the "other stuff". What I have tried so far is class D { }; template<> void C<D>::A() { /*...*/ } // Gives a link error: multiple definition Every other variant I've attempted fails with parse errors. What I did: The original problem was that the explicit specialization was in a header file so it was getting dumped into several object files and messing up the link (Why doesn't the linker notice all the instances of the symbol are the same a just shut up?) The solution ends up being to move the explicit specialization from the header file to a code file. However to make the other users of the header file not instance the default version, I needed to place a prototype back in the header. Then to get GCC to actually generate the explicit specialization, I needed to place a dummy variable of the correct type in the code file.
Alternatively to Martin York's inline solution you could also do in your header file: class D { }; template<> void C<D>::A(); // Don't implement here! And supply a .cpp file with the implementation: template<> void C<D>::A() { /* do code here */ } So you avoid the multiple definitions by supplying a single one. This is also good to hide implementations for specific Types away from the template header file when publishing the library.
1,481,733
1,481,768
Portable C++ 03 Exact Width Types
Background Unfortunately the current C++ standard lacks C99's exact-width types defined in the stdint header. The next best thing I could find (in terms of portability) was Boost's cstdint.hpp implementation from the Boost.Integer library. Concerns That said, I've got a few problems with it: Boost's implementation dumps all the typedefs in the boost namesapce (instead of something like boost::stdint). This is totally ugly, because now you're either forced to use a using-directive only on the types that you're interested in (this is an extra maintenance chore), or bring the entire boost namespace into global¹ scope (this defeats the point of namespaces). I could, of course, be verbose and type boost::uint32_t everywhere, for example, but this isn't very future-friendly², either. Questions I'm basically looking for advice. What's the best way to go about utilizing these not-yet-standard (not in C++ '03, anyway) types as transparently as possible? For those of you who use this header, or rolled your own, how do you use these types? Blindly merge the boost namespace into the global namespace, prefix everything with "boost::", wrote a header that wraps Boost.Integer's cstdint.hpp, etc.? Any advice is appreciated. Finally, having said all that (this wasn't a rant, by the way), I'm writing math-intensive code, so width-guarantees are important to me. Clarifications 1 - Global scope is my only option when I'm writing functions / class templates that take these types as arguments. 2 - When the next iteration of the standard wraps stdint.h into cstdint, I'll be stuck with a bunch of code that's prefixed with "boost::". This, then, will be an extra dependency (i.e., "boost/cstdint.hpp") that will be totally useless.
You could just use stdint.h, and provide one for compilers that don't have it (e.g. for MSVC - msinttypes). Or write cstdint that is using all of Boost's typedefs (it's a write-once, so I don't think maintenance will be problematic). It's easy to generate, too. Using this little script, i got that. You could also add defines to check for int64. #ifndef GEN_CSTDINT #define GEN_CSTDINT #include <boost/cstdint.hpp> using boost::int16_t; using boost::int32_t; using boost::int64_t; using boost::int8_t; using boost::int_fast16_t; using boost::int_fast32_t; using boost::int_fast64_t; using boost::int_fast8_t; using boost::int_least16_t; using boost::int_least32_t; using boost::int_least64_t; using boost::int_least8_t; using boost::intmax_t; using boost::uint16_t; using boost::uint32_t; using boost::uint64_t; using boost::uint8_t; using boost::uint_fast16_t; using boost::uint_fast32_t; using boost::uint_fast64_t; using boost::uint_fast8_t; using boost::uint_least16_t; using boost::uint_least32_t; using boost::uint_least64_t; using boost::uint_least8_t; using boost::uintmax_t; #endif // GEN_CSTDINT
1,481,793
1,481,811
Return value of XXTEA
This may seem a stupid question but I can't find the anwer... This is the code for XXTEA from Wikipedia: #include <stdint.h> #define DELTA 0x9e3779b9 #define MX ((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (k[(p&3)^e] ^ z)); void btea(uint32_t *v, int n, uint32_t const k[4]) { uint32_t y, z, sum; unsigned p, rounds, e; if (n > 1) { /* Coding Part */ rounds = 6 + 52/n; sum = 0; z = v[n-1]; do { sum += DELTA; e = (sum >> 2) & 3; for (p=0; p<n-1; p++) y = v[p+1], z = v[p] += MX; y = v[0]; z = v[n-1] += MX; } while (--rounds); } else if (n < -1) { /* Decoding Part */ n = -n; rounds = 6 + 52/n; sum = rounds*DELTA; y = v[0]; do { e = (sum >> 2) & 3; for (p=n-1; p>0; p--) z = v[p-1], y = v[p] -= MX; z = v[n-1]; y = v[0] -= MX; } while ((sum -= DELTA) != 0); } } I am porting this to C#. I don't know what I am overlooking, but where is the result of the encryption stored? I assume it is in v, but data from v is never set, only read. What is it that I don't see?
Operators = -= += has the same priority in expressions and they are associated from right to left according to C++ Standard 5.17 (and I believe there is the same rule in C) . For example, this: y = v[p] -= MX; Could be replaced with: v[p] -= MX; // <<< modification of data here y = v[p];
1,481,886
1,481,899
Failed to open an FTP connection
I had a problem when trying to connect and upload a file to an FTP server. Here's my code: #include <windows.h> #include <wininet.h> #pragma comment(lib, "wininet.lib") int main() { HINTERNET hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); HINTERNET hFtpSession = InternetConnect(hInternet, L"myserver.com", INTERNET_DEFAULT_FTP_PORT, L"user", L"pass", INTERNET_SERVICE_FTP, 0, 0); if(FtpPutFile(hFtpSession, L"file.txt", L"file.txt", FTP_TRANSFER_TYPE_BINARY, 0)) { MessageBox(NULL, L"Upload Complete", L"OK", 0); } else { MessageBox(NULL, L"Upload Failed", L"OK", 0); } InternetCloseHandle(hFtpSession); InternetCloseHandle(hInternet); return 0; } and the error: svDialog.obj : error LNK2005: "void * hFtpSession" (?hFtpSession@@3PAXA) already defined in MainDlg.obj svDialog.obj : error LNK2005: "void * hInternet" (?hInternet@@3PAXA) already defined in MainDlg.obj am I doing wrong? (the above code is just a simplified representation of my real program using wxWidgets and Multithreading)
There is nothing wrong with code you've posted. Linker error refers to redefined symbol - you have two same variables in global namespace, in two different object files (svDialog and MainDlg). Try not to use global variables; and if you have to, and you have HINTERNET hFtpSession; HINTERNET hInternet; in one of your headers, then prepend extern, i.e. extern HINTERNET hFtpSesssion; extern HINTERNET hInternet;. If not, and svDialog's hFtpSession and hInternet are completely different variables, rename them in one of those files (or try anonymous namespace).
1,481,971
1,483,019
MFC: CToolTipCtrl causes ASSERT
I have implemented tool tips seemingly successfully in an app which is MFC based and uses CPropertyPage. However after adding a button to open a dialog box called IDC_USERMSG which contains a single CEdit control on one of the CPropety pages an Assert is thrown when the IDC_USERMSG dialog is dismissed. _AFXWIN_INLINE CWnd* CWnd::GetParent() const { ASSERT(::IsWindow(m_hWnd)); // Asserts here. return CWnd::FromHandle(::GetParent(m_hWnd)); } I belive this is because the IDC_USERMSG dialog no longer exsists at this stage because it has been closed. Button/Tooltips implimented as follows. BEGIN_MESSAGE_MAP(CUserData, CPropertyPage) // Displays dialog when button pressed ON_BN_CLICKED(IDC_USERMSG, &CUserData::OnBnClickedUsermsgbtn) END_MESSAGE_MAP() BOOL CUserData::OnInitDialog() { EnableToolTips(TRUE); static CString ToolTip; CTTCtrl.Create(this); // CToolTipCtrl CTTCtrl is a global CTTCtrl.SetDelayTime(TTDT_AUTOPOP, 8000); CTTCtrl.SetMaxTipWidth(ToolTipWidth); ToolTip.LoadStringW(TT_REN); CTTCtrl.AddTool( GetDlgItem( IDC_TT_REN), ToolTip ); return 0; } BOOL CUserData::PreTranslateMessage(MSG* pMsg) { CTTCtrl.RelayEvent( pMsg ); CDialog::PreTranslateMessage(pMsg); // think I need some sort of filter here. return CDialog::PreTranslateMessage(pMsg); } Call Stack mfc90ud.dll!CWnd::GetParent() Line 297 + 0x2d bytes C++ mfc90ud.dll!CWnd::FilterToolTipMessage(tagMSG * pMsg=0x00155570) Line 392 + 0x8 bytes C++ mfc90ud.dll!CWnd::_FilterToolTipMessage(tagMSG * pMsg=0x00155570, CWnd * pWnd=0x0012fa78) Line 374 C++ mfc90ud.dll!CWnd::PreTranslateMessage(tagMSG * pMsg=0x00155570) Line 1070 C++ mfc90ud.dll!CDialog::PreTranslateMessage(tagMSG * pMsg=0x00155570) Line 56 + 0xc bytes C++ MyApp.exe!CUserData::PreTranslateMessage(tagMSG * pMsg=0x00155570) Line 495 C++
You are calling CDialog::PreTranslateMessag twice, remove the second call.
1,481,996
1,482,063
How to call an instantiated class member variable through other function that was unrelated to the class?
I'm now creating a file transaction system (through FTP) using wxWidgets for the GUI and a multithreading class from CodeProject (http://www.codeproject.com/KB/threads/SynchronizedThreadNoMfc.aspx) - Please read the article first for reference. In my GUI, I have a textbox (wxTextCtrl) that stores the file path that wanted to be sent to the FTP server, and I wanted to get its value through the multi-threading function. Here is my code so far: (simplified; multiple files) /////// Organizer.h // Main header file that utilizes all other headers #include <wx/wx.h> #include <wx/datectrl.h> #include <wininet.h> #pragma comment(lib, "wininet.lib") #include "Threading.h" #include "MainDlg.h" #include "svDialog.h" ///////// Threading.h // Please read the article given above #include "ou_thread.h" using namespace openutils; extern HINTERNET hInternet; // both declared in MainDlg.cpp extern HINTERNET hFtpSession; class svThread : public Thread { private: char* ThreadName; public: svThread(const char* szThreadName) { Thread::setName(szThreadName); this->ThreadName = (char* )szThreadName; } void run() { if(this->ThreadName == "Upload") { hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); hFtpSession = InternetConnect(hInternet, L"myserver.com", INTERNET_DEFAULT_FTP_PORT, L"user", L"pass", INTERNET_SERVICE_FTP, 0, 0); std::string filenameOnServer((char* )tb_file->GetValue().c_str()); // HERE..the tb_file.. std::vector<std::string> filepathParts; __strexp(filenameOnServer, "\\", filepathParts); // this is user-defined function that will split a string (1st param) with the given delimiter (2nd param) to a vector (3rd param) filenameOnServer = filepathParts.at(filepathParts.size() - 1); // get only the filename if(FtpPutFile(hFtpSession, tb_file->GetValue().c_str(), (LPCWSTR)filenameOnServer.c_str(), FTP_TRANSFER_TYPE_BINARY, 0)) { MessageBox(NULL, L"Upload Complete", L"OK", 0); } else { MessageBox(NULL, L"Upload Failed", L"OK", 0); } } } }; ////////// svDialog.h class svDialog : public wxFrame { public: svDialog(const wxString &title); void InitializeComponent(); void ProcessUpload(wxCommandEvent &event); // function (button event) that will start the UPLOAD THREAD wxTextCtrl *tb_file; // this is the textbox //....other codes }; ///////////svDialog.cpp #include "Organizer.h" Thread *UploadRoutine; svDialog::svDialog(const wxString &title) : wxFrame(...) // case unrelated { InitializeComponent(); } void svDialog::InitializeComponent() { tb_file = new wxTextCtrl(...); //......other codes } void svDialog::ProcessUpload(wxCommandEvent &event) { UploadRoutine = new svThread("Upload"); UploadRoutine->start(); //......other codes } ////// MainDlg.cpp // (MainDlg.h only contains the MainDlg class declaration and member function prototypes) #include "Organizer.h" HINTERNET hInternet; HINTERNET hFtpSession; IMPLEMENT_APP(MainDlg) // wxWidgets macro bool MainDlg::OnInit() // wxWidgets window initialization function { //......other codes } Well, as you can see in my code above, I wanted to get the content of tb_file (with tb_file->GetValue()) and pass it to the multi-threading function (void run()) for to be uploaded later. Any kind of help would be appreciated! Thanks. (and sorry for the long code..)
It's quite simple. You should create a start function that takes a std::string (or any other parameters) and store it (them) in the svThread object. Then you can access it in the run function: class svThread : public Thread { private: char* ThreadName; std::string FileName; public: svThread(const char* szThreadName) { Thread::setName(szThreadName); this->ThreadName = (char* )szThreadName; } void Start(const std::string& filename) { this->FileName = filename; Thread::Start(); } void Run() { // ... if(FtpPutFile(hFtpSession, FileName,(LPCWSTR)filenameOnServer.c_str(), FTP_TRANSFER_TYPE_BINARY, 0)) // ... } }; In your dialog class you just need to start your thread like this: UploadRoutine = new svThread("Upload"); UploadRoutine->start(tb_file->GetValue().c_str());
1,482,515
1,483,945
Clearing/resetting a model in qt (removing all rows)
I'm confused about the correct way to reset or clear the data associated with a QAbstractItemModel. I'm writing an application in which the user can "start over" with a new set of data (empty, or small). Should I be deleting the old model when the user makes this request? Or should I leave the model alone and just remove all of the rows? Regards, Dan O
Generally I would prefer to have the model react to changes and take the necessary actions to update it's view (indirectly ofcourse). However, programming models can be (=is) a PITA, so I would probably look through the fingers if I was reviewing code that created a new model and deleted the old one. Only do this if you are sure the user only will delete all rows. If the user may delete items from the model incrementally you're probably best off implementing removal properly in the first place... Also, ModelTest might help you discover problems with your Qt models.
1,482,535
1,482,690
Automatically deducing operators in C++?
Is it possible in C++ for the compiler/language to automatically deduce unimplemented operators? For example, if I have: class X { public: bool operator ==(const X &x) const; }; Is there a way for != to be deduced implicitly? And I'll exploit this questions for a semi-related one: How come map's only requirement from it's keys is to implement the < operator? How does it compare for equality?
The STL already has a set of definitions. In the namespace stl::rel_ops the following definitions can be found. namespace std { namespace rel_ops { // Uses == template <class _Tp> inline bool operator!=(const _Tp& __x, const _Tp& __y); // Uses < template <class _Tp> inline bool operator>(const _Tp& __x, const _Tp& __y); template <class _Tp> inline bool operator<=(const _Tp& __x, const _Tp& __y); template <class _Tp> inline bool operator>=(const _Tp& __x, const _Tp& __y); } // namespace rel_ops } To use it you just need to do: #include <utility> using namespace std::rel_ops; Though personally I would restrict the scope of the using as much as possable.
1,482,584
1,493,220
Drawbacks to nesting of child windows?
Just for fun I'm developing a native Win32 port of Mozilla XUL. XUL allows to create complex nested structures of all kinds of layout boxes (hbox, vbox, grid, deck..). For my Windows implemenation it would be convenient to implement them as STATIC child windows. Because then I can position their child windows using x & y offsets independent of the position of the parent box. However, this approach may lead to certain windows having a lot of nested child windows. And I wonder if there would be any disadvantages to such a situation. Does anyone here know?
I've been down this path, and I don't recommend you actually make deep hierarchies of windows. Lots of Windows helper functions (e.g., IsDialogMessage) work better with "traditional" layouts. Also, windows in Windows are relatively heavy objects, mostly for historical reasons. So if you have tons of objects, you could run into limitations, performance problems, etc. What I've done instead is to represent the deeply-nested layout as a tree of regular C++ objects that parallels the flatter hierarchy of actual windows. Some nodes of the object hierarchy have the HWNDs of the "real" windows they represent. You tell the hierarchy to lay out, and the nodes apply the results to the corresponding windows. For example, the root of the hierarchy may represent a dialog window, and the leaf nodes represent the child windows. But the hierarchy has several layers of non-window objects in between that know about layout.
1,482,610
1,482,630
Multiple threads for multiple ports?
I have a program (process) which needs to listen on 3 ports... Two are TCP and the other UDP. The two TCP ports are going to be receiving large amounts of data every so often (could be as little as every 5 minutes or as often as every 20 seconds). The third (UDP) port is receiving constant data. Now, does it make sense to have these listening on different threads? For instance, when I receive a large amount of data from one of the TCP ports, I don't want my UDP stream interrupted... are these common concerns for network programming? I'll be using the Boost library on Windows if that has any bearing. I'm just looking for some thoughts/ideas/guidance on this issue and how to manage multiple connections.
In general, avoid threads unless necessary. On a modern machine you will get better performance by using a single thread and using I/O readiness/completion features. On Windows this is IO Completion Ports, on Mac OS X and FreeBSD: kqueue(2), on Solaris: Event ports, on Linux epoll, on VMS QIO. Etc. In boost, this is abstracted by boost::asio. The place where threads would be useful is where you must do significant processing or perform a blocking operating system call that would add unacceptable latency to the rest of the networking processing.
1,482,656
1,482,668
How to get rid of the warning with time.h in C++?
When I use this #include<time.h> //... int n = time(0); //... I get a warning about converting time to int. Is there a way to remove this warning?
Time returns time_t and not integer. Use that type preferably because it may be larger than int. If you really need int, then typecast it explicitly, for example: int n = (int)time(0);
1,482,806
1,505,616
Manually incrementing and decrementing a boost::shared_ptr?
Is there a way to manually increment and decrement the count of a shared_ptr in C++? The problem that I am trying to solve is as follows. I am writing a library in C++ but the interface has to be in pure C. Internally, I would like to use shared_ptr to simplify memory management while preserving the ability to pass a raw pointer through the C interface. When I pass a raw pointer through the interface, I would like to increment the reference count. The client will then be responsible to call a function that will decrement the reference count when it no longer needs the passed object.
In your suggestion The client will then be responsible to decrement the counter. means that the client in question is responsible for memory management, and that your trust her. I still do not understand why. It is not possible to actually modify the shared_ptr counter... (hum, I'll explain at the end how to...) but there are other solutions. Solution 1: complete ownership to the client Hand over the pointer to the client (shared_ptr::release) and expect it to pass the ownership back to you when calling back (or simply deleting the object if it is not really shared). That's actually the traditional approach when dealing with raw pointers and it apply here as well. The downside is that you actually release ownership for this shared_ptr only. If the object is actually shared that might prove inconvenient... so bear with me. Solution 2: with a callback This solution means that you always keep ownership and are responsible to maintain this object alive (and kicking) for as long as the client needs it. When the client is done with the object, you expect her to tell you so and invoke a callback in your code that will perform the necessary cleanup. struct Object; class Pool // may be a singleton, may be synchronized for multi-thread usage { public: int accept(boost::shared_ptr<Object>); // adds ptr to the map, returns NEW id void release(int id) { m_objects.erase(id); } private: std::map< int, boost::shared_ptr<Object> > m_objects; }; // class Pool This way, your client 'decrementing' the counter is actually your client calling a callback method with the id you used, and you deleting one shared_ptr :) Hacking boost::shared_ptr As I said it is possible (since we are in C++) to actually hack into the shared_ptr. There are even several ways to do it. The best way (and easiest) is simply to copy the file down under another name (my_shared_ptr ?) and then: change the include guards include the real shared_ptr at the beginning rename any instance of shared_ptr with your own name (and change the private to public to access the attributes) remove all the stuff that is already defined in the real file to avoid clashes This way you easily obtain a shared_ptr of your own, for which you can access the count. It does not solve the problem of having the C code directly accessing the counter though, you may have to 'simplify' the code here to replace it by a built-in (which works if you are not multi-threaded, and is downright disastrous if you are). I purposely left out the 'reinterpret_cast' trick and the pointer offsets ones. There are just so many ways to gain illegit access to something in C/C++! May I advise you NOT to use the hacks though? The two solutions I presented above should be enough to tackle your problem.