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
238,517
238,522
What's a quick way to trace the entry and exit of functions in a Visual Studio 2005 c++ multithreaded program?
I have intermittent crashes occurring in my ActiveMQ libraries due to the way I'm using the activemq-cpp API. It'd be much easier to debug the issue if I could observe every function being called leading up to the crash. Are there any quick ways to trace the entry and exit of functions in a Visual Studio 2005 c++ mul...
Use a Tracer object. Something like this: class Tracer { public: Tracer(const char *functionName) : functionName_(functionName) { cout &lt&lt "Entering function " &lt&lt functionName_ &lt&lt endl; } ~Tracer() { cout &lt&lt "Exiting function " &lt&lt functionName_ &lt&lt endl; } const char *fun...
238,535
238,568
C++ performance of accessing member variables versus local variables
Is it more efficient for a class to access member variables or local variables? For example, suppose you have a (callback) method whose sole responsibility is to receive data, perform calculations on it, then pass it off to other classes. Performance-wise, would it make more sense to have a list of member variables tha...
Executive summary: In virtually all scenarios, it doesn't matter, but there is a slight advantage for local variables. Warning: You are micro-optimizing. You will end up spending hours trying to understand code that is supposed to win a nanosecond. Warning: In your scenario, performance shouldn't be the question, but t...
238,740
238,797
Visio & UML - Showing pointers in attributes and return values
I have the requirement of generating UML Diagrams for one of my C++ assignments. I'm using Visio 2007 and I'm having trouble representing C++ pointers. I've found a way to add a suffix to Datatypes however it's rather time consuming to do this for every pointer used or returned in my program. Basically I'm trying to g...
One solution is to create a custom datatype with Object* as the name but that would need to be done for every class.
238,764
238,785
Visio & UML - Showing vectors
I have the requirement of generating UML Diagrams for one of my C++ assignments. I'm using Visio 2007 and I'm having trouble representing C++ vectors. The only way I can see this working is creating a custom C++ datatype or creating a vector class in my project, then for each instance of a vector in the UML, I need to ...
You don't need to stipulate that it's a vector on the UML diagram. In the example you're giving, there is a one-to-many relationship between one class and another. That's the significant information you need to communicate. You've chosen to implement this as a vector: this is an implementation detail that doesn't need ...
239,302
239,307
Is it useful to test the return of "new" in C++?
I usually never see test for new in C++ and I was wondering why. Foo *f = new Foo; // f is assumed as allocated, why usually, nobody test the return of new?
As per the current standard, new never returns NULL, it throws a std::bad_alloc instead. If you don't want new to throw(as per the old standard) but rather return NULL you should call it by postfixing it with "(std::nothrow)". i.e. Foo* foo = new (std::nothrow) Foo; Of course, if you have a very old or possibly broken...
239,315
239,353
How to embed Ruby in C++?
What's the best way to embed Ruby as a scripting language in C++? Using ruby.h? SWIG? Something else? What I need is to expose some C++ objects to Ruby and have the Ruby interpreter evaluate scripts that access these objects. I don't care about extending Ruby or accessing it in C++. I've found this article on embedding...
swig is probablly the way to go..... but ruby doesnt embed too well...... if you want a language that embeds nicely into C++, try lua
239,344
239,348
How could I improve this C++ code
I want your suggestion on the following pseudo-code. Please suggest how could I improve it, whether or not I could use some design patterns. // i'm receiving a string containing : id operation arguments data = read(socket); tokens = tokenize(data," "); // tokenize the string based on spaces if(tokens[0] == "A") { ...
Have a class for each ID which implements a common interface. Basically the Strategy pattern IIRC. So you'd call (pseudo)code like: StrategyFactory.GetStrategy(tokens[0]).parse(tokens[1..n])
239,588
239,627
STL sorted set where the conditions of order may change
I have a C++ STL set with a custom ordering defined. The idea was that when items get added to the set, they're naturally ordered as I want them. However, what I've just realised is that the ordering predicate can change as time goes by. Presumably, the items in the set will then no longer be in order. So two questions...
set uses the ordering to lookup items. If you would insert N items according to ordering1 and insert an item according to ordering2, the set cannot find out if the item is already in. It will violate the class invariant that every item is in there only once. So it does harm.
240,184
240,235
Freeing memory on the heap. Should I and how?
I'm writing a CESetup.dll for a Windows Mobile app. It must be unmanaged, which I have little experience with. So I'm unsure of whether I should free the memory I allocate and how I do it. Here's the function I've written: Uninstall_Init( HWND hwndParent, LPCTSTR pszInstallDir ) { LPTSTR fold...
I think you want to use this: delete [] folderPath; It looks like you're allocating an array of TCHARs, which makes sense since it's a string. When you allocate an array, you must delete using the array delete operator (which you get by including the brackets in the delete statement). I'm pretty sure you'll get a me...
240,212
240,308
What is the difference between new/delete and malloc/free?
What is the difference between new/delete and malloc/free? Related (duplicate?): In what cases do I use malloc vs new?
new / delete Allocate / release memory Memory allocated from 'Free Store'. Returns a fully typed pointer. new (standard version) never returns a NULL (will throw on failure). Are called with Type-ID (compiler calculates the size). Has a version explicitly to handle arrays. Reallocating (to get more space) not handled...
240,874
240,881
Is there an easy way to use a base class's variables?
When you have a derived class, is there an simpler way to refer to a variable from a method other than: BaseClass::variable EDIT As it so happens, I found a page that explained this issue using functions instead: Template-Derived-Classes Errors. Apparently it makes a difference when using templates classes.
If the base class member variable is protected or public than you can just refer to it by name in any member function of the derived class. If it is private to the base class the compiler will not let the derived class access it at all. Example: class Base { protected: int a; private: int b; }; class Derived :...
241,144
251,586
How to set an initial size of a QScrollArea?
I know that this is a very specific C++ and Qt related question, but maybe someone can help me, anyway ... See the code below: I want to display an image within a scroll area. The view port of the scroll area shall have a defined initial size. That means, if the image's size is bigger than the initial size of the view ...
I think that you are looking at the problem the wrong way. The QScrollArea is just a widget that you put in a frame or QMainWindow. The size of the widget is controlled by the layout of the widget that contains it. Take a look at this example from Trolltech: Image Viewer Example
241,274
241,358
How do I view the contents of an IXMLDOMElementPtr when building an XML file?
I'm using IXMLDOM in MSXML 6 to build an XML file in a C++ MFC application. Is there a way to see the contents of the xml document while it is in memory? For example, an XPATH query is failing about halfway through creating the file. How would I view the entire contents of the xml doc? Thanks!
IXMLDOMElement derives from IXMLDOMNode, and IXMLDOMNode has an xml property that you can use to get the textual representation of the XML in memory. IXMLDOMElementPtr spElement = ...; _bstr_t xmlContents = spElement->xml(); If you're looking for a way to see the contents of the XML in the debugger without changing ex...
241,327
242,226
Remove C and C++ comments using Python?
I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.) I realize that I could .match() substrings with a Regex, but that doesn't solve nesting /*, or having a // inside a /* */. Ideally, I would prefer a non-naive implementation that properly han...
I don't know if you're familiar with sed, the UNIX-based (but Windows-available) text parsing program, but I've found a sed script here which will remove C/C++ comments from a file. It's very smart; for example, it will ignore '//' and '/*' if found in a string declaration, etc. From within Python, it can be used using...
241,403
241,584
How do I get a list of domain user accounts with win32 api?
How do I get a list of domain user accounts with win32 api? In particular, I can't get this list when the computer is not the domain controller. Instead it is a member of the domain.
Look into the LDAP API. This will let you query the LDAP server which will have a list of the user accounts.
241,516
241,521
Howto determine the size of a string give the current font in wxWidgets
Is there a way to determine the display length of a given string (in pixels) based on the currently selected font in (C++) wxWidgets? For example if I print out the string "Speed:" and want to put 10 pixels between the ':' and the value about to follow, I need to know how long the "Speed:" string was. Is there a way t...
Maybe http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcgettextextent ? Note: I'm not a wxWidgets user.
241,581
241,840
Boost C++ libraries for gcc-arm toolchain
I have no trouble building 1.35.0, as well as 1.36.0 on the timesys arm-gcc toolchain, both statically (link-static) as well as dynamically (.so, default option). However, when I try to link a simple sample filesystem app: #include <boost/filesystem.hpp> #include <iostream> namespace fs = boost::filesystem; int main(...
You need to add in file 'boost_1_35_0/boost/config/user.hpp': #define BOOST_SP_USE_PTHREADS btw, you need to set the gcc tool-chain in file 'boost_1_35_0/tools/build/v2/user-config.jam' to: using gcc : arm : /opt/timesys/at91sam9263_ek/toolchain/bin/armv5l-timesys-linux-gnueabi-gcc ; This will solve...
241,936
241,997
Gentle introduction to JIT and dynamic compilation / code generation
The deceptively simple foundation of dynamic code generation within a C/C++ framework has already been covered in another question. Are there any gentle introductions into topic with code examples? My eyes are starting to bleed staring at highly intricate open source JIT compilers when my needs are much more modest. ...
Well a pattern I've used in emulators goes something like this: typedef void (*code_ptr)(); unsigned long instruction_pointer = entry_point; std::map<unsigned long, code_ptr> code_map; void execute_block() { code_ptr f; std::map<unsigned long, void *>::iterator it = code_map.find(instruction_pointer); if(...
241,955
241,972
Checking lists and running handlers
I find myself writing code that looks like this a lot: set<int> affected_items; while (string code = GetKeyCodeFromSomewhere()) { if (code == "some constant" || code == "some other constant") { affected_items.insert(some_constant_id); } else if (code == "yet another constant" || code == "the constant I ...
Since you don't seem to care about the actual values in the set you could replace it with setting bits in an int. You can also replace the linear time search logic with log time search logic. Here's the final code: // Ahead of time you build a static map from your strings to bit values. std::map< std::string, int > c...
242,695
242,709
Long strings with newlines
I have seen C# code that uses the @ to tell the compiler the string has newlines in it and that it should be all in one line. Is there something like that for C/C++? Like if I want to put something like: 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112...
C and C++ have automatic concatenation of adjacent quoted strings. This means that const char *a = "a" "b"; and const char *b = "ab"; will make a and b point at identical data. You can of course extend this, but it becomes troublesome when the strings contain quotes. Your example seems not to, so it might be practic...
242,894
254,521
CUDA Driver API vs. CUDA runtime
When writing CUDA applications, you can either work at the driver level or at the runtime level as illustrated on this image (The libraries are CUFFT and CUBLAS for advanced math): (source: tomshw.it) I assume the tradeoff between the two are increased performance for the low-evel API but at the cost of increased com...
The CUDA runtime makes it possible to compile and link your CUDA kernels into executables. This means that you don't have to distribute cubin files with your application, or deal with loading them through the driver API. As you have noted, it is generally easier to use. In contrast, the driver API is harder to progr...
242,926
242,942
Comparison of C++ unit test frameworks
I know there are already a few questions regarding recommendations for C++ unit test frameworks, but all the answers did not help as they just recommend one of the frameworks but do not provide any information about a (feature) comparison. I think the most interesting frameworks are CppUnit, Boost and the new Google te...
See this question for some discussion. They recommend the articles: Exploring the C++ Unit Testing Framework Jungle, By Noel Llopis. And the more recent: C++ Test Unit Frameworks I have not found an article that compares googletest to the other frameworks yet.
243,082
243,150
C++ casting programmatically : can it be done?
Let's say I have a Base class and several Derived classes. Is there any way to cast an object to one of the derived classes without the need to write something like this : string typename = typeid(*object).name(); if(typename == "Derived1") { Derived1 *d1 = static_cast&lt Derived1*&gt(object); } else if(typename ==...
Don't. Read up on polymorphism. Almost every "dynamic cast" situation is an example of polymorphism struggling to be implemented. Whatever decision you're making in the dynamic cast has already been made. Just delegate the real work to the subclasses. You left out the most important part of your example. The use...
243,242
243,829
Pointer-to-data-member-of-data-member
I had the following piece of code (simplified for this question): struct StyleInfo { int width; int height; }; typedef int (StyleInfo::*StyleInfoMember); void AddStyleInfoMembers(std::vector<StyleInfoMember>& members) { members.push_back(&StyleInfo::width); members.push_back(&StyleInfo::height); } No...
Remember a pointer to a member is just used like a member. Obj x; int y = (x.*)ptrMem; But like normal members you can not access members of subclasses using the member access mechanism. So what you need to do is access it like you would access a member of the object (in your case via the size member). #include <v...
243,269
243,304
How do I get a "busy wheel" on Windows Mobile 6?
Windows Mobile pops up a "busy wheel" - a rotating colour disk - when things are happening . I can't find in the documentation how this is done - can someone point me in the right direction? We have a situation where we need to prompt the user to say we're doing stuff for a while, but we don't know how long it will ta...
Use SetCursor/LoadCursor/ShowCursor APIs, like this: SetCursor(LoadCursor(NULL, IDC_WAIT)); // my code ShowCursor(FALSE);
243,322
1,141,107
Save State of a Direct3D Device
State should include at least the following: All settings set via SetStreamResource() Indices I have a class whose Draw() function will call SetStreamResource, set Indices and eventually call DrawIndexedPrimitive(). I would like to restore the device state before Draw() returns. I am looking for something along the l...
State blocks are the mechanism provided by the API to save and restore chunks of device state. I cover the details of state blocks in Chapter 3. Direct3D Devices from my book The Direct3D Graphics Pipeline. You can download the PDF for that chapter from the link above.
243,365
243,548
creating objects dynamically in C++
I was just reading this thread and it occurred to me that there is one seemingly-valid use of that pattern the OP is asking about. I know I've used it before to implement dynamic creation of objects. As far as I know, there is no better solution in C++, but I was wondering if any gurus out there know of a better way....
I think what you are asking is how to keep the object creation code with the objects themselves. This is usually what I do. It assumes that there is some key that gives you a type (int tag, string, etc). I make a class that has a map of key to factory functions, and a registration function that takes a key and factor...
243,381
243,562
Anything I should know before converting a large C++ program from VS2005 to VS2008?
Is there anything I should know before converting a large C++ program from VS2005 to VS2008?
I'm working on this very problem right now. Running WinMerge to see what I've changed... OK, here is what I had to fix in an huge Win32/MFC client application: Some MFC functions have become virtual (which were not in the past - CWnd::GetMenu for one, if I recall correctly). Also something related to our legacy mouse ...
243,383
243,447
Why can't C++ be parsed with a LR(1) parser?
I was reading about parsers and parser generators and found this statement in wikipedia's LR parsing -page: Many programming languages can be parsed using some variation of an LR parser. One notable exception is C++. Why is it so? What particular property of C++ causes it to be impossible to parse with LR parsers? Us...
There is an interesting thread on Lambda the Ultimate that discusses the LALR grammar for C++. It includes a link to a PhD thesis that includes a discussion of C++ parsing, which states that: "C++ grammar is ambiguous, context-dependent and potentially requires infinite lookahead to resolve some ambiguities". ...
243,568
243,841
CTimeSpan.GetDays() and daylight savings time
I found in a bug in an old C++ MFC program we have that calculates an offset (in days) for a given date from a fixed base date. We were seeing results that were off by one for some reason, and I tracked it down to where the original programmer had used the CTimeSpan.GetDays() method. According to the documentation: ...
Your fix works fine to get the number of whole 24-hour periods between two times - as long as the events occur at the same time each day. Otherwise that "+1" in the expression could lead to an off-by-one error. Sometimes you don't care what time of day the event occured, you just want to know which day. In that case,...
243,696
244,584
Correctly over-loading a stringbuf to replace cout in a MATLAB mex file
MathWorks currently doesn't allow you to use cout from a mex file when the MATLAB desktop is open because they have redirected stdout. Their current workaround is providing a function, mexPrintf, that they request you use instead. After googling around a bit, I think that it's possible to extend the std::stringbuf cl...
You don't really want to overload std::stringbuf, you want to overload std::streambuf or std::basic_streambuf (if you want to support multiple character types), also you need to override the overflow method as well. But I also think you need to rethink your solution to your problem. cout is just an ostream, so if all c...
243,802
243,827
Memory allocation on Windows C code
I'd like to know which method is recommended on Windows C programming: using malloc or the Win32 HeapAlloc (maybe VirtualAlloc?) function. I've read the MSDN Memory Management Functions article and the MSDN articles regarding malloc and HeapAlloc, but they do not say which one should be used and in what situations.
Stick with malloc unless you have a compelling reason to use something different. It will be implemented underneath in terms of the OS memory allocation primitives, but there is no real advantage in diving down to that layer yourself. A few API calls I believe need a memory block allocated from a Windows heap, but you...
244,316
244,344
Reader/Writer Locks in C++
I'm looking for a good reader/writer lock in C++. We have a use case of a single infrequent writer and many frequent readers and would like to optimize for this. Preferable I would like a cross-platform solution, however a Windows only one would be acceptable.
Newer versions of boost::thread have read/write locks (1.35.0 and later, apparently the previous versions did not work correctly). They have the names shared_lock, unique_lock, and upgrade_lock and operate on a shared_mutex.
244,453
244,583
Best documentation for Boost:asio?
The documentation available on the boost website is... limited. From what I've been able to read, the general consensus is that it is simply difficult to find good documentation on the boost::asio library. Is this really the case? If so, why? Notes: I have already found the (non-boost) Asio website - and the document...
First, I've been using Boost.Asio for quite a while already -- and I share your concern. To address your question: There really is very scarce documentation about Boost.Asio aside from the introduction and tutorial. I am not the author, but this is mostly because there are just too many things to document for somethin...
244,487
244,507
How do I sort a CArray of a user defined type?
Is there a built-in way to sort a CArray in C++?
std::sort() should work: CArray<int> arrayOfInts; arrayOfInts.Add(7); arrayOfInts.Add(114); arrayOfInts.Add(3); std::sort(arrayOfInts.GetData(), arrayOfInts.GetData()+arrayOfInts.GetSize()); This uses the pointer to the first element in the array as the start iterator, and the pointer to one past the last element as t...
244,492
244,552
MFC Panel and window handle
Is there something like a panel that I can use in a MFC application. This is to overlay the default window in MFC (a dialog application). Then to paint the panel black and paint some random stuff on top of it. Something like a view port. is there a better option than this to achieve the same effect ?
Sure. It's called a window! Create a class that derives from CWnd and overrides OnPaint(). In your dialog's OnInitInstance(), instantiate a CMyWnd object and call it's Create() member. Of course, make sure the lifetime of your CMyWnd object is the same as the dialog's object lifetime window. iow, make it a member of yo...
244,646
244,676
Get elapsed time in Qt
I'm looking for the equivalent in Qt to GetTickCount() Something that will allow me to measure the time it takes for a segment of code to run as in: uint start = GetTickCount(); // do something.. uint timeItTook = GetTickCount() - start; any suggestions?
How about QTime? Depending on your platform it should have 1 millisecond accuracy. Code would look something like this: QTime myTimer; myTimer.start(); // do something.. int nMilliseconds = myTimer.elapsed();
244,784
245,261
YAML serialization library for C++?
YAML seems like a great format for configuration files & data binding persistent objects in human-readable form... Is there a C++ library that handles YAML? Does Boost::Serialization have plans for a YAML option? EDIT: I would prefer an OO library.
A quick search gave me this: yaml-cpp
244,845
244,859
Unit testing Visitor pattern architecture
I've introduced visitors as one of core architecture ideas in one of my apps. I have several visitors that operate on a same stuff. Now, how should I test it? Some tests I'm thinking of are a bit larger then a unit test should be (integration test? whatever) but I still wanna do it. How would you test code like the C+...
make a test visitor object and make it visit things.... test that it visited the right things.
245,475
245,483
How do I create a generic std::vector destructor?
Having a vector containing pointers to objects then using the clear function doesn't call the destructors for the objects in the vector. I made a function to do this manually but I don't know how to make this a generic function for any kind of objects that might be in the vector. void buttonVectorCleanup(vector<Button ...
The best thing to do is use smart pointers, such as from Boost. Then the objects will be deleted automatically. Or you can make a template function template <class T> void vectorCleanup(vector<T *>& dVector){ T* tmpClass; for(vector<T*>::size_type i = 0; i < dVector.size(); i++){ tmpClass = dVector[i];...
245,619
245,625
Howto initialise char array style string in constructor
I have a class which I'm serialising to send over a unix socket and it has to have a string which I've stored as a char array. Can I initialise it in the constructor differently to how I've done it here? typedef struct SerialFunctionStatus_t { SerialFunctionStatus_t() : serial_rx_count(0), serial_tx_count...
Put port() in the initializer list. This causes port to be 'value initialized' (12.6.2), which for arrays of builtins means zero initialized (8.5).
245,628
245,636
C++ Binary Search Tree Recursive search function
template <class T> bool BST<T>::search(const T& x, int& len) const { return search(BT<T>::root, x); } template <class T> bool BST<T>::search(struct Node<T>*& root, const T& x) { if (root == NULL) return false; else { if (root->data == x) return true; else if(root-...
Okay, bool BST<T>::search(struct Node<T>*& root, const T& x) should probably have const after it like so: bool BST<T>::search(struct Node<T>*& root, const T& x) const. Basically, you've called a non-const function from a const function and this is a no-no. BTW, this looks suspect to me "struct Node<T>*&"... I'd probabl...
245,742
245,761
Examples of good gotos in C or C++
In this thread, we look at examples of good uses of goto in C or C++. It's inspired by an answer which people voted up because they thought I was joking. Summary (label changed from original to make intent even clearer): infinite_loop: // code goes here goto infinite_loop; Why it's better than the alternatives:...
Heres one trick I've heard of people using. I've never seen it in the wild though. And it only applies to C because C++ has RAII to do this more idiomatically. void foo() { if (!doA()) goto exit; if (!doB()) goto cleanupA; if (!doC()) goto cleanupB; /* everything has succeeded ...
245,838
245,928
Binary Search Tree Deletion (Inorder Pred method) C++
Ok so I thought it was fixed, but I'm getting totally inconsistent results. I rewrote it kind of from scratch to start fresh and here are my results. I get no errors, no crashing, it just doesn't remove them. It just totally messes up the tree and gives me a ton more leaves, and mixes everything up. Not sure where e...
Are each T found in the tree unique? It looks like they are from your code... It looks like this should work: In the else case deleting the root node: Node<T> *tmp_r = root->left; Node<T> *parent = root; while (tmp_r->right != NULL) { parent = tmp_r; tmp_r = tmp_r->right; } Node<T> *tmp_l = tmp_r; while (tmp_l-...
246,071
246,083
Basic example of a scriptable plugin for Firefox in C++ with VS2005/8
My experience to write a plugin for Firefox is below zero. Is someone out there who could point me to sample code on how to get this accomplished in C++ with VS2005/8? What I need to do with JavaScript in the hosting html page is something like this: var obj = document.getElementById("MyFFPlugin"); var value = obj.Ca...
The SDK has basic samples on how to write mozzila plugins which can be downloaded here: http://mxr.mozilla.org/seamonkey/source/modules/plugin/tools/sdk/ Here is the official mozilla plugin site http://www.mozilla.org/projects/plugins/ Hope it helps.
246,077
246,084
How are Windows VK_ constants declared?
For example VK_LEFT, VK_DELETE, VK_ESCAPE, VK_RETURN, etc. How and where are they declared? Are they constants, #defines, or something else? Where do they come from? If possible, please provide a file name/path where they are declared. Or some other info as specific as possible.
These are declared using #define in the file winuser.h in the Platform SDK. In my installation of Visual Studio 2008, the full path is C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WinUser.h
246,293
246,323
c++ dynamic_cast error handling
Is there any good practice related to dynamic_cast error handling (except not using it when you don't have to)? I'm wondering how should I go about NULL and bad_cast it can throw. Should I check for both? And if I catch bad_cast or detect NULL I probably can't recover anyway... For now, I'm using assert to check if dyn...
If the dynamic_cast should succeed, it would be good practice to use boost::polymorphic_downcast instead, which goes a little something like this: assert(dynamic_cast<T*>(o) == static_cast<T*>(o)); return static_cast<T*>(o); This way, you will detect errors in the debug build while at the same time avoiding the runtim...
246,407
248,673
Disable sleep mode in Windows Mobile 6
Does anyone know how could I programatically disable/enable sleep mode on Windows Mobile? Thanks!
If you want your program to not be put to sleep while it's running, the best way is to create a KeepAlive type function that calls SystemIdleTimerReset, SHIdleTimerReset and simulates a key touch. Then you need to call it a lot, basically everywhere. #include <windows.h> #include <commctrl.h> extern "C" { void WI...
246,445
246,457
create std::string from char* in a safe way
I have a char* p, which points to a \0-terminated string. How do I create a C++ string from it in an exception-safe way? Here is an unsafe version: string foo() { char *p = get_string(); string str( p ); free( p ); return str; } An obvious solution would be to try-catch - any easier ways?
You can use shared_ptr from C++11 or Boost: string foo() { shared_ptr<char> p(get_string(), &free); string str(p.get()); return str; } This uses a very specific feature of shared_ptr not available in auto_ptr or anything else, namely the ability to specify a custom deleter; in this case, I'm using free as ...
246,564
246,568
What is the lifetime of a static variable in a C++ function?
If a variable is declared as static in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called? void foo() { static string plonk = "When will I die?"; }
The lifetime of function static variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed. Additionally, since the standard says that the destr...
246,683
246,715
CFile Error On Windows Ce
I am using Windows CE 4.2 and MS Embedded VC++ 4.0. The following code gives me the error Access to [file name] was denied., and it creates the file but does not write anything to it. CString tmp; tmp.Format(_T("%s%d"), mFileName, ++ctr); TRY { mFile.Open(tmp, CFile::modeCreate); mFile.Write(&data[ctr%2], 1); m...
I've not used MFC on Windows CE, but on ordinary Windows, the usual idiom is mFile.Open(tmp, CFile::modeCreate|CFile::modeWrite); i.e. try adding "CFile::modeWrite" to the constructor. The MSDN documentation suggests that this is necessary: You can combine options listed below by using the bitwise-OR (|) operator. On...
246,806
246,811
I want to convert std::string into a const wchar_t *
Is there any method? My computer is AMD64. ::std::string str; BOOL loadU(const wchar_t* lpszPathName, int flag = 0); When I used: loadU(&str); the VS2005 compiler says: Error 7 error C2664:: cannot convert parameter 1 from 'std::string *__w64 ' to 'const wchar_t *' How can I do it?
If you have a std::wstring object, you can call c_str() on it to get a wchar_t*: std::wstring name( L"Steve Nash" ); const wchar_t* szName = name.c_str(); Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in MultiByteToW...
247,093
248,604
Edit Registry Values
I want to change the registry values on the pocketPC. I ran the following code: if(enabled) { dwData = 120; } if(RegSetValueEx(HKEY_LOCAL_MACHINE, _T("System\\CurrentControlSet\\Control\\Power\\Timeouts\\BattSuspendTimeout"), 0, REG_DWORD, (LPBYTE)&dwData, sizeof(DWORD))) { return FALSE; } but it doesn't shang...
There are a two problems with what you are doing: 1: RegSetValueEx does not take a path, only a valuename. So you need to open the key path first. e.g. HKEY key; if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Control\\Power\\Timeouts", 0, 0, &key)) { if(RegSetValueEx(key, _T("BattS...
247,538
248,891
Which standard c++ classes cannot be reimplemented in c++?
I was looking through the plans for C++0x and came upon std::initializer_list for implementing initializer lists in user classes. This class could not be implemented in C++ without using itself, or else using some "compiler magic". If it could, it wouldn't be needed since whatever technique you used to implement init...
std::type_info is a simple class, although populating it requires typeinfo: a compiler construct. Likewise, exceptions are normal objects, but throwing exceptions requires compiler magic (where are the exceptions allocated?). The question, to me, is "how close can we get to std::initializer_lists without compiler magi...
247,639
250,159
What is the Performance, Safety, and Alignment of a Data member hidden in an embedded char array in a C++ Class?
I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are: Pool. This is a class which allocates memory efficiently, for some definition of 'efficient'. Pool is guaranteed to return a chunk of memory that is alig...
Ok - had a chance to read it properly. You have an alignment problem, and invoke undefined behaviour when you access the char array as an Obj_list. Most likely your platform will do one of three things: let you get away with it, let you get away with it at a runtime penalty or occasionally crash with a bus error. You...
247,703
247,721
Getting the name of the current method in c++
Is there a (standardized) way to get the name of the current method using c++? Using GNU GCC you can do this by using the macro __FUNCTION__ and __PRETTY_FUNCTION__ (surrounded by 2 underscores), however, this is of course non portable. Is there a way to do this in standard c++ or a way to make it portable?
The __func__ identifier is part of the C99 standard and is in the C++0x draft. The identifier __func__ is implicitly declared by the compiler as if the following were at the very start of each function body: static const char __func__[] = "function-name"; where function-name is an implementation-defined string automat...
247,738
247,764
Is it safe to assume that STL vector storage is always contiguous?
If you have an STL vector which has been resized, is it safe to take the address of element 0 and assume the rest of the vector will follow in memory? e.g. vector<char> vc(100); // do some stuff with vc vc.resize(200); char* p = &vc[0]; // do stuff with *p
Yes, that is a valid assumption (*). From the C++03 standard (23.2.4.1): The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size(). (*) ... but watch out for the array being re...
247,818
247,859
stl::multimap - how do i get groups of data?
Multimap essentially has groups of data sorted by the key. I want a method by which I could access these individual groups and get their aggregate values. For example, in a std::multimap< string, int > I store {"Group1", 1}, {"Group1", 2}, {"Group1", 3}, {"Group2", 10}, {"Group2", 11}, {"Group2", 12} Having sto...
pair<Iter, Iter> range = my_multimap.equal_range("Group1"); int total = accumulate(range.first, range.second, 0); Is one way. Edit: If you don't know the group you are looking for, and are just going through each group, getting the next group's range can be done like so: template <typename Pair> struct Less : public s...
248,104
248,119
How Do I Use Eclipse to Debug a C++ Program on Linux?
I don't use Eclipse as an IDE, and have no interest in doing so. However, I do like its source-level debugging. Is there any way I can use it to debug a C++ Linux app without going through the ritual of creating a project? (In effect, can I just use it like a frontend to gdb?) If not, what are the steps I need to fol...
Take a look at this question. Create a C/C++-project, use your project's source directory as project directory, select to use the external builder, and change "make" to whatever tool you want. The tricky part is to get the indexer to work correctly and find all your header files. EDIT: CMake 2.6.x has support for gener...
248,134
248,153
How can I experiment with garbage collection?
I'm interested in how garbage collection works. I've read up on how some work such as mark-and-sweep, stop-and-copy, generational GC, etc... I'd like to experiment with implementing some of these and comparing their behaviors. What's a good way to get started experimenting with my own? Ideally something in C, Java or P...
Never played with it myself, but the one that always gets mentioned for use with C/C++ is Hans Boehm's.
248,182
249,476
My C++ ActiveMQ client can send messages, but not receive messages
I have the ActiveMQ-CPP 2.2.1 Visual Studio 2005 project compiling and running. In the console window, it shows the messages are being sent, though they're not being received. I can both send and receive messages with ActiveMQ-CPP 2.0.1, but not 2.2.1. I'm new to ActiveMQ and don't even know where to begin troublesh...
I'd recommend posting this to the user forum to get the ActiveMQ C++ developers to help. Maybe even raise a JIRA with a test case
248,400
248,479
Finding composite numbers
I have a range of random numbers. The range is actually determined by the user but it will be up to 1000 integers. They are placed in this: vector<int> n and the values are inserted like this: srand(1); for (i = 0; i < n; i++) v[i] = rand() % n; I'm creating a separate function to find all the non-prime values. ...
In this code: if(i % v[j] == 0) cout << v[j] << endl; You are testing your index to see if it is divisible by v[j]. I think you meant to do it the other way around, i.e.: if(v[j] % i == 0) Right now, you are printing random divisors of i. You are not printing out random numbers which are known not to be prime. A...
248,421
251,634
Thread safety of Matlab engine API
I have discovered through trial and error that the MATLAB engine function is not completely thread safe. Does anyone know the rules? Discovered through trial and error: On Windows, the connection to MATLAB is via COM, so the COM Apartment threading rules apply. All calls must occur in the same thread, but multiple con...
When I first started using the engine, I didn't run across any documentation on thread safety, so I assumed that it was not thread-safe. I use a C++ class to synchronize access to an engine instance. For more parallel processing designs, I instantiate multiple instances of the engine class. (edit) I'm using MATLAB R14 ...
248,617
248,643
c++ adding method to class defined in header file
I'm wondering if it is possible to add methods in main program to an existing class defined in header file. For example: There is class CFun defined in file CFun.hpp, but in our party.cpp we want to add a method void hello() {cout << "hello" << endl;};without editing CFun.hpp Obviously (unfortunately) construction: #in...
No, but you could add a method that takes a reference/pointer to a CFun class - you just won't have access to private data: void Hello(CFun &fun) { cout << "hello" << endl; } This is probably the best you'll be able to do. As pointed out by litb - this function has to be in the same namespace as CFun. Fortunatel...
248,693
248,698
Double Negation in C++
I just came onto a project with a pretty huge code base. I'm mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic. if (!!variable && (!!api.lookup("some-string"))) { do_some_stuff(); } I know these guys are intelligent progr...
It's a trick to convert to bool.
249,009
249,014
Do you use curly braces for additional scoping?
I mean other than using it when required for functions, classes, if, while, switch, try-catch. I didn't know that it could be done like this until I saw this SO question. In the above link, Eli mentioned that "They use it to fold up their code in logical sections that don't fall into a function, class, loop, etc. that ...
I do if I am using a resource which I want to free at a specific time eg: void myfunction() { { // Open serial port SerialPort port("COM1", 9600); port.doTransfer(data); } // Serial port gets closed here. for(int i = 0; i < data.size(); i++) doProcessData(data[i]); etc... }
249,062
249,131
Easy to use SNMP client library for c++?
What's an easy to use SNMP client library for c++?
Probably the best choice is net-snmp. Note that the library has "C" linkage but will work just fine with C++.
249,415
249,463
Single-threading two processes
I have two C++ processes (A and B), executing under Windows, where one launches the other. I would like to effectively single-thread their execution. For example: Start process A A creates B A suspends B executes some fixed set of operations B suspends and A is resumed A executes some fixed set of operations A suspend...
Events would work in this case: A creates an event an starts Process B A waits for the event to be signaled B also creates an event, does it's first item, then signals A's event (which either has a well-known name or the handle can be passed to B when it starts or using some other mechanism B waits on its event when A...
249,500
249,525
Looking for a better way than virtual inheritance in C++
OK, I have a somewhat complicated system in C++. In a nutshell, I need to add a method to a third party abstract base class. The third party also provides a ton of derived classes that also need the new functionality. I'm using a library that provides a standard Shape interface, as well as some common shapes. class Sha...
We had a very similar problem in a project and we solved it by just NOT deriving ImprovedShape from Shape. If you need Shape functionality in ImprovedShape you can dynamic_cast, knowing that your cast will always work. And the rest is just like in your example.
249,581
249,981
Explain Facade pattern with c++ example?
I have checked with the wikipedia article, and it seems like it is missing the c++ version of a code example. I am not able to fully appreciate the Facade pattern without this, can you please help explain it to me using C++?
Facade pattern: provides a unified - simplified interface to a complex subsystem or set of interfaces. It provides a higher level interface simultaneously decoupling the client from the complex subsystem. An example to help you understand .. a cab driver. You tell the cab driver 'Take me to PointX' (unified simplified ...
249,607
254,069
VC++ linker errors on std::exception::_Raise and std::exception::exception
I am using Visual C++ 2005 Express Edition and get the following linker errors: 19>mylib1.lib(mylibsource1.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::exception::_Raise(void)const " (__imp_?_Raise@exception@std@@QBEXXZ) referenced in function "protected: static v...
Adding this line: #define _STATIC_CPPLIB before including the vector header seems to do the trick.
250,096
250,745
How to read arbitrary number of values using std::copy?
I'm trying to code opposite action to this: std::ostream outs; // properly initialized of course std::set<int> my_set; // ditto outs << my_set.size(); std::copy( my_set.begin(), my_set.end(), std::ostream_iterator<int>( outs ) ); it should be something like this: std::istream ins; std::set<int>::size_type size; ins ...
You could derive from the istream_iterator<T>. Though using Daemin generator method is another option, though I would generate directly into the set rather than use an intermediate vector. #include <set> #include <iterator> #include <algorithm> #include <iostream> template<typename T> struct CountIter: public std::is...
250,394
250,701
Does anyone know of any C/C++/C# code libraries that do audio synthesizer emulation?
I'm trying to write a software synthesizer that recreates the sounds made by classic synthesizers like the Moog and the DX7. Does anyone know of any code resources for something like this? Thanks.
There are an awful lot of C/C++ libraries out there, most no longer updated. There's not much for C#, but I have seen a couple. I haven't really used any of them in anger, so I can't give any recommendations. I would start with Harmony Central and see if you find anything of use there. Alternatively, a search for analo...
251,007
251,066
How difficult is it to turn a "Java School" programmer into a C or C++ programmer?
My company, a C++ house, is always looking to hire recent grads. However due to the Java Schools phenomenon, we typically end up interviewing strong Java programmers with maybe a minute smattering of C++. Often the C++ classes don't really prepare students for working in C++. Nevertheless, often these are bright kids, ...
Well, if they don't understand data structures and algorithmic complexity, they aren't going to be much good at serious Java programming, so I don't see that the language is an issue here. They won't understand pointers, but good C++ programming typically doesn't use pointers in complicated ways. (There are exceptions...
251,159
251,223
What is the use of const overloading in C++?
In C++, a function's signature depends partly on whether or not it's const. This means that a class can have two member functions with identical signatures except that one is const and the other is not. If you have a class like this, then the compiler will decide which function to call based on the object you call it...
This really only makes sense when the member function returns a pointer or a reference to a data member of your class (or a member of a member, or a member of a member of a member, ... etc.). Generally returning non-const pointers or references to data members is frowned upon, but sometimes it is reasonable, or simply...
251,248
251,267
How can I get the SID of the current Windows account?
I am looking for an easy way to get the SID for the current Windows user account. I know I can do it through WMI, but I don't want to go that route. Apologies to everybody that answered in C# for not specifying it's C++. :-)
In Win32, call GetTokenInformation, passing a token handle and the TokenUser constant. It will fill in a TOKEN_USER structure for you. One of the elements in there is the user's SID. It's a BLOB (binary), but you can turn it into a string by using ConvertSidToStringSid. To get hold of the current token handle, use Open...
251,325
251,335
Passing a Class Object to a function (probably by pointer not reference) C++
So let's say I have two different functions. One is a part of the BST class, one is just a helper function that will call on that Class function. I will list them out here. sieve(BST<T>* t, int n); this function is called like this: sieve(t,n) the object is called BST t; I'm going to be using the class remove fun...
sieve(BST<int>& t, int n) The & specifies passing by reference rather than value. :-)
251,403
252,106
how do you make a heterogeneous boost::map?
I want to have a map that has a homogeneous key type but heterogeneous data types. I want to be able to do something like (pseudo-code): boost::map<std::string, magic_goes_here> m; m.add<int>("a", 2); m.add<std::string>("b", "black sheep"); int i = m.get<int>("a"); int j = m.get<int>("b"); // error! I could have a po...
#include <map> #include <string> #include <iostream> #include <boost/any.hpp> int main() { try { std::map<std::string, boost::any> m; m["a"] = 2; m["b"] = static_cast<char const *>("black sheep"); int i = boost::any_cast<int>(m["a"]); std::cout << "I(" << i << ")\n"; ...
251,432
251,446
typedefs for templated classes?
Is it possible to typedef long types that use templates? For example: template <typename myfloat_t> class LongClassName { // ... }; template <typename myfloat_t> typedef std::vector< boost::shared_ptr< LongClassName<myfloat_t> > > LongCollection; LongCollection<float> m_foo; This doesn't work, but is there a wa...
No, that isn't possible currently. It will be made possible in C++0X AFAIK. The best I can think of is template<typename T> struct LongCollection { typedef std::vector< boost::shared_ptr< LongClassName<T> > > type; }; LongCollection<float>::type m_foo;
252,297
252,302
Why is RegOpenKeyEx() returning error code 2 on Vista 64bit?
I was making the following call: result = RegOpenKeyEx(key, s, 0, KEY_READ, &key); (C++, Visual Studio 5, Vista 64bit). It is failing with error code 2 ("File not found") even though "regedit" shows that the key exists. This code has always worked on 32bit XP. Why is it "file not found" when it clearly is there?
I discovered that I could solve my problem using the flag: KEY_WOW64_64KEY , as in: result = RegOpenKeyEx(key, s, 0, KEY_READ|KEY_WOW64_64KEY, &key); For a full explanation: 32-bit and 64-bit Application Data in the Registry
252,492
252,516
What's the latest version of Boost compatible with VC++6?
What is the latest version of the Boost library that is compatible with Microsoft Visual C++ 6? And can you provide a link to download it directly? The Downloads link at http://www.boost.org only gives a download for version 1.36.0, and the documentation for that version lists Visual C++ 7.1 as the lowest version of M...
Boost 1.34.1 has been tested with vc6. The old versions are still available.
252,515
252,518
Why do we even need the "delete[]" operator?
This is a question that's been nagging me for some time. I always thought that C++ should have been designed so that the delete operator (without brackets) works even with the new[] operator. In my opinion, writing this: int* p = new int; should be equivalent to allocating an array of 1 element: int* p = new int[1]; ...
It's so that the destructors of the individual elements will be called. Yes, for arrays of PODs, there isn't much of a difference, but in C++, you can have arrays of objects with non-trivial destructors. Now, your question is, why not make new and delete behave like new[] and delete[] and get rid of new[] and delete[]...
252,671
252,678
Is auto ever useful in C/C++?
Has anyone ever seen the storage class auto explicitly used in C/C++? If so, in what situation?
auto is never useful in current C/C++ because all variables are implicitly auto. It is useful in C++0x, where it can replace the type declaration entirely - if you have a variable with an initial assignment, 'auto' will just make it the type of that assignment value, as in the comments.
252,819
253,009
C++ : how to link against libA.so and not libA-X.Y.Z.so
I have a library A, that I develop. When I deploy it on a machine, the corresponding libA.so and libA-X.Y.Z.so are put in /usr/lib (X.Y.Z being the version number). Now I develop a library B, which uses A. When I link B, I use the flag -lA. Then "ldd libB.so" gives me : (...) libA-X.Y.Z.so => /usr/lib/libA-X.Y.Z.so (...
When you create libA.so, pass the -soname option to the linker (if you linking through gcc, use -Wl,-soname). Then, when B gets linked, the linker refers to A through its soname, not through its filename. On the target system, make sure you have a link from the soname to the real file. See http://www.linux.org/docs/ldp...
252,951
252,996
Finding invocations of a certain function in a c++ file using python
I need to find all occurrences of a function call in a C++ file using python, and extract the arguments for each call. I'm playing with the pygccxml package, and extracting the arguments given a string with the function call is extremely easy: from pygccxml.declarations import call_invocation def test_is_call_invocati...
XML-GCC can't do that, because it only reports the data types (and function signatures). It ignores the function bodies. To see that, create a.cc: void foo() {} void bar() { foo(); } and then run gccxml a.cc -fxml=a.xml. Look at the generated a.xml, to see that the only mentioning of foo (or its id) is in the...
252,962
253,128
Read 64 bit integer string from file
We have a file that has a 64 bit integer as a string in it. How do we scanf() or otherwise parse this numeric string into an unsigned 64 bit integer type in C++ ? We are aware of things like %lld etc., but a lot of ways to do this parse seem to break compiles under different compilers and stdlibs. The code should comp...
GCC has long long, as will compilers for C++0x. MSVC++ doesn't (yet), but does have its __int64 you can use. #if (__cplusplus > 199711L) || defined(__GNUG__) typedef unsigned long long uint_64_t; #elif defined(_MSC_VER) || defined(__BORLANDC__) typedef unsigned __int64 uint_64_t; #else #error "Please define ui...
253,099
2,123,260
How do I print the elements of a C++ vector in GDB?
I want to examine the contents of a std::vector in GDB, how do I do it? Let's say it's a std::vector<int> for the sake of simplicity.
To view vector std::vector myVector contents, just type in GDB: (gdb) print myVector This will produce an output similar to: $1 = std::vector of length 3, capacity 4 = {10, 20, 30} To achieve above, you need to have gdb 7 (I tested it on gdb 7.01) and some python pretty-printer. Installation process of these is descr...
253,157
253,173
How to downsize std::vector?
Is there a way to resize a std::vector to lower capacity when I no longer need previously reserved space?
Effective STL, by Scott Meyers, Item 17: Use the swap trick to trim excess capacity. vector<Person>(persons).swap(persons); After that, persons is "shrunk to fit". This relies on the fact that vector's copy constructor allocates only as much as memory as needed for the elements being copied.
253,212
253,223
What are assertions? and why would you use them?
How are assertions done in c++? Example code is appreciated.
Asserts are a way of explicitly checking the assumptions that your code makes, which helps you track down lots of bugs by narrowing down what the possible problems could be. They are typically only evaluated in a special "debug" build of your application, so they won't slow down the final release version. Let's say you...
253,284
253,318
How do you inherit from a class in a different header file?
I am having dependency troubles. I have two classes: Graphic and Image. Each one has its own .cpp and .h files. I am declaring them as the following: Graphic.h: #include "Image.h" class Image; class Graphic { ... }; Image.h: #include "Graphic.h" class Graphic; class Image : p...
This worked for me: Image.h: #ifndef IMAGE_H #define IMAGE_H #include "Graphic.h" class Image : public Graphic { }; #endif Graphic.h: #ifndef GRAPHIC_H #define GRAPHIC_H #include "Image.h" class Graphic { }; #endif The following code compiles with no error: #include "Graphic.h" int main() { return 0; }
253,469
505,535
How do I display a tooltip for a CMFCRibbonButton in the status bar?
I have a CMFCRibbonStatusBar in my mainframe to which I add a CMFCRibbonButtonsGroup which again has a CMFCRibbonButton. This button has the same ID as a menu entry. Creating the button is done as follows: CMFCRibbonButtonsGroup* pBGroup = new CMFCRibbonButtonsGroup(); CMFCToolBarImages images; images.SetImageSize(CSi...
I don't think it's possible to show the tooltip without the mouse cursor being over the control. That's all done automatically. However if you want to have a nice looking tooltip like in your screenshot, you need to call SetToolTipText and SetDescription, like this: CMFCRibbonButton* pBtn = new CMFCRibbonButton(12345, ...
253,475
253,519
Why doesn't anyone upgrade their C compiler with advanced features?
struct elem { int i; char k; }; elem user; // compile error! struct elem user; // this is correct In the above piece of code we are getting an error for the first declaration. But this error doesn't occur with a C++ compiler. In C++ we don't need to use the keyword struct again and again. So why doesn't anyone upda...
Because it takes years for a new Standard to evolve. They are working on a new C++ Standard (C++0x), and also on a new C standard (C1x), but if you remember that it usually takes between 5 and 10 years for each iteration, i don't expect to see it before 2010 or so. Also, just like in any democracy, there are compromise...
253,720
253,750
Weird #include problem
I have a problem with a simple included file. The file being included is in two MFC programs - one of which is a dll, and it also compiles itself into a non-mfc dll. Recently I was using the larger dll which wraps around the source of the smaller dll when I wanted access to some of the features of the original code tha...
This doesn't have anything to do with the way you include files, it's a syntax error that you get because you didn't nest ( and ) correctly.
253,768
257,369
Porting C++ code from Windows to the Mac
I'm a long time Windows developer, and it looks like I'm going to be involved in porting a Windows app to the Mac. We've decided to use Flex/Air for the gui for both sides, which looks really slick BTW. My Windows application has a C++ DLL that controls network adapters (wired and wireless). This is written using the s...
Xcode is the IDE for Mac OS X, you can download the latest version by joining the Apple Developer Connection with a free Online membership. I don't believe there are any supported APIs for controlling wireless networking adaptors. The closest thing would be the System Configuration framework, but I don't know if it wi...
254,132
255,663
Automake : what are the valid values for *_la_LDFLAGS in Makefile.am?
I am wondering what are the possible value for *_la_LDFLAGS in Makefile.am ? If I ask this question, it is because I would like the following : Actual shared library : libA.so (or with the version number I don't care) Symbolic links : libA-X.Y.Z.so, libA-X.so, libA.so soname : libA-X.so However...
You should use the -version-info option of Libtool to specify the interface version of the library, but be sure to read how versioning works (or here for the official manual.) You can additionally play with -release to make the version number of your package more apparent, but I doubt you will ever get the exact namin...
254,229
254,361
Crossplatform Bidirectional IPC
I have a project that I thought was going to be relatively easy, but is turning out to be more of a pain that I had hoped. First, most of the code I'm interacting with is legacy code that I don't have control over, so I can't do big paradigm changes. Here's a simplified explanation of what I need to do: Say I have a ...
On Windows, you invoke CreatePipe first (similar to pipe(2)), then CreateProcess. The trick here is that CreateProcess has a parameter where you can pass stdin, stdout, stderr of the newly-created process. Notice that when you use stdio, you need to do fdopen to create the file object afterwards, which expects file num...
254,526
254,599
What does a GCC compiled static library contain?
My application links against libsamplerate.a. I am doing this to make distributing the final binary easier. I am worried that perhaps the code inside the .a file depends on some other libraries I also will need to distribute. But if it doesn't I am worried I am bloating up my application too much by including multiple ...
A static library is just a collection of object files. When you compile a program against a static library, the object code for the functions used by your program is copied from the library into your executable. Linking against a static library will not cause any functions outside that library to be included in your ...
254,673
254,713
Multiple Inheritance from two derived classes
I have an abstract base class which acts as an interface. I have two "sets" of derived classes, which implement half of the abstract class. ( one "set" defines the abstract virtual methods related to initialization, the other "set" defines those related to the actual "work". ) I then have derived classes which use mult...
It looks like you want to do virtual inheritance. Whether that turns out to actually be a good idea is another question, but here's how you do it: class AbsBase {...}; class AbsInit: public virtual AbsBase {...}; class AbsWork: public virtual AbsBase {...}; class NotAbsTotal: public AbsInit, public AbsWork {...}; Ba...
254,985
339,306
choosing a SOAP library to integrate with ISAPI webapp
The company I work for has a large webapp written in C++ as an ISAPI extension (not a filter). We're currently enhancing our system to integrate with several 3rd party tools that have SOAP interfaces. Rather than roll our own, I think it would probably be best if we used some SOAP library. Ideally, it would be free ...
GSoap is a great open source cross platfrom soap stack. It is FAST. Great interop. Many open source soap libraries don't have great interop with java/c#/python/whatever. It parses HUGE payloads while using very little memory. It is open source! Since you are using an IIS extension, you would need to add the gsoap to y...
255,068
259,598
Referencing existing SWIG wrappers when creating new ones
I have an existing library (JPhysX) that is a Java wrapper for a native C++ library (PhysX). The Java library makes use of types generated by SWIG, for example, com.jphysx.SWIGTYPE_p_NxStream, which represents a pointer to an NxStream object in the C++ code. Now I want to create my own C++ class that inherits from the ...
Making the wrapper class explicitly inherit from the desired type did the trick in this case: %typemap(javabase) UserStream "com.jphysx.SWIGTYPE_p_NxStream"; There were some methods in the wrapper class with which I had similar problems, but I simply removed them from the SWIG interface file because they aren't going ...