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
2,595,770
2,595,839
Exposing an ISO C++ class to C#
I need to expose some C++ classes to C# (I am building on Linux, using mono, so COM is not an option) The evidence I have gathered so far suggests that the best way to approach this is: Write a wrapper C++.Net class around the ISO C++ class Consume the C++.Net classes from C# I have the following questions: First, i...
You can't do C++/.NET classes on Linux using Mono. Mono doesn't support Managed C++ or C++/CLI, so there is no way to "Write a wrapper C++.Net class around the ISO C++ class". Your best option for this is to generate a C API for your C++ class, which can be accessed via Platform Invoke. That being said, one option for...
2,595,849
2,595,884
how can i inherit from both QWidget and QThread?
I have a class like this class GUI : public QWidget, public QThread When I do the above i get errors about connect signals. The error says Reference to "connect" is ambiguous. Is there a way to inherit from both? Thank you
You can't. Both QWidget and QThread inherit (non-virtually) from QObject. You therefore do not have virtual derivation, thus two copies of QObject, which confuses the compiler. QObject was specifically designed this way. See: http://lists.trolltech.com/qt-interest/2006-10/msg00711.html http://www.qtforum.org/article/2...
2,595,920
2,596,280
C++ allocators, specifically passing constructor arguments to objects allocated with boost::interprocess::cached_adaptive_pool
This is an embarrassing question, but even the well-written documentation provided with boost.interprocess hasn't been enough for me to figure out how to do this. What I have is a cached_adaptive_pool allocator instance, and I want to use it to construct an object, passing along constructor parameters: struct Test { ...
cached_adaptive_pool has the method: void construct(const pointer & ptr, const_reference v) but I don't understand what that means and I can't find examples using it. It should follow the interface of std::allocator, in which case allocate() gives you a suitable chunk of uninitialized memory and construct() c...
2,596,275
2,600,141
How to export C++ functions with GCC?
I'm using Code::Blocks to compile a shared library on Ubuntu. When I make a simple main.c file with: void* CreateInterface() { int* x = (int*)malloc( sizeof( int ) ); *x = 1337; return x; } This works fine and I can find the function CreateInterface with dlsym in another application. However, I want the fu...
I've solved the problem by making a .cpp file with the declaration: extern "C" void* CreateInterface() { return new Flow::Render::IRender(); } and a .c file with the header like this: extern void* CreateInterface();
2,596,450
2,596,472
#define and how to use them - C++
In a pre-compiled header if I do: #define DS_BUILD #define PGE_BUILD #define DEMO then in source I do: #if (DS_BUILD && DEMO) ---- code--- #elif (PGE_BUILD && DEMO) --- code--- #else --- code --- #endif Do I get an error that states: error: operator '&&' has no right operand I have never seen this befo...
You need to add the defined keyword since you want to check that you defined have been defined. #if defined (DS_BUILD) && defined (DEMO) ---- code--- #elif defined (PGE_BUILD) && defined (DEMO) --- code--- #else --- code --- #endif
2,596,470
2,596,487
Importing a DllMain winapi .dll into Visual Studio project C++
I have the .def file, .lib file, the .dll, the source files. It's using WINAPI DllMain, all its functions follow that. It's like this: BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } extern "C" { int WINA...
I'm not sure exactly what you're asking for, but I think at the least you'll need to create a .h file for client code to include so it can call functions in the the DLL - otherwise how will the compiler know what the name DoSomething is? The header file should probably look something like: #ifndef DOSOMETHING_H #define...
2,596,500
2,596,549
Circumvent c++ null-terminated string frustration
I'm using boost::program_options and it suffers from the same as many other c++ libs, even std itself: It still uses C-style null-terminated strings, because nobody really likes the weak std::string. The method in question is: options_description_easy_init& operator()(const char* name, const value_semantic* ...
It's pretty strong convention to not hold on to const char*'s beyond the life of a function call like this. As long as they're not bucking this convention, .c_str() is the expected and best way to do what you're trying to do IMO. options.add_options() (key("graphical").c_str(), bool_switch(&isGraphical)->default_v...
2,596,522
2,596,551
C++ standard input from file when debugging from IDE
I'm using VS 2010, and I'm wondering how I can get my c++ program to read a file using standard input while debugging. I know how to do it from command prompt, but not when debugging. Basically I want it to read in a file with cin>> instead of me typing stuff - but in debug mode.
If you go into the project's Properties, under Debugging there's a set of options for how to actually launch the process. IIRC the way to do this is to put: < yourfile.txt In the Command Arguments box.
2,596,588
2,596,633
MFC/CCriticalSection: Simple lock situation hangs
I have to program a simple threaded program with MFC/C++ for a uni assignment. I have a simple scenario in wich i have a worker thread which executes a function along the lines of : UINT createSchedules(LPVOID param) { genProgThreadVal* v = (genProgThreadVal*) param; // v->searcherLock is of type CcriticalSection* ...
Are you sure the background thread is not doing anything that would SendMessage to the UI thread between the Lock and Unlock? If it does, it'll be blocked until the message queue processes that message; however, the message queue will never get to it, since it's blocked in the middle of processing the item changed noti...
2,596,863
2,596,878
How to process all #include directives in Visual Studio C++ 2005?
I want to see how my #include files be processed when Microsoft Visual Studio C++ compile it. As I remember, there is a compile option to inline all #includes and #define lines but I can't find it. I use MSVC 2005 sp1.
The option you are looking for is under your project properties, "C/C++", "Preprocessor" then change "Generate Preprocessed File" to "With Line Numbers" or "Without Line Numbers", whatever you want.
2,596,909
2,596,940
What's correct way to remove a boost::shared_ptr from a list?
I have a std::list of boost::shared_ptr<T> and I want to remove an item from it but I only have a pointer of type T* which matches one of the items in the list. However I cant use myList.remove( tPtr ) I'm guessing because shared_ptr does not implement == for its template argument type. My immediate thought was to try ...
enable_shared_from_this can help with your problem, but it will require that the types you're using in the list derive from it: http://www.boost.org/doc/libs/1_42_0/libs/smart_ptr/enable_shared_from_this.html If the type enables that functionality, you can get the shared pointer from the object itself by calling shar...
2,596,934
2,598,483
How to draw an Arc in OpenGL
While making a little Pong game in C++ OpenGL, I decided it'd be fun to create arcs (semi-circles) when stuff bounces. I decided to skip Bezier curves for the moment and just go with straight algebra, but I didn't get far. My algebra follows a simple quadratic function (y = +- sqrt(mx+c)). This little excerpt is just...
What is the purpose of sqrtf((-currentX * arcAngle)+ arcWidth)? When i>25, that expression becomes imaginary. The proper way of doing this would be using sin()/cos() to generate the X and Y coordinates for a semi-circle as stated in your question. If you want to use a parabola instead, the cleaner way would be to calcu...
2,596,953
2,596,970
Multiply char by integer (c++)
Is it possible to multiply a char by an int? For example, I am trying to make a graph, with *'s for each time a number occurs. So something like, but this doesn't work char star = "*"; int num = 7; cout << star * num //to output 7 stars
I wouldn't call that operation "multiplication", that's just confusing. Concatenation is a better word. In any case, the C++ standard string class, named std::string, has a constructor that's perfect for you. string ( size_t n, char c ); Content is initialized as a string formed by a repetition of character c, n tim...
2,597,116
2,597,398
Is extending a base class with non-virtual destructor dangerous?
In the following code: class A { }; class B : public A { }; class C : public A { int x; }; int main (int argc, char** argv) { A* b = new B(); A* c = new C(); //in both cases, only ~A() is called, not ~B() or ~C() delete b; //is this ok? delete c; //does this line leak memory? return 0; } When c...
So everyone has been saying you cant do it - it leads to undefined behaviour. However there are some cases where it is safe. If you are never creating instances of your class dynamically then you should be OK. (i.e. no new calls) That said, it is generally considered a bad thing to do as someone might try to create one...
2,597,157
2,597,341
Get a QWidget to take up the entire QMainWindow
I have a class that inherits QMainWindow and I just want it to have a webview widget and nothing else, so here's what I tried doing for constructor: MyWindow::MyWindow(QWidget *parent) : QMainWindow(parent) { this->_webView = new QWebView(this); this->setCentralWidget(this->_webView); } This didnt work do I ha...
Just get rid of the QMainWindow and use QWebView as the top level widget. If you're not going to use any of the features of QMainWindow then there's no reason to use it.
2,597,534
2,597,664
Is there a way to display icons in QListView without text?
Using a QListView, and QStandardItemModel, is it possible to display icons in the list view without displaying the associated text? QStandardItem is defined as so: QStandardItem ( const QIcon & icon, const QString & text ) So it seems to require a text string of some sort - I only want the icon displayed. If I use...
Yes, you can do. first you create a delegate associated with the list-view.Then, While inserting the elements to the listview, use set-data function to insert the icon and in the paint event of delegate you handle the drawing icon. i hope its clear.
2,597,996
2,598,041
precompiled header .pch files are machine sensitive?
I tried to reuse the .pch to speed the build using the following way: use /Yc on stdafx.cpp to create the .pch files to a folder exclude stdafx.cpp in the project, and modify the link option It success in my machine, but failed in another, got the error message: error C2011: '***' : 'struct' type redefinition So firs...
Precompiled headers can be machine specific up to Visual Studio 2008 SP1 (from here): Precompiled header files store the “state” of a compilation up to a certain point, and that state information can be reused in subsequent compiler invocations to significantly increase build throughput. For the past 15 ye...
2,598,084
2,598,093
Function with missing return value, behavior at runtime
As expected, the compiler (VisualStudio 2008) will give a warning warning C4715: 'doSomethingWith' : not all control paths return a value when compiling the following code: int doSomethingWith(int value) { int returnValue = 3; bool condition = false; if(condition) // returnValue += value; // D...
It is Undefined behaviour as specified in the ISO C++ standard section 6.6.3: Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
2,598,132
2,598,140
length of va_list when using variable list arguments?
Is there any way to compute length of va_list? All examples I saw the number of variable parameters is given explicitly.
There is no way to compute the length of a va_list, this is why you need the format string in printf like functions. The only functions macros available for working with a va_list are: va_start - start using the va_list va_arg - get the next argument va_end - stop using the va_list va_copy (since C++11 and C99) - copy...
2,598,178
2,598,272
Is there any reasonable use of a function returning an anonymous struct?
Here is an (artificial) example of using a function that returns an anonymous struct and does "something" useful: #include <iostream> template<typename T> T* func(T* t, float a, float b) { if(!t) { t = new T; t->a = a; t->b = b; } else { t->a += a; t->b += b; } r...
For now, your code is not portable; it will, for example, not build with gcc. Section 14.3.1/2 of the standard says: A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template- argument for a template type-parameter. See item ...
2,598,394
2,598,538
Timestamp issue with localtime and mktime
Please see the code below: #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int main(void) { time_t current_time = 1270715952; cout << "Subscriber current timestamp:" << current_time << endl; tm* currentTm = localtime(&current_time); char tmp_str[256]; //201...
I think the problem is that you set tm_isdst to 0, which means no DST, however localtime() uses system-wide DST settings. If you set tm_isdst to 1, everything should be ok. According to man mktime, you can set negative value for tm_isdst if you are not sure about it. man doesn't say it explicitly but I guess in this ca...
2,598,401
2,599,608
C++: Failure to get data through pipe when using wide strings in both programs
I’m trying to use the following code in C++ on Mac OS X Snow Leopard to get the output of an external program through a pipe. FILE * al = popen("program program.cfg", "r"); string data; char buffer[100]; while (fgets(buffer, 100, al) != NULL) data.append(buffer); cout << "«" << data << "»" << endl; pclose(al); Howev...
It turned out that I was overwriting a file the external program used for input, so it did not give any output… Still, it’s nice to have the above snippets at one place, as it wasn’t straightforward to decipher the Boost documentation.
2,598,486
2,598,523
Safe division function
I would like to define some kind of safe division (and modulo) function, one that would return some predefined value when attempting to divide by zero. I don't want to throw exceptions, just to return some "reasonable" value (1? 0?) and continue the program flow. Obviously there is no correct return value, but I wonder...
The IEEE floating point standard defines what to get from a division by zero. +a / +0 gives +Inf +a / -0 gives -Inf 0 / 0 gives NaN If you work with integers, you can use this standard to define your own routine, but you have to define what is Inf and what is NaN in integer logic.
2,598,516
2,598,797
C++ Array of Variable sized Arrays
I am very new to C++ and I realise the following is not necessarily as easy as I'd like it to be, but I'd really appreciate a more expert opinion. I am essentially trying to achieve a dynamic iteration over a variable sized array of variable sized arrays similar to the following. String *2d_array[][] = {{"A1","A2"},{"B...
You are using a plain C array of C++ string objects. In C there are no variable sized arrays. Besides that this code wont compile anyway, in such a construct the compiler will generate a array of arrays that have the maximum length declared. In the sample case that would be String *2d_array[3][3] If you want variable...
2,598,535
2,598,689
About enumerations in Delphi and c++ in 64-bit environments
I recently had to work around the different default sizes used for enumerations in Delphi and c++ since i have to use a c++ dll from a delphi application. One function call returns an array of structs (or records in delphi), the first element of which is an enum. To make this work, I use packed records (or aligned(1)-s...
There is no 64bits compiler for Delphi so you can't compile your program for 64bits. However, you can still compile it and run it on a 64bit OS as a 32 bits process. in that case, noting will happens to your structures. The question of the library is a bit more complex: if you compile it as a 64 bits library, you won't...
2,598,569
2,598,678
toupper/tolower + locale (german)
how to convert a string (wstring) from lowercase to uppercase characters and vice versa? I searched the net and found there is a STL-function std::transform. But until now I hav'nt figured out how to give the right locale-object for example "Germany_german" to the function. Who can help please? my code looks like: w...
If you're on Unix, see /usr/share/locale/ for available locales. It looks like you want "de_DE.UTF-8". But setlocale(LC_ALL, ""); should set the program to work in the system's locale, whatever it is. Your program works for me (I fixed a close-paren) if I simply set the default locale like that, without specifying Germ...
2,598,579
2,598,596
C++ Expression Templates
I currently use C for numerical computations. I've heard that using C++ Expression Templates is better for scientific computing. What are C++ Expression Templates in simple terms? Are there books around that discuss numerical methods/computations using C++ Expression Templates? In what way, C++ Expression Templates a...
What are C++ Expression Templates in simple terms? Expression templates are a category of C++ template meta programming which delays evaluation of subexpressions until the full expression is known, so that optimizations (especially the elimination of temporaries) can be applied. Are there books around that discuss...
2,598,965
2,598,983
gethostbyname replacement for IPv6 addresses
I have a program that uses gethostbyname (in Windows) in order to convert IP address to hostname. But, it works only for IPv4... What is the correct replacement for IPv6? Thanks.
Looking up gethostbyname in MSDN tells us that it's deprecated and we should look at getaddrinfo, which has all kinds of options for dealing with other addressing families. Or if you're doing address to name translation, you'll end up at getnameinfo
2,599,036
2,605,171
How do you debug c/c++ source code in linux using emacs?
I am using emacs and autotools, to write and compile c/c++ sources on linux. I am using gdb via GUD in emacs. I have defined for convenience: F7:compile, F10:gud-next, F11:gud-step, F5:gud-cont, F9:gud-tbreak, F8:gud-until, F4:gud-print. I am mainly interested in debugging c/c++ source code on linux from emacs and I wo...
You'll get the most out of gdb by using the command line instead of key bindings. The most useful commands that I use: bt - prints a backtrace; helpful to know full context of where you are s, n, cont - step, next, continue run - very useful for starting over within the same session watch - sets a watchpoint; useful ...
2,599,211
2,599,625
C++ dynamic type construction and detection
There was an interesting problem in C++, but it was more about architecture. There are many (10, 20, 40, etc) classes describing some characteristics (mix-in classes), for example: struct Base { virtual ~Base() {} }; struct A : virtual public Base { int size; }; struct B : virtual public Base { float x, y; }; struct C...
The real problem here is about what you are trying to achieve. Do you want something like: void operate(A-B& ) { operateA(); operateB(); } // OR void operate(A-B& ) { operateAB(); } That is, do you want to apply an operation on each subcomponent (independently), or do you wish to be able to apply operations dependin...
2,599,658
2,599,969
C++ library for Coordinate Transformation Matrices (CTM)?
I'm looking for a C++ library which allows for easy integration of Coordinate Transformation Matrices (CTM) in my application. You might know CTMs from PDF or PostScript. For one project we are using C++/Qt4 as a framework, which offers a QTransform class, which provides methods like .translate(double x, double y) or ....
Why not just use Qt? It does what you want, is open source (LGPL I think) and you should be able to link just against the QTransform class.
2,599,795
2,609,695
UnitTest++ creates cmd windows, which can't be closed
I have a setup for using UnitTest++ like this in VS2008. Sometimes the cmd window, which shows the console output of the unit tests just hangs. I can move the window, resize and stuff, but I'm unable to close it. I see the window in the App tab of the Task Manager, but not in the Process tab, "Switch to process" doesn...
See Unkillable console windows
2,599,809
2,599,872
No whitespace between a cast and a namespace operator?
Could anyone please explain the following line of code, found on http://docs.openttd.org/ai__cargo_8cpp_source.html return (AICargo::TownEffect)::CargoSpec::Get(cargo_type)->town_effect; If this line was: return (AICargo::TownEffect) ::CargoSpec::Get(cargo_type)->town_effect; (note the space between TownEffect) and t...
Other than separating tokens, white space is generally not significant in C++ grammar. Parentheses are significant, and they can't appear in a qualified-id so there is no equivalence between: (AICargo::TownEffect)::CargoSpec::Get and AICargo::TownEffect::CargoSpec::Get In the first there are two qualified-ids, one in...
2,599,844
2,602,887
ideas for a distributed cache proxy server
I am implementing, a distributed cache proxy server.I have an idea of the HTTP and related stuff, so i am rather concentrating on the sub part "Distributed data storage". From some search on web i found that this could be done using Distributed Hash Tables(DHT). I was wondering if there exists some kind of library for ...
Have you looked at Kademlia? There's KadC (C) and maidsafe-dht (C++) for it.
2,599,990
2,600,090
Looking for a safe, portable password-storage method
I'm working on C++ project that is supposed to run on both Win32 and Linux, the software is to be deployed to small computers, usually working in remote locations - each machine likely to contain it's own users/service-men pool. Recently, our client has requested that we introduce access control via password protection...
You could use a SQLite database. As it's just a file you can use standard file permissions to restrict access. e.g. chmod 600 foo.dbs will restrict access to the file so that only the owner can read/write to it. Then as others have suggested you store a hashed password in the database and it'll be reasonably secure. R...
2,600,100
2,602,285
how to determine base of a number?
Given a integer number and its reresentation in some arbitrary number system. The purpose is to find the base of the number system. For example, number is 10 and representation is 000010, then the base should be 10. Another example: number 21 representation is 0010101 then base is 2. One more example is: number is 6 an...
An algorithm like this should find the base if it is an integer, and should at least narrow down the choices for a non-integer base: Let N be your integer and R be its representation in the mystery base. Find the largest digit in R and call it r. You know that your base is at least r + 1. For base == (r+1, r+2, ......
2,600,152
2,600,328
Initialising a reference member with itself legal?
This was a bug I found in a server application using Valgrind. struct Foo { Foo(const std::string& a) : a_(a_) { } const std::string& a_; }; with gcc -Wall you don't get a warning. Why is this legal code?
What you've got violates 8.3.2/4 A ... reference shall be initialized to refer to a valid object or function. So it is most certainly illegal. Note that not all erroneous programs are required to be detected by the compiler, although I honestly would have thought this was one of them. For what it's worth, g++ vers...
2,600,336
2,600,610
How to initialize 4th position only in Array of 5 positions
I wanted to store 10 in 4th position of array of 5 positions. How to do ? int main( ) { int a[5] = {,,,,4} ; return 0; } If i do that i get error. Please help. Thanks in advance.
I suppose you can use placement new. int arr[4]; //uninitialized new (&arr[3]) int(10); //"initializes"
2,600,385
2,600,679
C++ nested class/forward declaration issue
Is it possible to forward-declare a nested class, then use it as the type for a concrete (not pointer to/reference to) data member of the outer class? I.E. class Outer; class Outer::MaybeThisWay // Error: Outer is undefined { }; class Outer { MaybeThisWay x; class MaybeThatOtherWay; MaybeThatOtherWay y; // E...
You can't forward-declare a nested class like that. Depending on what you're trying to do, maybe you can use a namespace rather than a class on the outer layer. You can forward-declare such a class no problem: namespace Outer { struct Inner; }; Outer::Inner* sweets; // Outer::Inner is incomplete so ...
2,600,395
2,600,453
VS2005 C++: strange linking problem
I have some strange linking problem in my Visual Studio 2005 C++ project. As always, I declare class in a header and define it's methods in cpp. A have all these files included in my project. And I still have the unresolved external symbol calcWeight. It appears if I actually use this class in my main function. calcWe...
What happens if you remove "inline" from your declaration and definition of calcWeight?
2,600,505
2,600,530
C++ Class Inheritance architecture - preventing casting
I have a structure of base class and a couple of inherited classed. Base class should be pure virtual class, it should prevent instantiation. Inherited classes can be instantiated. Code example below: class BaseClass { public: BaseClass(void); virtual ~BaseClass(void) = 0; }; class InheritedClass : public Base...
Make the copy constructor and the assignment operator in BaseClass protected. The class is non-creatable already, so you don't need public copy-constructor and assignment operators. With protected copy constructor and assignments operators you can call it from the derived classes constructors and assignment operators.
2,600,585
2,603,655
Emacs, Cedet and semantic
I've configured CEDET for emacs following Alex article (great!!). Now, the questions: I've generated GTAGS with Gnu Global in my /usr/include, how can i check if semantic is using GTAGS? Can I keep my GTAGS in another directory and instruct semantic to use that dir? In C/C++ sources, completion on include statement (...
You can use the command: M-x semantic-c-describe-environment RET to find out about your include path and CPP macro settings. To test GNU Global use, you can use: M-x semanticdb-test-gnu-global RET printf RET to search for "printf" in in some project. Since your project (perhaps in /home/you/myproject) does not have ...
2,600,616
2,600,700
How can one enforce calling a base class function after derived class constructor?
I'm looking for a clean C++ idiom for the following situation: class SomeLibraryClass { public: SomeLibraryClass() { /* start initialization */ } void addFoo() { /* we are a collection of foos */ } void funcToCallAfterAllAddFoos() { /* Making sure this is called is the issue */ } }; class SomeUserClass : ...
I would probably implement this with a factory of some sort. The following code should be read as pseudocode, I haven't tried compiling it or anything. class LibraryClass { public: template<typename D> static D *GetNewInstance() { // by assigning the new D to a LibraryClass pointer, you guarantee it der...
2,600,676
2,601,827
Tokenizer for full-text
This should be an ideal case of not re-inventing the wheel, but so far my search has been in vain. Instead of writing one myself, I would like to use an existing C++ tokenizer. The tokens are to be used in an index for full text searching. Performance is very important, I will parse many gigabytes of text. Edit: Plea...
I wrote my own tokenizer as part of the open-source SWISH++ indexing and search engine. There's also the the ICU tokenizer that handles Unicode.
2,600,682
7,362,512
How to make ATL control persistence future proof?
I have a custom button control created using ATL. This control is used by some composite controls and lots of dialog boxes. I just added some new properties to the button control and found that I then had to update all the controls and dialogs that used it. This is a really poor situation so I wondered if I could be...
I used to slightly modify ATL persistence classes to implement a simple thing. When loading from stream, before starting each property the implementation checks if we are already at the end of stream and if so, it exits the loop assuming that unloaded properties are left initialized by default. From there on, you can a...
2,600,874
2,618,259
Symbol Not Found, expected in Flat Namespace ObjC++
I've got probably what is a simple problem, but there's no informative errors or warnings during compile to alert me to what is going wrong. I've got a Objective-C++ app that includes a C++ main and ObjC header files. It builds fine, but when run, it gives this error message: Dyld Error Message: Symbol not found: _OB...
Clearly the AppController class is missing. Is the AppController class defined in a framework of dynamic library? If so, when you run the app, does it know where to find the libraries/frameworks? This is a linker issue, by the way. The header files are irrelevant. It's the .m or .mm files you need to look at.
2,601,161
2,601,499
C++ Pointer trouble with File I/O
I am writing a function that takes in a output target file and a couple of other arguments. I am currently having trouble with converting types between the argument passed in and using it in the fopen_s() method. FILE* outputf; void myfunc(FILE* fin, CString finpath,...) { outputf = fopen_s(&fin, finpath, "w"); ....
Looks like I found my answer. Turns out that fopen_S doesn't allow shared access to the FILE* specified for opening. I had to use _fsopen instead and that solced my problem!
2,601,290
2,601,402
"Unhandled exception" error when mixing boost::thread with wxWidgets GUI
I was trying to access a wxDialog members from a boost::thread: void AnotherThread(myWxDialog *dlg) { wxMessageBox(dlg->TextBox1->GetValue(), "It works!"); // This throws an error } void myWxDialog::OnButtonClick(wxCommandEvent &event) { boost::thread myThread(AnotherThread, this); } And I got this error: Unhandl...
0xbaadf00d indicates that you're dereferencing an uninitialized pointer; if I were you I'd dig deeper with the debugger to see exactly where that pointer is (in dlg? in TextBox1? in what GetValue() returns? Somewhere else in wxMessageBox?). This would help you to understand where is the problem. Still, the biggest faul...
2,601,370
2,601,854
C++/MFC: Handling multiple CListCtrl's headers HDN_ITEMCLICK events
I'm coding an MFC application in which i have a dialog box with multiple CListCtrls in report view. I want one of them to be sortable. So i handled the HDM_ITEMCLICK event, and everything works just fine .. Except that if i click on the headers of another CListCtrl, it does sort the OTHER CListCtrl, which does look ki...
Ok i found a solution, though i find it a bit dirty but it works, so i'll post it for future reference. You can get the Header through the GetHeaderCtrl member function of CListCtrl. You can then get it's handler thru m_hWnd. So all you got to do is to test if that handler is the same as the one in the NMHDR structure,...
2,601,630
2,601,672
Which HRESULT literal constant will fail the SUCCEEDED() macro?
Definition of SUCCEEDED(): #define SUCCEEDED(hr) (((HRESULT)(hr)) >= 0) Background: When an Ok button is clicked on a dialog, I need to return an HRESULT value hr such that SUCCEEDED(hr) is true. If Cancel button is clicked, I need to return a negative value. I could have used bools, but that would break the existing p...
Typical values are shown here: http://msdn.microsoft.com/en-us/library/aa378137(VS.85).aspx E_FAIL or E_ABORT seem the most obvious.
2,601,798
2,603,449
Adding compiled libraries and include files to a CMake Project?
What is the best method to include a prebuilt library to a cmake project? I want to include FreeType into the project I am working on and the file structure is like this: Build MacOS Make/ XCode/ Windows VisualStudio/ Source libs MacOS libfreetype Windows freetype.dll ...
Recent versions already have a module for finding FreeType. Here's the kind of thing I've done in the past: INCLUDE(FindFreetype) IF(NOT FREETYPE_FOUND) FIND_LIBRARY(FREETYPE_LIBRARIES NAMES libfreetype freetype.dll PATHS "./libs/MacOS" "./libs/Windows" DOC "Freetype library") FIND_PATH(FREETYPE_INCLUDE_DIRS ftbui...
2,601,869
2,602,116
Using Valgrind tool how can I detect which object trying to access 0x0 address?
I have this output when trying to debug Program received signal SIGSEGV, Segmentation fault 0x43989029 in std::string::compare (this=0x88fd430, __str=@0xbfff9060) at /home/devsw/tmp/objdir/i686-pc-linux-gnu/libstdc++-v3/include/bits/char_traits.h:253 253 { return memcmp(__s1, __s2, __n); } Current langu...
You don't need to use Valgrind, in fact you want to use the GNU DeBugger (GDB). If you run the application via gdb (gdb path_to_my_executable_file/executable_file) and you've compiled the application with debugging enabled (-g or -ggdb for GNU C/C++ compilers), you can start the application (via run command at the gdb ...
2,601,902
2,601,977
passing structure directly to function
I have a struct that I initialize like this: typedef struct { word w; long v; } MyStruct; MyStruct sx = {0,0}; Update(sx); Now, it seems such a waste to first declare it and then to pass it. I know that in C#, there's a way to do everything in one line. Is there any possiblity of passing it in a more clever (read:...
It depends on how your Update is declared. If it expects a value of MyStruct type or a reference of const MyStruct& type, you can just do Update(MyStruct()); This is possible because you wanted to initialize your object with zeroes (which is what the () initializer will do in this case). If you needed different (non-z...
2,601,916
2,602,021
C++ Memory Leak, Can't find where
I'm using Visual Studio 2008, Developing an OpenGL window. I've created several classes for creating a skeleton, one for joints, one for skin, one for a Body(which is a holder for several joints and skin) and one for reading a skel/skin file. Within each of my classes, I'm using pointers for most of my data, most of wh...
In this code: Body *body = new Body(); body->readSkel("C:\\skel2.skel"); body->drawBody(); body = new Body(); you're leaking a Body because you don't delete the first one. And this: body->~Body(); delete body; is just weird. You don't explicitly call destructors like that - the delete takes care of calling the destr...
2,602,013
2,602,060
Read whole ASCII file into C++ std::string
I need to read a whole file into memory and place it in a C++ std::string. If I were to read it into a char[], the answer would be very simple: std::ifstream t; int length; t.open("file.txt"); // open input file t.seekg(0, std::ios::end); // go to the end length = t.tellg(); // report location (this i...
Update: Turns out that this method, while following STL idioms well, is actually surprisingly inefficient! Don't do this with large files. (See: http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html) You can make a streambuf iterator out of the file and initialize the string with it: #include <string> ...
2,602,254
2,602,308
Member function pointers in a hierarchy
I'm using a library that defines an interface: template<class desttype> void connect(desttype* pclass, void (desttype::*pmemfun)()); and I have a small hierarchy class base { void foo(); }; class derived: public base { ... }; In a member function of derived, I want to call connect(this, &derived::foo); but it se...
Firstly, when you do &class::member the type of the result is always based on the class that member actually declared in. That's just how unary & works in C++. Secondly, the code does not compile because the template argument deduction fails. From the first argument it derives that desttype = derived, while from the se...
2,602,312
2,671,399
Compiling Havok demos
I've downloaded and extracted the Havok demos, but the project has dependency on a folder: $(HAVOK_SDKS_DIR)/win32/dx/Include But it didn't set up a HAVOK_SDKS_DIR (there is no installer), and I can't find a win32/dx directory anywhere in the extracted Havok package. How can I get the demo files to build? What am I mi...
I fixed this by simply REMOVING all references to $(HAVOK_SDKS_DIR) from the project settings. You don't need it.
2,602,724
2,603,000
Can I use QSharedData while inheriting from QObject?
How do I hide the private implementation (implicit sharing) in Qt: I have Employee.cpp the following in my Employee.h header: #include <QSharedData> #include <QString> class EmployeeData; class Employee: public QObject { Q_OBJECT public: Employee(); Employee(int id, QString name); Employee(const E...
Thus, can I use QSharedData while inheriting from QObject ? You cannot inherit from QObject when using QSharedData. QSharedData uses copy-on-write semantics and will call detach() to create a copy of the data when it's no longer being shared. In order to do the copy, a copy-constructor is needed, which QObject does ...
2,602,823
2,602,836
In C/C++ what's the simplest way to reverse the order of bits in a byte?
While there are multiple ways to reverse bit order in a byte, I'm curious as to what is the "simplest" for a developer to implement. And by reversing I mean: 1110 -> 0111 0010 -> 0100 This is similar to, but not a duplicate of this PHP question. This is similar to, but not a duplicate of this C question. This questio...
If you are talking about a single byte, a table-lookup is probably the best bet, unless for some reason you don't have 256 bytes available.
2,602,874
2,602,909
How to use enumeration types in C++?
I do not understand how to use enumeration types. I understand what they are, but I don't quite get their purpose. I have made a program that inputs three sides of a triangle and outputs whether or not they are isosceles, scalene, or equilateral. I'm suppose to incorporate the enumeration type somewhere, but don't get ...
It's a value, and you probably want to return it from your function. Try: triangleType triangleShape(double x, double y, double z) { if (...) { return scalene; } else if (...) { return isosceles. } else if (...) { return equilateral } else { return noTriangle; } } Note, you can print the res...
2,603,095
2,603,233
Change Name of Outputted DLL
If my project name is ABC and the DLL currently outputs as ABC.DLL, how can I make my DLL be outputted as say CBA.DLL and so that when the .LIB is compiled linked against, it is not looking for ABC.DLL, but CBA.DLL. I tried changing the name under Linker > General > Output File but when I linked to the .lib in my other...
No repro, the .lib file has the correct DLL name. The original name is not present at all. But, don't make the same mistake I first made. Use cba.lib, not abc.lib.
2,603,271
2,603,301
Placement new in gcc
I need to find a workaround for a bug with placement new in g++. I now it was fixed in gcc-4.3 but I have to support versions 4.2 and 4.1. For example, following code compiles with an error "error: no matching function for call to 'operator new(long unsigned int, void*&)" template<class T, template<typename> class Allo...
To use the standard library placement news, you have to #include <new>.
2,603,276
10,627,669
How do I clear a Direct2D render target to fully transparent
I'm trying to draw semi-transparent rectangles on an invisible HWND. However, clearing the window with ID2D1HwndRenderTarget::Clear just makes the entire window black, so when I draw rectangles on top, they look semi-black. If I don't Clear() and don't draw, then the window is invisible, as it should be. Clear() is the...
When creating your RenderTarget, you'll have to tell D2D that you want to use alpha (in premultiplied mode) in the pixel format: HRESULT hr = mD2DFactory->CreateHwndRenderTarget( D2D1::RenderTargetProperties( D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat( DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED ) ...
2,603,279
2,603,335
Are C/C++/ObjC/Swift/JS Apple's only allowed languages for iPhone development?
According to this post on Daring Fireball a new iPhone SDK Agreement release in conjunction with the iPhone OS 4.0 announcement today specifically bans any iPhone application not implemented in C, C++ Objective-C or JavaScript. The clear impact here is to the wide array of programs written in languages other than those...
Apple has had a ban on interpreted languages on the iPhone for a while now, but yes, I suppose this makes the ban more clear and more precise. I imagine that yes, Apple is saying that if you use a language other than C, C++, Objective-C, or JavaScript, you run the risk of having your app rejected from the App Store on ...
2,603,312
2,603,349
The result of int c=0; cout<<c++<<c;
I think it should be 01 but someone says its "undefined", any reason for that?
c++ is both an increment and an assignment. When the assignment occurs (before or after other code on that line) is left up to the discretion of the compiler. It can occur after the cout << or before. This can be found in the C99 standard http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1124.pdf You can find it on p...
2,603,314
2,604,157
forward/strong enum in VS2010
At http://blogs.msdn.com/vcblog/archive/2010/04/06/c-0x-core-language-features-in-vc10-the-table.aspx there is a table showing C++0x features that are implemented in 2010 RC. Among them are listed forwarding enums and strongly typed enums but they are listed as "partial". The main text of the article says that this m...
I think I found the answer. I found "enum class" in the VS 2010 documentation under the keywords documentation. It's managed only--unsupported in real C++ builds. So it seems that they mean this C++0x feature is "partially done" in that it isn't done at all.
2,603,583
2,603,767
Boost Thread Hanging on _endthreadex
I think I am making a simple mistake, but since I noticed there are many boost experts here, I thought I would ask for help. I am trying to use boost threads(1_40) on windows xp. The main program loads a dll, starts the thread like so (note this is not in a class, the static does not mean static to a class but private...
You are not supposed to create/end threads in InitInstance/ExitInstance, see http://support.microsoft.com/default.aspx?scid=kb;EN-US;142243 for more info. Also, see http://msdn.microsoft.com/en-us/library/ms682583%28VS.85%29.aspx about DllMain in general.
2,603,611
2,603,845
write a program that prompts the user to input five decimal numbers
This is the question. write a program that prompts the user to input five decimal numbers. the program should then add the five decimal numbers, convert the sum to the nearest integer,m and print the result. This is what I've gotten so far: // p111n9.cpp : Defines the entry point for the console application. // #inclu...
"declare m" means say int m; if you say m = (int)f; // it means the int value of f is assigned to m. The casting is actually not even necessary here: m=f; //works just as well now you can print m cout<<m;
2,603,917
2,604,080
Generic FSM for game in C++?
I was wondering if there's a way I could code some kind of "generic" FSM for a game with C++?. My game has a component oriented design, so I use a FSM Component. my Finite State Machine (FSM) Component, looks more or less this way. class gecFSM : public gecBehaviour { public: //Constructors gecFSM() { state ...
Have a look at the Boost Statechart Library. (formerly known as boost::fsm) It comes with a very nice photo camera example.
2,604,201
2,604,292
Inter process communication C# <--> C++ for game debugging engine
I am working on a debugger project for a game's scripting engine. I'm hoping to write the debugger's GUI in C#. The actual debugging engine, however, is embedded in the game itself and is written in a mixture of C, C++, and assembly patches. What's the best way to handle communication between the debugger GUI and the d...
If you can require Windows Vista or later, and .Net 3.5 or later, Named Pipes provide simple, high-performance IPC. Check out this article.
2,604,202
2,604,216
C++ extern keyword on functions. Why no just include the header file?
If I understand it correctly this means extern void foo(); that the function foo is declared in another translation unit. 1) Why not just #include the header in which this function is declared? 2) How does the linker know where to look for function at linking time? edit: Maybe I should clarify that the above declarati...
1) It may not have a header file. But yes, in general, for large projects, you should have a header file if multiple translation units are going to use that function (don't repeat yourself). 2) The linker searches through all the object files and libraries it was told about to find functions and other symbols.
2,604,206
2,604,269
C++ constant reference lifetime (container adaptor)
I have code that looks like this: class T {}; class container { const T &first, T &second; container(const T&first, const T & second); }; class adapter : T {}; container(adapter(), adapter()); I thought lifetime of constant reference would be lifetime of container. However, it appears otherwise, adapter object is...
According to the C++03 standard, a temporary bound to a reference has differing lifetimes depending on the context. In your example, I think the highlighted portion below applies (12.2/5 "Temporary objects"): The temporary to which the reference is bound or the temporary that is the complete object to a subobject of ...
2,604,358
2,605,585
From where starts the process' memory space and where does it end?
On Windows platform, I'm trying to dump memory from my application where the variables lie. Here's the function: void MyDump(const void *m, unsigned int n) { const unsigned char *p = reinterpret_cast<const unsigned char *>(m); char buffer[16]; unsigned int mod = 0; for (unsigned int i ...
Overview What you're trying to do is absolutely possible, and there are even tools to help, but you'll have to do more legwork than I think you're expecting. In your case, you're particularly interested in "where the variables lie." The system heap API on Windows will be an incredible help to you. The reference is real...
2,604,541
2,605,828
How can I use ToUnicode without breaking dead key support?
A similar question has already been asked, so I'm not going to waste time re-explaining it, an existing discussion can be found here: ToAscii/ToUnicode in a keyboard hook destroys dead keys The reason I'm posting a new question however is that I seem to have come across a 'solution', but I'm not quite sure how to imple...
The first part of the answer is entirely information-free. However, the second part does make sense. ToUnicode() should have been a pure function, which merely acts as a lookup. However, it isn't. But you can call it repeatedly for all expected inputs, store those in your own lookup table and access that. I'd recommend...
2,604,715
2,612,145
Add functions in gdb at runtime
I'm trying to debug some STL based C++ code in gdb. The code has something like int myfunc() { std::map<int,int> m; ... } Now in gdb, inside myfunc using "print m" gives something very ugly. What I've seen recommended is compiling something like void printmap( std::map<int,int> m ) { for( std::map<int,int>::...
So my solution is to load a shared object containing my debugging routines at run time, using dlopen. Turns out it is even simpler than I thought when you get all the compile flags right. On OS X this means you compile your application and debugging object like this: all : application.x debug_helper.so application.x :...
2,604,748
2,604,766
operator+ overload returning object causing memory leaks, C++
The problem I think is with returning an object when i overload the + operator. I tried returning a reference to the object, but doing so does not fix the memory leak. I can comment out the two statements: dObj = dObj + dObj2; and cObj = cObj + cObj2; to free the program of memory leaks. Somehow, the problem is with ...
you need to declare copy constructor since you are returning object in overloaded operator +, the compiler automatically generates one for you if you dont explicitly define it, but compiler are stupid enough to not do deep copy on pointers to summarize your mistake in the code posted: 1.) No Copy-Constructor/Assignment...
2,604,847
2,604,859
How to read values from file. tokenizer
I have a file in which each line contains two numbers. The problem is that the two number are separated by a space, but the space can be any number of blank spaces. either one, two, or more. I want to read the line and store each of the numbers in a variable, but I'm not sure how to tokenize it. i.e 1 5 3 2 5 6 3 4...
Read each line, stick the contents of the line into a stringstream, and then read the two int out of the line: std::string line; while (std::getline(myfilestream, line)) { std::stringstream ss(line); int i, j; if (ss >> i >> j) { // use i and j } } If you know for a fact that each line will...
2,605,099
2,605,108
c++ process always on foreground in window OS
I have a c++ process, I want that process should always remain on foreground, kindly guide me how can I make it possible?
It is not possible since user always has an option to switch to another application. This is by design. Good link from Billy ONeal: How do I create a window that is never covered by any other windows, not even other topmost windows? Imagine if this were possible and imagine if two programs did this. Program A creates ...
2,605,352
2,605,370
How is destroying local variables when a block is exited normally called in C++?
C++ automagically calls destructors of all local variables in the block in reverse order regardless of whether the block is exited normally (control falls through) or an exception is thrown. Looks like the term stack unwinding only applies to the latter. How is the former process (the normal exit of the block) called c...
An object is automatically destructed when it "goes out of scope". This could be referred to as "automatic storage reclamation", but that actually refers to garbage collection (there are several papers with that phrase in their name that use the term to mean garbage collection). When it is used to ensure proper pairing...
2,605,427
2,606,152
C++ How to get a filename (and path) of the executing .so module in Unix
C++ How to get a filename (and path) of the executing .so module in Unix? Something similar to GetModuleFileName on Windows.
Although it is not a POSIX standard interface, the dladdr() function is available on many systems including Linux, Solaris, Darwin/Mac OS X, FreeBSD, HP-UX, and IRIX. This function takes an address, which could be a pointer to a static function within the module for example (if cast to void *), and fills in a Dl_info ...
2,605,520
2,605,559
C++ where to initialize static const
I have a class class foo { public: foo(); foo( int ); private: static const string s; }; Where is the best place to initialize the string s in the source file?
Anywhere in one compilation unit (usually a .cpp file) would do: foo.h class foo { static const string s; // Can never be initialized here. static const char* cs; // Same with C strings. static const int i = 3; // Integral types can be initialized here (*)... static const int j; // ... OR in cpp. }...
2,605,593
2,605,918
What's the correct way to do a 'catch all' error check on an fstream output operation?
What's the correct way to check for a general error when sending data to an fstream? UPDATE: My main concern regards some things I've been hearing about a delay between output and any data being physically written to the hard disk. My assumption was that the command "save_file_obj << save_str" would only send data to s...
Everything except for the check after the close seems reasonable. That said, I would restructure things slightly differently and throw an exception or use a bool, but that is simply a matter of preference: bool Saver::output() { std::fstream out(_filename.c_str(),std::ios::out); if ( ! out.is_open() ){ ...
2,605,603
2,605,623
Declaration and initialization of local variables - what is most C++ like?
I did not find any suitable questions answered yet, so I'd like to know what is "better" C++ style in the mean of performance and/or memory. Both codes are inside a method. The question is: When to declare long prio? And what are the implications? Code 1 while (!myfile.eof()) { getline(myfile, line); long prio = ...
There is no difference in performance in this case. If you compare the generated code, it will very likely be the same for both cases. I think the most common style is to declare the variable as close to its first use as possible, but as with all matters of style, it can be very subjective what is "best". As others hav...
2,605,630
2,605,731
Having a destructor take different actions depending on whether an exception occurred
I have some code to update a database table that looks like try { db.execute("BEGIN"); // Lots of DELETE and INSERT db.execute("COMMIT"); } catch (DBException&) { db.execute("ROLLBACK"); } I'd like to wrap the transaction logic in an RAII class so I could just write { DBTransaction trans(db); //...
Use following: transaction tr(db); ... tr.commit(); When tr.commit() completes it sets the state to "commit done" and destructor does nothing, otherwise it rollbacks. Checking for exception is bad idea, consider: transaction tr(db); ... if(something_wrong) return; // Not throw ... tr.commit(); In this case you pro...
2,605,674
2,608,349
How to properly rewrite ASSERT code to pass /analyze in msvc?
Visual Studio added code analysis (/analyze) for C/C++ in order to help identify bad code. This is quite a nice feature but when you deal with and old project you may be overwhelmed by the number of warnings. Most of the problems are generating because the old code is doing some ASSERT at the beginning of the method or...
PREFast is telling you that you have a defect in your code; don't ignore it. You do in fact have one, but you have only skittered around acknowleging it. The problem is this: just because pBytes has never been NULL in development & testing doesn't mean it won't be in production. You don't handle that eventuality. ...
2,605,689
2,605,759
Character pointers and integer pointers (++)
I have two pointers, char *str1; int *str2; If I look at the size of both the pointers let’s assume str1=4 bytes str2=4 bytes str1++ will increment by 1 byte, but if str2++ it will increment 4 bytes. What is the concept behind this?
Simple, in the provided scenario: char is 1 byte long int (in your platform) is 4 bytes long The ++ operator increments the pointer by the size of the pointed type.
2,606,216
2,607,076
Exposing a C++ API to C#
So what I have is a C++ API contained within a *.dll and I want to use a C# application to call methods within the API. So far I have created a C++ / CLR project that includes the native C++ API and managed to create a "bridge" class that looks a bit like the following: // ManagedBridge.h #include <CoreAPI.h> using nam...
Yes, you are passing an unmanaged structure by reference. That's a problem for a C# program, pointers are quite incompatible with garbage collection. Not counting the fact that it probably doesn't have the declaration for the structure either. You can solve it by declaring a managed version of the structure: public v...
2,606,705
2,607,831
Objective-C++ compiles for iPhone, but not simulator
I have a C++ library I want to add to my iphone project. In one header file I declare @interface a { cppvirtualclass V; } This compiles fine for the iPhone device with Release settings. However it refuses to compile for the Simulator with or without debug info. It give the error error: type 'V' has virtual member f...
By default Objective C does not run constructors on C++ instance variables when it creates Objective C objects. This means (I think) that the C++ object's vtable will not get initialised correctly. Try making your instance variable a pointer and allocating it in the init method (and destroying it in dealloc/finalize)....
2,607,010
8,792,991
Linux, how to capture screen, and simulate mouse movements
I need to capture screen (as print screen) in the way so I can access pixel color data, to do some image recognition, after that I will need to generate mouse events on the screen such as left click, drag and drop (moving mouse while button is pressed, and then release it). Once its done, image will be deleted. Note: ...
//sg //Solution using Xlib for those who use Linux #include <X11/Xlib.h> #include<stdio.h> #include<unistd.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <X11/Xlib.h> #include <X11/Xutil.h> void mouseClick(int button) { Display *display = XOpenDisplay(NULL); XEvent event; if(d...
2,607,235
2,607,255
append set to another set
Is there a better way of appending a set to another set than iterating through each element ? i have : set<string> foo ; set<string> bar ; ..... for (set<string>::const_iterator p = foo.begin( );p != foo.end( ); ++p) bar.insert(*p); Is there a more efficient way to do this ?
You can insert a range: bar.insert(foo.begin(), foo.end());
2,607,236
2,607,277
Constructing / destructing QApplication causes QWebView to mess up rendering of HTML
We need to create & destroy instances of QApplication, as we want to use Qt in a plug-in to an existing host application. void multiQT() { int argc = 0; QApplication app(argc, NULL); QWebView view; view.setHtml("<html><head><title>Title</title></head><body><h1>Hello World</h1></body></html>"); view...
You might have run into something that has been very lightly tested, the QApplication object among others creates/holds some of the rendering context information of widgets, I don't think it was ever planned for people to take it down and put it back up again. There might be some static content that does not get reinit...
2,607,524
2,607,584
C question on casting
Can anybody explain me this statement! pin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
Takes hp->h_addr, and casts it to struct in_addr*. The cast may have different reasons. Perhaps hp->h_addr is void* and the cast is needed to tell the compiler what type it should use for finding s_addr. It may also be another struct that has an in_addr as its first member struct in_addr { struct saddr_t s_addr; }; ...
2,607,895
2,607,988
c++ opengl: how can i combine 2 different projection types for 3d graphics and 2d menus?
I would like to use Oblique projection for menus and perspective projection for the 3d-scene. is there a way to combine between this two projections ? In general I'm asking how can I create menus in opengl for my 3d scene. Programming using the c++ language. Thanks!
No problem. Just draw your 3D scene with appropriate modelview and projection matrices loaded. Then load up 2D matrices, turn off depth test, and render your menus. Here's an example of what it might look like. glEnable(GL_DEPTH_TEST) glMatrixMode(GL_MODELVIEW); --code to load my Perspective Modelview Matrix glMatri...
2,608,283
2,937,821
Direct2D window black when not in focus
I have a Direct2D window which paints fine when in focus; however, when focus moves to another window (same application or another), the entire window goes black. I pinned the issue down to the use of ID2D1HwndRenderTarget::Clear. This function is vital to my application as without it, painting becomes rather... weird....
With my experience with DirectX, if the screen turns back its because DX lost the device it was 'painting' to. This happens a lot - for instance - when switching between a full-screen DirectX window to another application, and vice-versa. So what you need to do is re-intialize the DX device so it can resume painting o...
2,608,381
2,608,480
Boost graph libraries: setting edge weight values
I am investigating the use of the boost graph libraries in order to apply them to various network problems I have in mind. In the examples I have been looking at the graph edge values ("weights") are always initialized as integers, such as in these Bellman-Ford and Kruskal algorithms eg: int weights[] = { 1, 1, 2, 7, 3...
It's caused by a mismatch between the weights[] array and the type used for edge weights by your boost graph/algorithm. In the first linked sample, eg, you should also change struct EdgeProperties { int weight; }; [...] property_map<Graph, int EdgeProperties::*>::type to struct EdgeProperties { double weight; };...
2,608,596
2,608,635
std::deque: How do I get an iterator pointing to the element at a specified index?
I have a std::deque, and I want to insert an element at a specified index (I'm aware that std::list would be better at this). The deque::insert() function takes an iterator to specify the location to insert. Given an index, how can I get an iterator pointing to that location, so that I can pass that iterator to inser...
void insertThing ( deque<Thing> & things, Thing thing, size_t index ) { deque<Thing>::iterator it = things.begin() + index; things.insert ( it, thing ); }
2,608,696
14,800,172
C++ Formatting like Visual Studio C# formatting
I like the way Visual Studio (2008) formats C# code; unfortunately it seems it doesn't behave in the same way when writing C++ code. For example, when I write a code in this way: class Test { public: int x; Test() {this->x=20;} ~Test(){} }; in C# (ok this is C++ but you can understand what I mean), this pa...
I'm using AStyle extension for VS2012 and I'm happy with it. It's free :)
2,609,104
2,609,113
Why isn't strlen working for me?
char p[4]={'h','g','y'}; cout<<strlen(p); This code prints 3. char p[3]={'h','g','y'}; cout<<strlen(p); This prints 8. char p[]={'h','g','y'}; cout<<strlen(p); This again prints 8. Please help me as I can't figure out why three different values are printed by changing the size of the array.
strlen starts at the given pointer and advances until it reaches the character '\0'. If you don't have a '\0' in your array, it could be any number until a '\0' is reached. Another way to reach the number you're looking for (in the case you've shown) is by using: int length = sizeof(p)/sizeof(*p);, which will give you...
2,609,145
2,612,125
Interpreters: Handling includes/imports
I've built an interpreter in C++ and everything works fine so far, but now I'm getting stuck with the design of the import/include/however you want to call it function. I thought about the following: Handling includes in the tokenizing process: When there is an include found in the code, the tokenizing function is rec...
This problem is easy to solve if you have a clean design and you know what you're doing. Otherwise it can be very hard. I have written at least 6 interpreters that all have this feature, and it's fairly straightforward. Your interpreter needs to maintain an environment that knows about all the global variables, func...
2,609,207
2,609,293
How to use linked resource with eclipse CDT?
I found it very difficult to configure linked resource in Eclipse CDT. Folder "wspolne" is located somewhere in the system, I'd like to use .cpp .h files from it in my current project, but avoid copying it. From what I read about Linked Resources is a solution, but I can't build a projct :/ I followed instuctions des...
I am not sure linked folder are always adequately indexed by the CDT (update October 2012, it has gotten better with recent CDT releases) A workaround would be, as in this thread: If you want CDT to manage the builds you need to move the sub-folders into there own project folder and create dependencies between them.