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,158,410
2,158,437
Memory leaks in Debug mode
Is there any reason for a program to leak when compiled in Debug mode and not in release? (Debug means debug informations, and compiler optimization disabled, Release means no debug info / full optimization) That's what it seems to do but I can't figure out why. Btw purify is not being helpful here
A lot of pointer type errors, including memory leaks, can seem to appear or disappear when switching between debug and release mode. A couple of reasons might be: Conditional code compiled in one version or the other Memory locations of things move around Special formatting of uninitialized data in the debug version ...
2,158,438
2,158,531
How do I get specific error information from GetFile()?
void GetFtpFile(LPCTSTR pszServerName, LPCTSTR pszRemoteFile, LPCTSTR pszLocalFile) { CInternetSession session(_T("My FTP Session")); CFtpConnection* pConn = NULL; pConn = session.GetFtpConnection(pszServerName); //get the file if (!pConn->GetFile(pszRemoteFile, pszLocalFile)) { //display an er...
According to MSDN: Return Value Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error. GetLastError() returns an error code, but you can call FormatMessage() to get a human-readable string from the error code. Here's a u...
2,158,512
2,158,697
more c++ multiple inheritance fun
Possible Duplicate: C++ pointer multi-inheritance fun. (Follow up on: C++ pointer multi-inheritance fun ) I'm writing some code involving inheritance from a basic ref-counting pointer class; and some intricacies of C++ popped up. I've reduced it as follows: Suppose I have: class A{int x, y;}; class B{int xx, yy;}; c...
Yes Yes No Yes No* But you need to know how C++ organises memory. The layout of a class, CClass, is as follows: offset 0 First base class in list of base classes sizeof first base class Next base class sizeof first N-1 base classes Nth base class sizeof all base classes CCl...
2,158,638
2,158,684
c++ multiple-inheritance
Possible Duplicates: C++ pointer multi-inheritance fun. more c++ multiple inheritance fun This is a problem that arose from dealing with ref-counted pointer base class and threading fun. Given: class A{int x, y;}; class B{int xx, yy;}; class C: public A, public B {int z;}; C c; C* pc = &c; B* pb = CtoB(pc); A* pa = ...
You don't need any function, since C only derives once from A and B. Unless you derive from A or B multiple times (without virtual inheritance), you only need to use: A *pbb = pc; B *pba = pc; AtoC and BtoC are only safe through: C *c = dynamic_cast<C*>(a_or_b_pointer);
2,158,839
2,158,907
Notify a C++ application when a change in a SQL Server table is made
I've posted this before but haven't obtained a suitable answer that fits my requirements. I'm looking for a technology to notify a C++ application when a change to a SQL Server table is made. Our middle-tier is C++ and we're not looking to move onto .NET infrastructure which means we can't use SQLDependency, or SQL Not...
You can actually use Query Notifications from C++. Both the OleDB and the ODBC clients for SQLNCLI10 and SQLNCLI providers support Query Notifications. See Working with Query Notifications, at the second half of the page you'll find the SSPROP_QP_NOTIFICATION... stuff for the OleDB rowsets and the SQL_SOPT_SS_QUERYNOTI...
2,158,901
2,161,027
Connected Component Labeling in C++
I need to use the connected component labeling algorithm on an image in a C++ application. I can implement that myself, but I was trying to use Boost's union-find/disjoint sets implementation since it was mentioned in the union-find wiki article. I can't figure out how to create the disjoint_sets object so that it'll w...
Surprisingly, there is no CCL in OpenCV. However, there is a workaround that is described in the reference manual. See the example for cvDrawContours. When I tried to use it, I had some strange behaviour on first and last rows and columns of an image, but I probably did something wrong. An alternative way is to use cvB...
2,158,928
2,158,965
Inherit from two polymorphic classes
Given the following code class T { public: virtual ~T () {} virtual void foo () = 0; }; class U { public: U() {} ~U() {} void bar () { std::cout << "bar" << std::endl; } }; class A : public U, public T { public: void foo () { std::cout << "foo" << std::endl;...
Firstly, there are no virtual base classes in your example. Classes that contain virtual functions are called polymorphic. (There is such thing as "virtual base classes" in C++ but it has nothing to do with your example.) Secondly, the behavior of your code does not depend on any virtual declarations. You have delibera...
2,158,943
2,158,953
Split string into array of chars
I'm writing a program that requires a string to be inputted, then broken up into individual letters. Essentially, I need help finding a way to turn "string" into ["s","t","r","i","n","g"]. The strings are also stored using the string data type instead of just an array of chars by default. I would like to keep it that w...
string a = "hello"; cout << a[1]; I hope that explains it
2,158,949
2,159,093
How to use colors in Motif
I'm new to GUI programming in C and Linux, and I'm having a hard time with it. It seems like a fairly simple/straightforward thing, but I can't find any answers googling. I want to add a background color to a widget. XmNbackground seems to be what I want to use, but I don't understand what I set it to, like a simple co...
See here for an answer in the function Pixel convert_color_name_to_pixel, and also here. Hope this helps.
2,159,108
2,159,136
C++ classes and nested members
I'm not sure how to call this. Basically I want to make a class with nested members. Example: ball->location->x; or ball->path->getPath(); right now I only know how to make public and private members such as ball->x; ball->findPath(); Thanks
Something like this: class Plass { public: Plass(Point *newPoint, Way *newWay) { moint = newPoint; bay = newWay; // or instantiate here: // moint = new Point(); // bay = new Way(); // just don't forget to mention it in destructor } Point *moint; ...
2,159,147
2,159,157
Program unexpectedly quits for unknown reason (C++)
For some reason, whenever I run this program it exits at permute(permutater, length, lenth); . This doesn't happen whenever I comment out the line and the function doesn't even run. Any help?
First thing I noticed - you're not initializing the index variable hor. int permute(string permutater,int length,int lenth) { int hor,hor2,marker; cout << length/lenth; for (marker=0;marker !=(length/lenth);marker++) { hor2 = permutater[hor]; // <== hor is not initialized ...
2,159,338
2,159,346
What is the Java equivalent of C++'s templates?
What is the Java equivalent of C++'s templates? I know that there is an interface called Template. Is that related?
Templates as in C++ do not exist in Java. The best approximation is generics. One huge difference is that in C++ this is legal: <typename T> T sum(T a, T b) { return a + b; } There is no equivalent construct in Java. The best that you can say is <T extends Something> T Sum(T a, T b) { return a.add(b); } where Somet...
2,159,390
2,159,405
In C++, is it possible to forward declare a class as inheriting from another class?
I know that I can do: class Foo; but can I forward declare a class as inheriting from another, like: class Bar {}; class Foo: public Bar; An example use case would be co-variant reference return types. // somewhere.h class RA {} class RB : public RA {} ... and then in another header that doesn't include somewhere....
A forward declaration is only really useful for telling the compiler that a class with that name does exist and will be declared and defined elsewhere. You can't use it in any case where the compiler needs contextual information about the class, nor is it of any use to the compiler to tell it only a little bit about t...
2,159,452
2,159,469
C++: assign cin to an ifstream variable?
You know the common stdio idiom that stdin is specified by a filename of "-", e.g. if ((strcmp(fname, "-")) fp = fopen(fname); else fp = stdin; What's the best way to do this with an ifstream instance? I've received a bit of code that has an ifstream as part of a class and I'd like to add code to do the equiv...
cin is not an ifstream, but if you can use istream instead, then you're in to win. Otherwise, if you're prepared to be non-portable, just open /dev/stdin or /dev/fd/0 or whatever. :-) If you do want to be portable, and can make your program use istream, here's one way to do it: struct noop { void operator()(...) c...
2,159,490
2,159,504
C++, twenty numbers not random?
Why are my C++ numbers not random? #include <iostream> #include <cstdlib> using namespace std; int main() { int randomNumber = rand() % 100; for (randomNumber = 0; randomNumber < 20; randomNumber++) { cout << randomNumber << endl; } return 0; } //Why are my 20 numbers not random?
You need to call rand() each time you want a random number. As you have it now you're generating one random number, then incrementing it and printing it out 20 times so you're going to get 20 sequential numbers. Try something like srand(time(NULL)); // Seeding the random number generator for(int i=0; i<20; ++i) { ...
2,159,496
2,159,524
c++ problem with function overloading
i have a problem with function overloading. I will show you with some simple example: class A {}; class B : public A{}; void somefunction(A&, A&); void somefunction(B&, B&); void someotherfunction() { ... A& a1 = ... A& a2 = ... ... } Both a1 and a2 are instances of B but somefunction(a1,a2); calls void somefuncti...
Cast them statically so that the compiler knows which one to pick: void somefunction((B&)a1, (B&)a2); The reason why you are having this problem is with the program design, not the language. Compiler picks which which function is used based on the types that are passed in. C# will behave in exactly the same way (prett...
2,159,538
2,159,558
c++ publicly inherited class member cannot be used as default argument
A schematic of my problem... class A { public: // etc. protected: uint num; }; class B : public A { public: void foo(uint x = num); //bad }; gives this error: error: invalid use of non-static data member ‘A::num’ error: from this location Why does this happen, and what can I do to work around this?
I suspect this happens (based on the complaint about non-staticness) because there is no this pointer for it to use to know which instance of B it should get num from. The Microsoft compiler (at least) allows you to specify an expression, but not a non-static member. From MSDN: The expressions used for default argu...
2,159,713
2,159,732
Overloading Output operator for a class template in a namespace
I've this program #include <iostream> #include <sstream> #include <iterator> #include <vector> #include <algorithm> using namespace std ; #if 0 namespace skg { template <class T> struct Triplet ; } template <class T> ostream& operator<< (ostream& os, const skg::Triplet<T>& p_t) ; #endif namespace skg { template...
You need to move your implementation of operator<< into the same namespace as your class. It's looking for: ostream& operator<< (ostream& os, const skg::Triplet<T>& p_t) But won't find it because of a short-coming in argument-dependent look-up (ADL). ADL means that when you call a free function, it'll look for that fu...
2,159,801
2,159,835
Application wide periodic tasks with Dialog Based MFC application
In Single Document Interface (SDI) or Multiple Document Interface (MDI) MFC application, I created an application wide timer in the View. The timer will tick as long as the application is running and trigger some periodic actions. How can I do the same with Dialog Based MFC application? Should I create Thread's Timer ...
A timer works as well in a dialog-based application as an SDI or MDI app. OTOH, timers are (mostly) a leftover from 16-bit Windows. If you want to do things periodically, a worker thread is usually a better way to do it (and yes, Windows Mobile supports multiple threads). Edit: in a dialog-based application, the main d...
2,159,986
2,160,315
gcc code::blocks shared library questions
I'm using code::blocks on a linux system with the gcc compiler, and I want to be able to use the shared library template to make a shared library with classes, then make another project that accesses that shared library(at compile time, not dynamically) and classes. I'm sure that code::blocks has simple way of doing th...
You can have more then one project in your workspace and set project dependencies, there are no custom makefiles needed. The basic steps with Code::Blocks are the following: make sure your shared library project generates an import library (project properties->build targets) make the shared lib project a dependency...
2,160,187
2,160,540
C++ compilation for iPhone (STL issue?)
I am trying to compile some C++ code as a static library to use on the iPhone. If I compile things for the simulator (i386 architecture), everything compiles just peachy, but when I switch the architecture to arm, I get all these include errors, seemingly within the iPhone SDK STL headers. Any idea what's going on? Fir...
Add /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.0.sdk/usr/include/c++/4.2.1/armv6-apple-darwin9/ as the include path. Also, please file a bug to Apple.
2,160,334
2,160,422
Boost weak_ptr's in a multi-threaded program to implement a resource pool
I'm thinking of using boost::weak_ptr to implement a pool of objects such that they will get reaped when nobody is using one of the objects. My concern, though, is that it's a multi-threaded environment, and it seems there's a race condition between the last shared_ptr to an object going out of scope and a new shared_...
To use a weak_ptr, you normally have to grab a strong reference by constructing a shared_ptr with it. This last step is atomic: you either get a strong reference back, or you get a bad_weak_ptr exception thrown. (Alternatively, call lock() on the weak_ptr, and either get a strong reference or null.) Example (with lock(...
2,160,565
2,160,797
Is there any charting lib for C++?
I have a C++ program that generates some data and i need to generate some charts for that data and to plot some functions. Is there any free library available that can do that and just generate a png/jpeg(format doesn't matter)? Google charts is not an option as i want to be able to generate charts even when offline.
Check out http://qwt.sourceforge.net/. It's Qt-based.
2,160,616
2,160,632
Convert C++ to Python (For Loop multiple assignment)
Convert to python: #include <iostream> using namespace std; int main(int argc, char** argv) { for (int i = 0, j = i + 3; i < 100; ++i, j= i+3) cout << i << " j: " << j << endl; getchar(); return 0; } I try: for i in range(99): j = i + 3 print i, " j: ", j How to make it one for loop?
Just change 99 to 100 for i in range(100): j = i + 3 print i, " j: ", j Or for i,j in [(i, i+3) for i in range(100)]:
2,160,720
2,160,769
Any smarter way to extract from array of bits?
I have areas of memory that could be considered "array of bits". They are equivalent to unsigned char arr[256]; But it would be better thought of as bit arr[2048]; I'm accessing separate bits from it with #define GETBIT(x,in) ((in)[ ((x)/8) ] & 1<<(7-((x)%8))) but I do it a lot in many places of the code, often in...
For randomly accessing individual bits, the macro you've suggested is as good as you're going to get (as long as you turn on optimisations in your compiler). If there is any pattern at all to the bits you're accessing, then you may be able to do better. For example, if you often access pairs of bits, then you may see s...
2,160,889
2,161,288
How to detect the device name for a capture device?
I am writing a GStreamer application (GStreamer uses DirectShow under the hood on Windows) that captures a computer's microphone and videocamera. It works fine, but requires me to specify the device names manually. I would like to have my program detect these automatically. Does anyone know how to do that?
It would surprise me if GStreamer doesn't have capabilities to enumerate devices, but DirectShow definitely has. See the article on using the system device enumerator and use it with the correct filter categories - in your case CLSID_AudioInputDeviceCategory and CLSID_VideoInputDeviceCategory.
2,160,920
2,160,944
Why can't we declare a std::vector<AbstractClass>?
Having spent quite some time developping in C#, I noticed that if you declare an abstract class for the purpose of using it as an interface you cannot instantiate a vector of this abstract class to store instances of the children classes. #pragma once #include <iostream> #include <vector> using namespace std; class I...
You can't instantiate abstract classes, thus a vector of abstract classes can't work. You can however use a vector of pointers to abstract classes: std::vector<IFunnyInterface*> ifVec; This also allows you to actually use polymorphic behaviour - even if the class wasn't abstract, storing by value would lead to the pro...
2,160,935
2,164,881
Programmatically fetch GPU utilization
Is there a standard way of getting the current load on the GPU? I'm looking for something similar to the Task Manager showing CPU%. Utilities such as GPU-Z show this value but I'm not sure how it gets this. I'm specifically interested in AMD graphics cards at the moment, any pointers would be helpful. If there's no c...
For AMD/ATI cards, check out GPU PerfStudio. http://developer.amd.com/gpu/Pages/default.aspx For NVidia cards, look at PerfHUD. http://developer.nvidia.com/object/nvperfhud_home.html There is also a more generic tool in the DirectX SDK from MS called Pix that overlaps partially with these tools. AFAIK there's no way...
2,161,002
2,161,025
Restricting the size of an array when passed to a function
Is there anyway to restrict the size of an array when passed as an argument to a function? I mean is something like this possible? /*following will lead to compile time error */ template<typename T, size_t n>=20> // or template<typename T,size_t n<=20> void func(T (&a)[n]) { // do something with a } I want the si...
You can simply make the requirement a static assertion - e.g. with Boosts static assert: template<typename T, size_t n> void func(T (&a)[n]) { BOOST_STATIC_ASSERT(n >= 20); // ... } A basic custom implementation (not solving the problem of using it more then once per scope) might look like the following: temp...
2,161,397
2,161,474
Is this ambiguous or is it perfectly fine?
Is this code ambiguous or is it perfectly fine (approved by standards/has consistent behavior for any compilers in existence)? struct SCustomData { int nCode; int nSum; int nIndex; SCustomData(int nCode, int nSum, int nIndex) : nCode(nCode) , nSum(nSum) , nIndex(nIndex) {} };...
No, in this case there are no ambiguity, but consider following: struct SCustomData { //... void SetCode(int nCode) { //OOPS!!! Here we do nothing! //nCode = nCode; //This works but still error prone this->nCode = nCode; } }; You should draw attention to one...
2,161,410
2,161,429
Big Endian and Little Endian for Files in C++
I am trying to write some processor independent code to write some files in big endian. I have a sample of code below and I can't understand why it doesn't work. All it is supposed to do is let byte store each byte of data one by one in big endian order. In my actual program I would then write the individual byte out t...
In your example, data is 0x12345678. Your first assignment to byte is therefore: byte = 0x12000000; which won't fit in a byte, so it gets truncated to zero. try: byte = (data & bitmask) >> (sizeof(long) - 1) * 8);
2,161,462
2,161,501
C++ inheritance and function overriding
In C++, will a member function of a base class be overridden by its derived class function of the same name, even if its prototype (parameters' count, type and constness) is different? I guess this a silly question, since many websites says that the function prototype should be the same for that to happen; but why doe...
The term used to describe this is "hiding", rather than "overriding". A member of a derived class will, by default, make any members of base classes with the same name inaccessible, whether or not they have the same signature. If you want to access the base class members, you can pull them into the derived class with a...
2,161,567
2,230,857
I need a tree dump option, which doesn't exist any more in current gcc versions
Older versions of GCC (for example 4.0.2 or 4.1.2) had the option -df (see Options for Debugging Your Program or GCC for 4.1.2). I used this option to dump the files filename.c.134r.life2 and filename.c.126r.life1, because I want to extract some values out of these files (for example the register count for every method...
GCC 4.2-4.3 does really have the dump_flow_info function, which reports number of register used. I'll search, how it can be called. Oh, yes: gcc-4.3.1 file.c -fdump-rtl-all-all produces file.c.175r.lreg with file.c.175r.lreg:81 registers. More specific option: -fdump-rtl-lreg-all. It was wested with 4.3.
2,161,770
2,161,802
Visual C++ Automatically Appending A or W to end of Function
In C++ I have defined a class that has this as a member: static const std::basic_string<TCHAR> MyClass_; There is also a getter function for this value: LPCTSTR CClass::GetMyClassName() { return MyClass_.c_str(); } When I create an instance of this class and then try and access it intellisense pops up but the nam...
Your method name is literally "GetMyClassName" or is it "GetClassName"? GetClassName is in the SDK (winuser.h) and is redefined based on the UNICODE defines. If you are using "GetClassName" the intellisense is probably getting confused; in fact the compiler is generating the A/W suffix for the actual compiled method ...
2,161,940
2,161,947
Two enums have some elements in common, why does this produce an error?
I have two enums in my code: enum Month {January, February, March, April, May, June, July, August, September, October, November, December}; enum ShortMonth {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; May is a common element in both enums, so the compiler says: Redeclaration of enumerator 'Ma...
Enum names are in global scope, they need to be unique. Remember that you don't need to qualify the enum symbols with the enum name, you do just: Month xmas = December; not: Month xmas = Month.December; /* This is not C. */ For this reason, you often see people prefixing the symbol names with the enum's name: enum M...
2,162,016
2,162,124
How do I treat a pointer as a multi array?
I have this loop which gives seg. fault. s->c = malloc(width * height * sizeof(double)); if (s->c == NULL) { puts("malloc failed"); exit(1); } for (int n = 0; n < width; n++) { for (int m = 0; m < height; m++) { d = (&s->c)[m][n]; printf("d %f\n", d); printf("m %i\n", m); printf("n ...
The problem is that the compiler doesn't know the dimensions of your matrix. When you have: double tab[m][n] you can access the element tab[row][col] as *(tab + (row * n) + col) In your case you only have double *tab; that can be considered as the pointer to the element tab[0][0] with no information on the matrix dime...
2,162,022
2,162,116
Downloading all files in directory using libcurl
I am new to the libcurl and found a way to download a single file from the ftp server. Now my requirement is to download all files in a directory and i guess it was not supported by libcurl. Kindly suggest on libcurl how to download all files in directory or is there any other library similar to libcurl? Thanks in adva...
You need the list of files on the FTP server. Which isn't straightforward as each FTP server might return a different format of file listing... Anyway, the ftpgetresp.c example shows a way to do it, I think. FTP Custom CUSTOMREQUEST suggests another way.
2,162,099
2,186,504
Winsock accept event sometimes stops signaling (WSAEventSelect)
I have a problem with a piece of legacy c++/winsock code that is part of a multi-threaded socket server. The application creates a thread that handles connections from clients, of which there are typically a couple of hundred connected at any one time. It typically runs without a problem for several days (continuously)...
Maybe an FD_ACCEPT is signaling during HandleConnect() after the accept() and before the return and subsequent ResetEvent(). Then, ResetEvent() ends up resetting all signals and no re-enabling accept() is ever called. For example, the following sequence is possible: Event signaled, WaitForMultipleObjects() returns D...
2,162,390
2,167,897
iconv encoding conversion problem
I am having trouble converting strings from utf8 to gb2312. My convert function is below void convert(const char *from_charset,const char *to_charset, char *inptr, char *outptr) { size_t inleft = strlen(inptr); size_t outleft = inleft; iconv_t cd; /* conversion descriptor */ if ((cd = iconv_open(t...
outleft should be the size of the output buffer (e.g. 1000 bytes), not the size of the incoming string. When converting, the string length usually changes in the process and you cannot know how long it is going to be until afterwards. E2BIG means that the output buffer wasn't large enough, in which case you need to giv...
2,162,510
2,162,593
strange template namespace problem
I've got a strange problem with templates and namespaces... I have the following code which compiles fine.. using namespace boost::multi_index; template < typename OT, typename KT, KT (OT::* KM)() const, typename KC, typename CMP > class OrderBook { public: OrderBook() {} ~OrderBook() {} typedef multi_ind...
Prefix get<0>() with template: const_iterator_0 begin0() const { return _container.template get<0>().begin(); } const_iterator_0 end0 () const { return _container.template get<0>().end(); } Similar to typename for dependent types, dependent templates have to be prefixed by template: struct X { template<class T>...
2,162,646
2,162,670
Is there a C/C++ project similar to portablepython?
I've searched the internet for this but couldn't find anything useable, I was just wondering if there exists a C/C++ project similar to portablepython? EDIT I guess the question becomes: is there a portable C/C++ compiler I can stick onto a usb key?
Python is an interpreter that can run "scripts" (.py files). Therefore portablepython makes sense - if you don't want to install Python everywhere, but still want to run the small Python files. This helps if the target PC doesn't have Python installed (or you can't even do it because of privileges). For C/C++ this doe...
2,162,819
2,162,881
can someone help me translate this c++ code to c?
this is a magic square generator, but do not know C++, I have some difficulties to convert this code: #include <vector> #include <iostream> using namespace std; //There two series will be on even in case of magic square // One of even order will be for multiple of 4 void BuildDoublyEvenMagicSquare(vector<vector<int> > ...
For the last part of the question, in C that function prototype would look like this if you follow the rest of my advice: void BuildDoublyEvenMagicSquare(int *mat, int Order); There are actually several ways you could do it. There are some things being done here that simply can't be done in C, so you'll have to sort ...
2,163,090
2,163,132
When I kill a pThread in C++, do destructors of objects on stacks get called?
I'm writing a multi-threaded C++ program. I plan on killing threads. However, I am also using a ref-counted GC. I'm wondering if stack allocated objects get destructed when a thread gets killed.
The stack does not unwind when you 'kill' a thread. Killing threads is not a robust way to operate - resources they have open, such as files, remain open until the process closes. Furthermore, if they hold open any locks at the time you close them, the lock likely remains locked. Remember, you are likely calling a lo...
2,163,365
2,163,386
WinAPI for Game Controllers
I know that all windows platforms automatically detect when a game controller is connected. I also know there is a WinAPI for polling these controllers. I can't seem to find the functions I am looking for anywhere. Any help is greatly appreciated! Brendan
You can use either DirectInput or XInput from the DirectX SDK.
2,163,632
2,163,657
hooking on WM_SETTEXT message
I have setup a hook on WM_SETTEXT message using WH_CALLWNDPROC. In hook procedure CWPSTRUCT* info = (CWPSTRUCT*) lParam; switch(info->message) { case WM_SETTEXT: break; } Now in the above code how can I get the string that is passed along WM_SETTEXT message? I am not able to get this information anywher..
The lParam passed to WM_SETTEXT contains the string, so info->lParam should have the info you want.
2,163,853
2,163,875
How can I display variable strings using C++ and PDCurses?
I'm extremely sorry to post such an embarrassingly newbish question, but I haven't mucked around much with C++ since my college days and I think at some point I drank all that I knew about pointers and C++ strings right out of my head. Basically, I'm creating a C++ console app (a roguelike, to be precise) with PDCurse...
Just declare pvers as: const char *pvers = vers.c_str(); This const means you aren't going to modify the memory pointed to by pvers. It's really more of a hint so that the compiler can yell at you if you break this assumption. (Which is why you got the compiler warning.) You might start to see something funky if yo...
2,163,892
2,164,039
API to use deault Web Cam?
I'm working on a Win32 application in C++ and would like to add the ability to output the default web cam onto the screen. I was wondering if there was a Win32 API for this, or a way to do this without coding the whole thing. Thanks
Yes, it is really simple with capCreateCaptureWindow. That googles really well, you'll have no trouble finding code samples.
2,164,001
2,164,122
Installing C/C++ libraries on Windows
I'm studying (well, trying to) C right now, but I'm limited to working in Windows XP. I've managed to set up and learn how to use Emacs and can compile simple C programs with gcc (from Emacs no less!), but I'm getting to the point where I'd like to install something like SDL to play around with it. The thing is that t...
The build process usually works like this: the configure script finds the appropriate settings for the compilation (like which features to enable, the paths to the required libraries, which compiler to use etc.) and creates a Makefile accordingly. make then compiles the source code to binaries. make install copies the ...
2,164,095
2,164,155
Static variables in instance methods
Let's say I have this program: class Foo { public: unsigned int bar () { static unsigned int counter = 0; return counter++; } }; int main () { Foo a; Foo b; } (Of course this example makes no sense since I'd obviously declare "counter" as a private attribute, but it's just to illustra...
Yes, counter will be shared across all instances of objects of type Foo in your executable. As long as you're in a singlethreaded environment, it'll work as expected as a shared counter. In a multithreaded environment, you'll have interesting race conditions to debug :).
2,164,276
2,204,671
Compiling OpenCV for Visual C++ 9.0
I looked at many places but could not find anything telling me how to buld the lib files. I know how to link them, but openCV install folder only contains .a files. I cant find an sln file or dsp. How can I make the lib files? Right now all the samples get linker problems because the lib files dont exist. Thanks
The Windows installer (.exe) for OpenCV 2.0 does not come with the binaries pre-built for vc++, nor does it have the .vcproj files for using vc++ to build them. You need to have cmake, which is available for free on the web. I used the GUI. Use that to build .vcproj files with which you can compile everything in VC+...
2,164,360
2,164,375
am i implementing this template class correctly?
Okay, I'm trying to implement a templated class of an array-based queue called Queue. Here's how I did it. First, is this the right way to implement a templated class? The problem is, when I try to compile, I get the error messages undefined reference to 'Queue::Queue()' undefined reference to 'Queue::~Queue()' ...
Several issues: The cause of your problem - C++ does not really support splitting templates into .h and .cpp files - you need to put everything in the header The name __QUEUE_H__ is reserved for the C++ implementation, as are all names that contain double-underscores or begin with an underscore and an uppercase letter...
2,164,365
2,164,454
Algorithm for searching for an image in another image. (Collage)
Is this even possible? I have one huge image, 80mb with a lot of tiny pictures. They are tilted and turned around as well. How can i search for an image with programming? I know how to use java and c++. How would you go about this?
One algorithm I've used before is SIFT. If you're interested in implementing the algorithm for yourself, you can see course notes for CPSC 425 at UBC, which describes in gentle detail how to implement SIFT in MATLAB. If you just want code that does this, take a look at VLFeat, a C library that does SIFT and a number of...
2,164,373
2,164,630
A scripting language to simply compile
I'm looking for a simple script language which I can compile easily by just putting the .h files under an include folder and the .c/.cpp files under a source directory. Something without any Makefile. Must be written in C/C++ rather C++. Okay so LUA doesn't work, I need something which I can just call a simple method ...
Lua is a simple lightweight scripting language that can be easily embedded into your application. It is written in C (I don't really understand what you mean by "Must be written in C/C++ rather C++"). You can simply add all files from the src directory except for lua.c and luac.c into your project and it should work. N...
2,164,376
2,184,609
Counter in AS3 "without dynamic text field"
What is the best way to program an LED number tick. I need to have a number display that goes up to 1,000,000.00. Dynamic text fields are not an option because of symbol instances. How would I make a counter? ANIMATION The numbers move in increments like an LED display. This NUMBERS The numbers multiple by ten each spa...
In Flash, and to achieve the result in your picture there, I would create 2 MovieClips: A black bar with a decimal point The grey digits in a column, 0 -> 0, as suggested by your pic Then, combine the black bar and 9 of the digit columns into a single MovieClip to represent your counter, along with a custom base clas...
2,164,634
2,164,715
Program Interaction and testing via bash script
I've just completed the coding section of simple homework assignment for my C++ class. The second part of the assignment requires us to verify our code's input validation. (The program takes several different values as inputs from a user and prints those values to a file) I was hoping that I could use bash script for...
To build on @Travis' answer, create two files: one holds your inputs (input.txt) and one holds the expected output (expected_output.txt). Then do the following: ./myprogram <input.txt >output.txt diff output.txt expected_output.txt If the diff command has any output, there's a problem.
2,164,635
2,164,700
Calculating a gradient fill's start and end colours given a base colour
I have a WTL C++ application and I want the user to be able to select different colours for some of the UI elements and apply a gradient fill using the GradientFill API call. However, instead of letting the user pick the start and end colours for the gradient, I'd like them to be able to select a 'base' colour and for...
The RGB color space is not suitable for this. Use HSL or HSV: it is easy to auto-generate a good looking gradient by varying an individual component. Converting from HSL/V to an RGB triplet you can use in the API is simple.
2,164,720
2,165,685
Collisions in a real world application
Here's my problem. I'm creating a game and I'm wondering about how to do the collisions. I have several case to analyze and to find the best solution for. I'll say it beforehand, I'm not using any third party physics library, but I'm gonna do it in house. (as this is an educational project, I don't have schedules and ...
The most common approaches used in many current AAA games is "k-DOP" simplified collision for StaticMeshes, and a simplified physical body representation for the SkeletalMeshes. If you google for "kDOP collision" or "discrete orientation polytopes" you should find enough references. This is basicly a bounding volume de...
2,164,827
2,164,853
Explicitly exporting shared library functions in Linux
Is there a Linux equivalent of __declspec(dllexport) notation for explicitly exporting a function from a shared library? For some reason with the toolchain I'm using, functions that aren't class members don't appear in the resulting shared library file.
__attribute__((visibility("default"))) And there is no equivalent of __declspec(dllimport) to my knowledge. #if defined(_MSC_VER) // Microsoft #define EXPORT __declspec(dllexport) #define IMPORT __declspec(dllimport) #elif defined(__GNUC__) // GCC #define EXPORT __attribute__((visibility("defaul...
2,164,910
2,164,966
is this a correct use of boost condition variables?
I wrote the following program for alternatively incrementing and doubling a counter(increment first) using boost condition variables. Can any one tell me if this is the correct use of boost condition variables. It is working correctly. I don't understand the use of lock in wait function call. What does condition.wait(l...
No, this is not correct. You're almost there, but the big problem is that the Multiply and Increment functions should be using the same mutex. A mutex is an object that provides MUTual EXclusion. In other words, the point of a mutex is to prevent two threads from touching the same variable at the same time and causing...
2,164,932
2,164,946
Adding layout to another layout in Qt [C++]
Could anyone tell me why I'm getting error and how to fix it? QGridLayout* mainLayout = new QGridLayout; QGridLayout *leftLayout = new QGridLayout; QGridLayout *rightLayout = new QGridLayout; mainLayout->addLayout(leftLayout); mainLayout->addLayout(rightLayout); setLayout...
Qt4 Reference says: void addLayout ( QLayout * layout, int row, int column, Qt::Alignment alignment = 0 ) So you have to do: mainLayout->addLayout(leftLayout, 0, 0); mainLayout->addLayout(rightLayout, 0, 1);
2,165,011
2,612,549
Using OpenCV to detect a finger tip instead of a face
I'm using the facedetect example and going from there. Right now it only detects faces. Could someone point me in the direction to detect finger tips. Thanks
Put a simple bright fluorescent sticker on the finger tip with a black dot in center or something like that. or even fashion a finger cap with a pattern printed on it which can be easily differentiated by the camera and your problem is very much solved.
2,165,030
2,165,051
Use Boost to get arity and paramerter types of member function? (boost::function_traits)
It works just fine, for plain vanilla functions. The code below works just fine. It prints just what is should: int __cdecl(int, char) 2 int,char #include <boost/type_traits.hpp> #include <boost/function.hpp> #include <boost/typeof/std/utility.hpp> #include <iostream> using std::cout; using std::endl; int foo(in...
Boost Function Types would probably be the natural solution: #include <boost/function_types/function_type.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/function_types/function_arity.hpp> #include <boost/typeof/std/utility.hpp> #include <boost/typeof/typeof.hpp> #include <iostream> struct bar...
2,165,078
2,165,109
A reference can not be NULL or it can be NULL?
I have read from the Wikipedia that: “References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.” But I don’t believe because of following code, look at it, compiler gives no error: class person { public: virtual void setage()=0; }; int main() {...
Saying person &object1=*object is not the same thing as saying person &object1=NULL. Probably the compiler is just not smart enough to find out that you are dereferencing null pointer, but you'll get a runtime error anyway. So they are kind of true still ;)
2,165,079
2,165,255
gcc with parameters "-S -save-temps" puts intermediate files in current directory
The parameters -S -save-temps work fine, as long as i don't use them on files with the same name. Think of the following situation: I have a project with a main directory and a subdirectory with the name subDir and in both of the directories are files placed with the name file.c. If I now call gcc -S -save-temps file.c...
There's no problem with file.cpp / file.c in different directories. GCC will create a *.ii and a *.i depending on the files' extension. If they both have c||cpp you can use -E and receive only one *.i where you can search for the pragma # 1 "<FILE_PATH>" and extract it via a script.
2,165,223
2,165,243
C++ Controlling destructor order for global objects
I've got a class (A) that accesses (indirectly via a static method) a static variable (an STL container) in another class (B) in its constructor and destructor. A objects may be global, global constants, static members of another class, stored in other classes (which may themselves have global or static instances) or b...
No. This is known as the static-initialization fiasco. The order that objects get constructed prior to entering main is unspecified. The only guarantee is that it happens. What you can do is lazy-initialize. This means your objects won't be initialized until you use them. Such as: struct A { /* some data */ }; struct B...
2,165,230
2,166,341
Should I use DirectInput or Windows message loop?
I'm working on a C++ DirectX 2D game and I need keyboard and mouse input. Wikipedia says: Microsoft recommends that new applications make use of the Windows message loop for keyboard and mouse input instead of DirectInput So how should I use it? I have a GameScreen class whice take care of the drawing and the updatin...
Since you pretty much have to run a message pump in order to have a window, you might as well use that pump to handle keyboard and mouse input as well. It's entirely up to your pump whether you hand keyboard events on to a child window, you can handle them in the pump if you prefer. Your typical message pump looks li...
2,165,315
2,165,367
Checking if a string object has only null characters
I want to check if a string object of 20 characters has only null characters in it (values of zero). My attempt: string subString; subString = fileBuffer.substr(origin, origin+20); if(strCompare.compare("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0") == 0) cout<<"string is empty"<<endl; else cout<<"string is not e...
The problem with this: if(strCompare.compare("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0") is that the string constructed from the C-style string will be empty. You need to construct a string explicitly, providing the size. One way: if( strCompare.compare( std::string( "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", ...
2,165,637
2,166,047
Char array pointer vs string refrence in params
I often see the following structure, especially in constructors: class::class(const string &filename) { } class::class(const char * const filename) { } By step-by-step debug, I found out the 2nd constructor is always called if I pass a hard-coded string. Any idea: 1) Why the dual structure is used? 2) What is the sp...
Two constructors are needed because you can pass a NULL to your MyClass::MyClass(const std::string &arg). Providing second constructor saves you from a silly crash. For example, you write constructor for your class, and make it take a const std::string & so that you don't have to check any pointers to be valid if you'd...
2,165,726
2,165,776
How do I record timestamps in a Mac OS X C++ program?
I'm running a giant simulation / with a graphics engine. There are lots of events that are flying by. I would like to timestamp them (measured in milliseconds since the start of program execution). What should I be using for this? [What library?]
Since Mac OS X is Unix based, try gettimeofday(). It will return seconds and microseconds, up to the resolution of the system clock. #include <sys/types.h> int gettimeofday(struct timeval *tv, struct timezone *tz); struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseco...
2,165,921
2,165,980
Converting from a std::string to bool
What is the best way to convert a std::string to bool? I am calling a function that returns either "0" or "1", and I need a clean solution for turning this into a boolean value.
It'll probably be overkill for you, but I'd use boost::lexical_cast boost::lexical_cast<bool>("1") // returns true boost::lexical_cast<bool>("0") // returns false
2,165,995
2,166,013
How to include all boost header files?
In Java if you wanted all the classes in a namespace you could just do this: import com.bobdylan.*; Is there anyway I can get a result similar to: import boost.*; (except in C++)
Not automatically. You can write a single header file that #includes all the other headers you are interested in, and then just #include that, but that's it - C++ has no "import" feature like java.
2,166,098
2,166,102
Why does GetErrorMessage return "wrong password", when the user name is wrong?
GetErrorMessage (from CInternetException) gives me the following: With the incorrect ftp server name: "ERROR! The server name or address could not be resolved" With the incorrect password: ERROR! The password was not allowed With the incorrect user name: ERROR! The password was not allowed <-----? NO separate mess...
Yes that is intended. A typical FTP server will not distinguish between an invalid password and an invalid username. This is for security reasons, so e.g. attackers can't brute force their way to discover valid usernames.
2,166,099
2,166,109
Calling a constructor to re-initialize object
is it possible to re-initialize an object of a class using its constructor?
Sort of. Given a class A: A a; ... a = A(); the last statement is not initialisation, it is assignment, but it probably does what you want.
2,166,169
2,166,334
how to assign a Base object to a Derived object
I have a question about C++, how to assign a Base object to a Derived object? or how to assign a pointer to a Base object to a pointer to a Derived object? In the code below, the two lines are wrong. How to correct that? #include <iostream> using namespace std; class A{ public: int a; }; class B:public A{ public: ...
When an object is on the stack, you can only really assign objects of the same type to one another. They can be converted through overloaded cast operators or overloaded assignment operators, but you're specifying a conversion at that point. The compiler can't do such conversions itself. A a; B b; b = a; In this case,...
2,166,271
2,167,476
How to resolve a naming conflict between two libraries in C++?
I am using two large libraries (GUI & network) and I can happily do using namespace FirstLib; using namespace SecondLib; Except for 1 single class called Foobar where names clash. I my code, I do not use FirstLib::Foobar. Is there a way to say "in my code, whenever you see Foobar, think SecondLib::Foobar ?
It's strange nobody suggested to replace the full namespace use by the list of used class names. This solution is even in the C++faq (where I should have thought to look first). If we cannot say include all FirstLib, but remove SecondLib::Foobar We can use using-declarations of the exact elements we need: using First...
2,166,321
2,166,330
Push_back causing an error when using vectors in C++
I am having issues getting this piece of code to compile. I am compiling with Eclipse on OS X 10.6. The problem seems to occur only when using vectors. I cannot seem to use the push_back function at all. Every time I try, I get the error "expected constructor, destructor, or type conversion before '.' token". Here are ...
Here: float turtleScale = 20; Point turtlePos = Point(300./turtleScale,200./turtleScale); LinePoint* lp = new LinePoint(turtlePos,BLACK); vector<LinePoint*> lines; ... you use initializations, but this: lines.push_back(lp); ... is a statement! It must live in a function :) int main() { lines.push_back(lp); } .....
2,166,425
2,166,534
How to structure a C++ application to use a multicore processor
I am building an application that will do some object tracking from a video camera feed and use information from that to run a particle system in OpenGL. The code to process the video feed is somewhat slow, 200 - 300 milliseconds per frame right now. The system that this will be running on has a dual core processor. ...
Basically, you need to multithread your application. Each thread of execution can only saturate one core. Separate threads tend to be run on separate cores. If you are insistent that each thread ALWAYS execute on a specific core, then each operating system has its own way of specifying this (affinity masks & such)... b...
2,166,473
2,166,684
How to create a multicolumn Listbox?
I'm working on a program, which should list all files and it's size(for now...). I created a simple application, which should write the data to a listbox. I'm trying to write the data in two columns(the first should be the name, and next to it, in an other column, it's size), but i can't figure out, how should i do thi...
The list box control does support multiple columns, but it only supports a single series of entries; the multiple column support just makes the items continue onto the next columns so that vertical scrolling is not necessary. As Kornel has suggested, a list view control may be more appropriate. After creating a list vi...
2,166,475
2,166,489
What would be a good replacement for C++ vector in C#?
I'm working on improving my skills in other languages, coming from using c++ as my primary programming language. My current project is hammering down C#.net, as I have heard it is a good in-between language for one who knows both c++ and VB.net. Typically when working with an unknown number of elements in c++ I would d...
If you target pre .NET 2.0 versions, use ArrayList If you target .NET 2.0+ then use generic type List<T> You may need to find replacements for other C++ standard containers, so here is possible mapping of C++ to .NET 2.0+ similar types or equivalents: std::vector - List<T> std::list - LinkedList<T> std::map - Dictionar...
2,166,483
2,166,491
Which macro to wrap Mac OS X specific code in C/C++
While reading various C and C++ sources, I have encountered two macros __APPLE__ and __OSX__. I found plenty of use of __OSX__ in various codes, especially those originating from *BSD systems. However, sometimes I find that testing __OSX__ only is not sufficient and I have to complete tests with __APPLE__ macro. The P...
It all depends. Each macro specifies something different in meaning. See: https://developer.apple.com/library/mac/documentation/Porting/Conceptual/PortingUnix/compiling/compiling.html#//apple_ref/doc/uid/TP40002850-SW13 __APPLE__ This macro is defined in any Apple computer. __APPLE_CC__ This macro is set to an integer...
2,166,532
2,166,550
Why does GetLastError() (NOT GetReturnMessage) return “wrong password”, when the user name is wrong?
Possible Duplicate: Why does GetErrorMessage return “wrong password”, when the user name is wrong? Since GetErrorMessage gave the same string for invalid password and username, I decided to use GetLastError(), as it has a separate error for each. However with the incorrect username it still gives me the code 12014?...
The function can only tell you what the FTP server returns. The FTP server, being securely coded, says it's the wrong password. There's nothing the function can do to give you a different result from what the FTP server is telling it. :-P For FTP servers that do distinguish between invalid usernames and invalid passwor...
2,166,581
2,166,594
C++ SetWindowsHookEx WH_KEYBOARD_LL Correct Setup
I'm creating a console application in which I'd like to record key presses (like the UP ARROW). I've created a Low Level Keyboard Hook that is supposed to capture all Key Presses in any thread and invoke my callback function, but it isn't working. The program stalls for a bit when I hit a key, but never invokes the cal...
You can't block on a syscall (the getchar), you have to be running a window loop and processing messages before your hook gets called.
2,166,587
2,166,626
Linked lists implementation issue
I'm trying to make a Stack using an underlying linked list structure. Maybe I'm wrong, but I'm having trouble with the remove() function. int Stack::remove(){ node* victim = new node; int popped; popped = top->element; victim = top; top = victim->next; delete victim; return popped; } I'm ge...
A stack is much like a bunch of dishes that are being washed and set on top of one another. That is the first one in is the last one out (FILO data type). That is if your stack read in 2, 7, 8 then it would appear as : 8 7 2 That is first the 2 is placed in the stack, followed by the 7 and then by the 8. If you want...
2,166,622
2,166,673
Why does OpenGL have global functions?
Why isn't openGL object-orientied? Everybody teaches Object Orientated Programming + Design Patterns, but OpenGL has many global functions. Isn't this bad style?
The whole point of a low-level API is to make it as minimal and portable as possible. Giving it an object-oriented architecture would not allow this: Polymorphism adds unnecessary function call overhead. It forces you to use some relatively difficult calling convention, which reduces portability. You cannot wrap an ob...
2,166,802
2,166,817
C++ Binary Tree error: request for member (X) in (Y) which is of non-class type (Z)
Hey all, so I am trying to build a simple binary tree that has two keys and evaluates the sum for its sorting. Here is what it's looking like: struct SumNode { int keyA; int keyB; SumNode *left; SumNode *right; }; class SumBTree { public: SumBTree(); ~SumBTree(); void inse...
you need to replace SumBTree sbt(); with SumBTree sbt; Right now it thinks sbt isn't a class. If there are no parameters in a constructor don't use empty brackets.
2,167,059
2,167,068
A dynamic 2 dimensional array in C++?
I am trying to build a 2 dimensional array in C++ while I don't know how many rows I will have. Here is some code: In the header file: class model { ... ... float vertices[][3]; ... ... } And in the .cpp file: istringstream iss(str); for (int i = 0; i <=2; i++) { iss >> vertices...
You need to either use pointers, or use a dynamically resizable container such as std::vector when you don't know the size.
2,167,093
2,167,115
Best way of replacing heavy exception use?
I have an old C++ project I made a while back. Well, it is a CPU emulator. Whenever a CPU fault happens(such as divide by zero, or debug breakpoint interrupt, etc) in my code it just does a throw and in my main loop I have something like this: try{ *(uint32_t*)&op_cache=ReadDword(cCS,eip); (this->*Opcodes[op_ca...
You haven't shown your loop, but I'm guessing in pseudocode it's: while (some_condition) { // Your try..catch block: try { // Do an op } catch (CpuInt_excp err) { // Handle the exception } } You could move the try..catch out a level: done = false; while (!done) { try { w...
2,167,293
2,167,342
C++ virtual function call versus boost::function call speedwise
I wanted to know how fast is a single-inheritance virtual function call when compared to one same boost::function call. Are they almost the same in performance or is boost::function slower? I'm aware that performance may vary from case to case, but, as a general rule, which is faster, and to a how large degree is that ...
As a very special case, consider calling an empty function 109 times. Code A: struct X { virtual ~X() {} virtual void do_x() {}; }; struct Y : public X {}; // for the paranoid. int main () { Y* x = new Y; for (int i = 100000000; i >= 0; -- i) x->do_x(); dele...
2,167,335
2,167,355
Pure Virtual Method Called
EDIT: SOLVED I'm working on a multi-threaded project right now where I have a base worker class, with varying worker classes that inherit from it. At runtime, the worker classes become threads, which then perform work as needed. Now, I have a Director I've written which is supposed to maintain an array of pointers to a...
The problem appears to be that Director::manageWorker is called in the constructor of workerVariant instances: Director::manageWorker(baseWorkerClass* worker) { workerPtrArray[worker->getThreadID()] = worker; } Presumably getThreadID() isn't a pure virtual function or you would have (hopefully!) gotten a compiler ...
2,167,506
2,167,511
Static member data of template class with two parameters
http://www.adp-gmbh.ch/cpp/templates/static_members.html makes it clear what I need to do - if the template has a single parameter. What if it had two? template <typename T, typename T2> class X { public: static int st_; }; How would I template the static memebr data? template <typename T, typename T2> i...
template <typename T, typename T2> int X<T, T2>::st_; You don't need two int-s. The int is the just type of st_.
2,167,588
2,167,677
boost::function and boost::bind are cool, but what is really cool about boost::lambda?
On Page 175 Paragraph 1 of Effective C++ Meyers has this to say about generalized functors and binding: I find what tr1::function lets you do so amazing, it makes me tingle all over. If you're not tingling , it may be because you're staring at the definition of ... and wondering what's going on with the .......
Based on the comments left above, and the link in the question, the following is the answer I accept (community wiki) : Boost.Lambda fills the purpose of inline functor creation (that's the term I like). This functionality can be filled by Function + Bind, but it is more verbose than it needs to be, and for simple fun...
2,167,802
2,168,276
Resolving typedefs in C and C++
I'm trying to automatically resolve typedefs in arbitrary C++ or C projects. Because some of the typedefs are defined in system header files (for example uint32), I'm currently trying to achieve this by running the gcc preprocessor on my code files and then scanning the preprocessed files for typedefs. I should then be...
If you do not care about figuring out where they are defined, you can use objdump to dump the C++ symbol table which resolves typedefs. lorien$ objdump --demangle --syms foo foo: file format mach-o-i386 SYMBOL TABLE: 00001a24 g 1e SECT 01 0000 .text dyld_stub_binding_helper 00001a38 g 1e SECT 01 0...
2,167,895
2,168,265
Howto implement callback interface from unmanaged DLL to .net app?
in my next project I want to implement a GUI for already existing code in C++. My plan is to wrap the C++ part in a DLL and to implement the GUI in C#. My problem is that I don't know how to implement a callback from the unmanaged DLL into the manged C# code. I've already done some development in C# but the interfacing...
You don't need to use Marshal.GetFunctionPointerForDelegate(), the P/Invoke marshaller does it automatically. You'll need to declare a delegate on the C# side whose signature is compatible with the function pointer declaration on the C++ side. For example: using System; using System.Runtime.CompilerServices; using Sy...
2,167,922
2,167,940
how to make "choose file" function on windows programming?
I need this us all known "choose file" feature in my program, so i can load files. What is this thing called as and where is the code for it?
What you are referring to are the "common dialogs", and you can get a file open dialog with GetOpenFileName BOOL GetOpenFileName( LPOPENFILENAME lpofn ); A sample is available here
2,167,941
2,168,060
Iterating over the types in a boost::variant
I'm using a boost variant to hold some generated types, right now my code generator creates a header with the types and a variant capable of holding them. At initialization time, I'd like to iterate over the allowable types in the variant, not the types the variant is holding at the moment. Can I do this with a varian...
boost::variant exposes its types via types, which is an MPL list. You can do runtime operations over MPL lists using mpl::for_each: struct printer { template<class T> void operator()(T t) { std::cout << typeid(T).name() << std::endl; } }; // ... typedef boost::variant<int, char> var; boost::mpl::for_e...
2,168,054
2,168,059
What does C(++) do with values that aren't stored in variables?
I'm a bit curious about how C and C++ handle data which isn't stored in variables, e.g: int IE6_Bugs = 12345; int Win_Bugs = 56789; Yeah - everything clear. IE6_Bugs has 123456 stored at it's specific memory address. Then what about.. if ( IE6_Bugs + Win_Bugs > 10000 ) { // ... So C grabs the values of the two vari...
It'll be placed in a register in the CPU (assuming one is available). A register is a sort of super-fast super-small RAM that's built into the CPU itself and used to store results of intermediate operations. If the value can be determined to always equal xxx then a smart compiler will substitute the value of xxx in its...
2,168,055
2,168,196
K-Dop collision between different K and Volumes
And now after some work, I finally understand how the KDop bounding volume are created and how the collisions are intersected and I maked a working implementation of them. Now the problem is another. :D How can I intersect (it has to be possible, or it would not make any sense) 2 K-Dop of different K values? (obviously...
If the Ks are a different order, just run your i loop to the minimum of a.K/2 or b.K/2.
2,168,082
2,168,217
How to rewrite array from row-order to column-order?
I have this double for-loop, where I have both row-order and column-order array indexing, which should be bad for performance. for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { /* Column-major order */ d = array_a[col*height +row]; if (d < 0) { d = 0; } /*...
This is never going to be very fast as you'll probably have a number of cache misses, you'll either have to step to the one matrix with a large pitch or the other, there's no escaping that. The problem here is that a computer likes successive memory accesses to be close together, which in your algorithm is not the case...
2,168,201
2,168,222
What is a copy constructor in C++?
On page 6 of Scott Meyers's Effective C++, the term 'copy constructor' is defined. I've been using Schiltdt's book as my reference and I can find no mention of copy constructors. I get the idea but is this a standard part of c++? Will such constructors get called when a pass a class by value?
A copy constructor has the following form: class example { example(const example&) { // this is the copy constructor } } The following example shows where it is called. void foo(example x); int main(void) { example x1; //normal ctor example x2 = x1; // copy ctor example x3(x2); // co...
2,168,233
2,168,248
c++ use of ptr as array base
On page 42 of Effective C++, a pointer is used as an array name ala AirPlane *newBlock = ... newBlock[i].next=0; I've not been aware that this is legal. Is this part of the c++ standard? Is it common practice?
From http://www.cplusplus.com/doc/tutorial/pointers/: In the chapter about arrays we used brackets ([]) several times in order to specify the index of an element of the array to which we wanted to refer. Well, these bracket sign operators [] are also a dereference operator known as offset operator. They de...