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,178,109 | 2,178,136 | Win32 exe not finding resources compiled in a .lib | I have a pretty plain Win32 application that links against a library I wrote that contains resources in an .rc file. The problem is that the .exe doesn't seem to find those resources. But if I move the .rc file from the library project to the .exe project resource loading works.
What step am I missing? I have the impr... | VC++ resources in a static library
|
2,178,171 | 2,178,272 | Unix program console vs something else | I am writing a program in unix. At the moment, it has a console interface. I am just curious like dll's in windows does a similar concept exist in unix when another program wants to call your program. I have been asked to simply provide a binary with little else in terms of details. I have a feeling that there might be... | The unix equivalent of a Windows dll is a shared library, e.g. libfoobar.so.
With regards to how to distribute your code to a third party in binary form your options are:
a static library: libfoobar.a
a shared / dynamic library: libfoobar.so
an executable
The first two cases are effectively the same. People tend to p... |
2,178,252 | 2,178,339 | Pimpl idiom: What size_type to use if implementation is unknown? | I have a class that holds an array of elements, and I want to give it a GetSize member function. But what return type should I give that function?
I'm using the pimpl idiom, and so in the header file it is not known what the implementation will use to store the elements. So I cannot just say std::vector<T>::size_type,... | If the client code can only see Foo (which is the purpose of pimpl idiom), then there's no use in define a specific size_type in the concrete implementation - it won't be visible/accessible to the client anyway. Standard containers can do that since they are built on so called "compile-time polymorphism", while you are... |
2,178,281 | 2,178,694 | small string optimization for vector? | I know several (all?) STL implementations implement a "small string" optimization where instead of storing the usual 3 pointers for begin, end and capacity a string will store the actual character data in the memory used for the pointers if sizeof(characters) <= sizeof(pointers). I am in a situation where I have lots o... | You can borrow the SmallVector implementation from LLVM. (header only, located in LLVM\include\llvm\ADT)
|
2,178,303 | 2,178,531 | C++ Read file from bottom to top | I have a very large file I need to parse, so reading it into memory all at once is non-ideal. The way the file is structured, it would be much, much easier if I could start at eof and go up to the beginning. Does anyone have a good trick for doing this? I'm using Visual Studio 2008 and C++. Thanks
| If your operating system supports it, consider using a memory mapped file. You can then treat the file contents as a very large array of bytes, with the operating system managing bringing the data into memory (and releasing it) as necessary.
|
2,178,316 | 2,179,873 | Private members in pimpl class? | Is there any reason for the implementation class as used in the pimpl idiom to have any private members at all? The only reason I can really think of is to protect yourself from yourself -- i.e. the private members serve to enforce some kind of contract between the class and the user, and in this case the class and the... | I think people are confusing the Pimpl idiom with Adapter/Bridge/Strategy patterns. Idioms are specific to a language. Patterns can apply to many languages.
The Pimpl idiom was devised to address the following problem in C++: Private members of a class are visible in the class declaration, which adds unnecessary #inclu... |
2,178,760 | 2,178,914 | Public new private constructor | When I try compiling the following:
#include <iostream>
class Test
{
public:
void* operator new (size_t num);
void operator delete (void* test);
~Test();
private:
Test();
};
Test::Test()
{
std::cout << "Constructing Test" << std::endl;
}
Test::~Test()
{
std::cout << "Destroying Test" << std::... | I think you have a misunderstanding on what the operator new does. It does not create objects, but rather allocates memory for the object. The compiler will call the constructor right after calling your operator new.
struct test {
void * operator new( std::size_t size );
};
int main()
{
test *p = new test;
// ... |
2,178,909 | 2,178,915 | How to initialize 3D array in C++ | How do you initialize a 3d array in C++
int min[1][1][1] = {100, { 100, {100}}}; //this is not the way
| The array in your question has only one element, so you only need one value to completely initialise it. You need three sets of braces, one for each dimension of the array.
int min[1][1][1] = {{{100}}};
A clearer example might be:
int arr[2][3][4] = { { {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4} },
... |
2,179,017 | 2,183,343 | Can i call multiple times JNI_CreateJavaVM? | I´m Trying to launch two threads witch calls "DispFrontEnd" function
First thread ended OK, second failed to start jvm.. ??
tks
#include "jni.h"
#include <process.h>
#include "Stdafx.h"
//DISPATCH Thread Check
bool DispatchThreadCreated = FALSE;
if (DispatchThreadCreated == FALSE)
{
HANDLE hDispThread;
hDispT... | Do you really have to start many JVM ? Could you use
jint AttachCurrentThread(JavaVM *vm, JNIEnv **p_env, void *thr_args);
instead ?
The only thing I know is a native thread cannot attach two different JVM at the same time.
|
2,179,065 | 2,179,248 | std::vector overwriting final value, rather than growing? | I'm having an issue where using vector.push_back(value) is overwriting the final value, rather than appending to the end. Why might this happen? I have a sample item in the vector, so it's size never hits zero. Below is the code..
void UpdateTable(vector<MyStruct> *Individuals, MyStruct entry)
{
MyStruct someEnt... | I'm going to hazard a guess:
Suppose MyStruct is declared like
struct MyStruct
{
const char *sourceAddress;
// Other Gubbins ...
};
And that ReceivedValue does something like
MyStruct ReceivedValue()
{
static char nameBuffer[MAX_NAME_LEN];
// Do some work to get the value, put the name in the buffer
... |
2,179,270 | 2,179,603 | Pass C# string to C++ and pass C++ result (string, char*.. whatever) to C# | I tried different things but i'm getting mad with Interop.
(here the word string is not referred to a variabile type but "a collection of char"):
I have an unmanaged C++ function, defined in a dll, that i'm trying to access from C#, this function has a string parameter and a string return value like this:
string myFunc... | What I've found to work best is to be more explicit about what's going on here. Having a string as return type is probably not recommended in this situation.
A common approach is to have the C++ side be passed the buffer and buffer size. If it's not big enough for what GetString has to put in it, the bufferSize variab... |
2,179,345 | 2,181,710 | Python method to boost function | I have a method exported to Python using boost python that takes a boost::function as an argument.
From what I have read boost::python should support boost::function without much fuss, but when I try to call the function with a python method it gives me this error
Boost.Python.ArgumentError: Python argument types in
... | Got an answer on the python mailing list, and after a bit of reworking and more research I got exactly what I wanted :)
I did see that post before mithrandi but I did not like the idea of having to declare the functions like that. With some fancy wrappers and a bit of python magic this can work and look good at the sa... |
2,179,426 | 2,179,811 | How to structure data for optimal speed in a CUDA app | I am attempting to write a simple particle system that leverages CUDA to do the updating of the particle positions. Right now I am defining a particle has an object with a position defined with three float values, and a velocity also defined with three float values. When updating the particles, I am adding a constant... | It's common in data parallel programming to talk about "Struct of Arrays" (SOA) versus "Array of Structs" (AOS), where the first of your two examples is AOS and the second is SOA. Many parallel programming paradigms, in particular SIMD-style paradigms, will prefer SOA.
In GPU programming, the reason that SOA is typical... |
2,179,477 | 2,179,588 | Best way to parse HTML in Qt? | How would I go about parsing all of the "a" html tags "href" properties on a page full of BAD html, in Qt?
| I would use the builtin QtWebKit. Don't know how it does in terms of performance, but I think it should catch all "bad" HTML.
Something like:
class MyPageLoader : public QObject
{
Q_OBJECT
public:
MyPageLoader();
void loadPage(const QUrl&);
public slots:
void replyFinished(bool);
private:
QWebView* m_view;... |
2,179,506 | 2,179,535 | LoadString, static library and executables | My project is set up so all the framework code and modules are compiled to a static .lib (let's call it framework.lib), and many test projects use framework.lib and compile to executable files.
For error handling, I'm trying to put the resource strings in framework.rc (part of the framework.lib project) and load the ... | Static libraries are just concatenations of .OBJ files - they don't have features like resources. To do this you need to put the resources in DLL.
|
2,179,543 | 2,179,742 | C++ standard/de facto STL algorithm wrappers | Are there any standard/de facto standard (boost) wrappers around standard algorithms which work with containers defining begin and end. Let me show you what I mean with the code:
// instead of specifying begin and end
std::copy(vector.begin(), vector.end(), output);
// write as
xxx::copy(vector, output);
I know it can... | There is an extension to the Boost Range library called RangeEx which contains range wrappers for all stl algorithms, plus some new ones.
It has recently been accepted into Boost and so it's not yet in the current "official" release (1.41). Until this changes, you can download the latest version from the Boost Vault.
... |
2,179,623 | 2,180,056 | How does QDebug() << stuff; add a newline automatically? | I'm trying to implement my own qDebug() style debug-output stream, this is basically what I have so far:
struct debug
{
#if defined(DEBUG)
template<typename T>
std::ostream& operator<<(T const& a) const
{
std::cout << a;
return std::cout;
}
#else
template<typename T>
debug const&... | Qt uses a method similar to @Evan. See a version of qdebug.h for the implementation details, but they stream everything to an underlying text stream, and then flush the stream and an end-line on destruction of the temporary QDebug object returned by qDebug().
|
2,179,624 | 2,179,803 | Can I force a parent window to redraw without causing its children to redraw? | Is it possible to invalidate a window without invalidating its children? (display invalidation to cause a repaint of the parent window, but not redraw its children)
This assumes that the parent window already has the "clipchildren" style, so that its painting wouldn't inherently invalidate the children.
| InvalidateRect() already does this. Another way is RedrawWindow() with the RDW_NOCHILDREN option.
|
2,179,724 | 2,179,840 | Why can't I index a std::vector in the immediate window? | So, I have a vector
std::vector<std::string> lines.
I fill this vector up, and can access it like
std::string temp = lines[0];
However, in the immediate window, both
lines[0] - error:overloaded operator not found
and
lines.at(0) - error:symbol is ambiguous
don't work at all. Is there a trick to using the imm... | The immediate and watch windows don't support overloaded operators. There is some support in there for printing standard containers as a whole in a sensible fashion (see, e.g., http://www.virtualdub.org/blog/pivot/entry.php?id=120), but this doesn't extend to being able to use operator[] on them.
Hopefully this will be... |
2,179,946 | 2,179,985 | I would like to see a hash_map example in C++ | I don't know how to use the hash function in C++, but I know that we can use hash_map. Does g++ support that by simply including #include <hash_map>? What is a simple example using hash_map?
| The current C++ standard does not have hash maps, but the coming C++0x standard does, and these are already supported by g++ in the shape of "unordered maps":
#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;
int main() {
unordered_map <string, int> m;
m["foo"] = 42;
cou... |
2,179,999 | 2,180,304 | C++ Adobe source libraries impressions? | I just stumbled upon Adobe source libraries, ASL. It is set of templates and functions similar to boost, under MIT license.
Some of the utilities in the library I found quite useful and now I consider using it.
the library seems pretty straightforward, however.
Have you used ASL yourself? if so, what were your impress... |
ASL uses Boost heavily, so it's not such similar to Boost, as (in some cases) a relatively thin wrapper around Boost.
The "big" pieces of ASL are Adam and Eve. Most of the rest appears to be (and if memory serves, really is) little more than support for those.
ASL hasn't been updated in a while, and if I'm not mistake... |
2,180,161 | 2,180,814 | Can anyone explain event handling in C++ please? | I should mention that i am using Mac OS X, XCode.
When a buffer has finished writing to file, it generates an event to tell the gui to read the data off the file.
I am not sure what kind of event would i need in this case? Is it possible to do it without using event?
Thank you.
| Event handling in C++ primarily consists of exceptions and signals. The exact details of how these are handled is best described in the specification or one of Stroustrup's books.
Other event handling, such as mouse clicks, interrupts, and semaphores, is handled by the OS. Different OSes have different API and set ... |
2,180,368 | 2,180,477 | State machine implementation | I have a state machine as described below.
We can start in one of two starting states, but we must hit all 4 states of the handshake. From there, we can either transfer a payload of data or receive a payload of data. Then, we return to our original starting state.
Handshake:
-> StartingState1 -> FinalState1 -> Starting... | What you have doesn't represent the possible states of your system completely, but it's easy to transform it so that it does. You need additional states to represent the difference between being in state 1 and not having been in state 2, and being in state 1, whilst having been in state 2 (and the same for state 2). So... |
2,180,501 | 2,180,769 | In C++, are static initializations of primitive types to constant values thread-safe? | i.e., would the following be expected to execute correctly even in a multithreaded environment?
int dostuff(void) {
static int somevalue = 12345;
return somevalue;
}
Or is it possible for multiple threads to call this, and one call to return whatever garbage was at &somevalue before execution began?
| From the C++ Standard, section 6.7:
A local object of POD type (3.9) with static storage duration
initialized with constant-expressions
is initialized before its block is
first entered.
This means that a function-level static object must be initialised by the first time the function is entered, not necessarily ... |
2,180,527 | 2,180,545 | sort() function in C++ | I found two forms of sort() in C++:
1) sort(begin, end);
2) XXX.sort();
One can be used directly without an object, and one is working with an object.
Is that all? What's the differences between these two sort()? They are from the same library or not? Is the second a method of XXX?
Can I use it like this
vector<int> m... | std::sort is a function template that works with any pair of random-access iterators. Consequently, the algorithm implemented by std::sort is tailored (optimized) for random access. Most of the time it is going to be some flavor of quick-sort.
std::list::sort is a dedicated list-oriented version of sort. std::list is a... |
2,180,561 | 2,180,583 | Visual Studio resource editor: there can only be one string table? | I created a string table in my .rc file containing my English strings - now I need to add another string table for a different language.
If I try to do:
Add Resource... -> String Table -> New
I get the error: "there cannot be more than one instance of this type".
I know I can open up the .rc file in notepad and ad... | Yes, it is very well hidden. Double-click the .rc file in Solution Explorer to open the Resource View window. Expand the String Table node, right-click "String Table" and select "Insert Copy". That takes you to the language selection combo.
|
2,180,698 | 2,180,751 | How do I create a non managed Windows GUI in Visual C++? | When I create a 'Windows Forms Application', the resultant program is a managed one. Creating a 'Win32 Application' results in a native one, but when I try to add a form I'm informed that the project will be converted to CLI if I continue. How do I design a native Windows GUI with Visual C++ 2008 Express Edition? I'm p... | As Reed Copsey, MFC would be the "default" way of creating a native unmanaged GUI on the Windows platform. However, MFC is not included with Visual Studio Express. Consequently, you would either need to upgrade to the full version or you could look into using a freely available C++ GUI library such as wxWidgets.
There ... |
2,180,755 | 2,180,782 | C++ GUI Tutorial: undefined reference to TextOut | So after a bit of searching for Win32 GUI tutorials (I decided a tutorial on making GUIs might make me more active in making C++ applications and therefore stronger at programming in C++ in general,) I came across a rohitab tutorial. There are two parts that I have been able to find. Part 1 worked fine, and I'm now wor... | Did you link your app against GDI32.LIB?
|
2,180,909 | 2,185,061 | How to use ALSA's snd_pcm_writei()? | Can someone explain how snd_pcm_writei
snd_pcm_sframes_t snd_pcm_writei(snd_pcm_t *pcm, const void *buffer,
snd_pcm_uframes_t size)
works?
I have used it like so:
for (int i = 0; i < 1; i++) {
f = snd_pcm_writei(handle, buffer, frames);
...
}
Full source code at http://pastebin... | frames should be the number of frames (samples) you want to write from the buffer. Your system's sound driver will start transferring those samples to the sound card right away, and they will be played at a constant rate.
The latency is introduced in several places. There's latency from the data buffered by the driver ... |
2,181,025 | 2,181,810 | Draw World Map [WGS84] with OpenGL in a wide Range | I want to draw a Map, consisting of 256x256 pixle Tiles (a lot of them). These cover a big area.
The transformation to convert lat|lon(from the globe) to x|y (map) spawns quite big values.
With these big values goes accurcy and so, if I go far away from the 0/0 Point, I get inaccuracies of multiple pixels between textu... | Actually, I have recently run into the exact same problem in my implementation of rendering entire planets from space to ground. In fact, what you have to do is create a new position structure that splits the accuracy between different floats. For example,
struct location
{
vec3 metre;
vec3 megametre;
ve... |
2,181,028 | 2,181,129 | C++ Seg fault on reference to stored base class pointer | I'm getting some nasty segmentation faults through the g++ compiler on the following code. Any ideas on why this would happen and how to fix it would be great.
#include <iostream>
using namespace std;
class Base {
public:
Base() {}
virtual ~Base() {};
virtual int getNum(int) = 0;
};
class Derived: public Base {... | void init() {
Derived n;
*baseId = n;
}
Apart from what Neil noted, derived n is local to your init function. It "dies" when you exit the function, so even if you assigned it correctly, it won't work.
What you want is not assigning on the stack but on the heap:
void init() {
baseId = new Derived();
... |
2,181,135 | 2,181,198 | Finite State Machine : Bad design? | Are Finite State Machines generally considered as bad design in OOP ?
I hear that a lot. And, after I had to work on a really old, undocumented piece of C++ making use of it, I tend to agree. It was a pain to debug.
what about readability/maintainability concerns?
| FSMs should never be considered bad. They are far too useful, but people whom aren't accustomed to them will often consider them burdensome.
There are numerous ways to implement one with OOP. Some are uglier than others. Your low-level guys will use switch statements, jump tables or even "goto."
If you're looking for a... |
2,181,205 | 2,181,226 | utf-8 to/from utf-16 problem | I based these two conversion functions and an answer on StackOverflow, but converting back-and-forth doesn't work:
std::wstring MultiByteToWideString(const char* szSrc)
{
unsigned int iSizeOfStr = MultiByteToWideChar(CP_ACP, 0, szSrc, -1, NULL, 0);
wchar_t* wszTgt = new wchar_t[iSizeOfStr];
if(!wszTgt) a... | Check the docs for WideCharToMultiByte(). CP_ACP converts using the current system code page. That's a very lossy one. You want CP_UTF8.
|
2,181,474 | 2,181,510 | How to use Redis within a C++ program? | What would be the best way to use a Redis DB within a C++ program?
| Using a C bindings library? There doesn't seem to be a C++ wrapper available anywhere.
|
2,181,594 | 2,181,761 | Select mutex or dummy mutex at runtime | I have a class that is shared between several projects, some uses of it are single-threaded and some are multi-threaded. The single-threaded users don't want the overhead of mutex locking, and the multi-threaded users don't want to do their own locking and want to be able to optionally run in "single-threaded mode." ... | How about something like this?
Its untested but should be close to OK.
You might consider making the template class hold a value rather than a pointer
if your mutexes support the right kinds of constructions. Otherwise you could specialise the MyMutex class to get value behaviour.
Also it's not being careful about copy... |
2,181,600 | 2,181,645 | Need basic help parsing a string in C++ | C++ is not my preferred language.
I have a file that contains this:
e 225,370 35,75
I want to separate e, 225, 370, 35 and 75 from each other into a char and ints but I'm having trouble. I tried doing everything I found online and in my C++ book and still it's not working out. Please help.
I would have an easier tim... | #include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream f("a.txt"); // check for errors.
char ch,dummy;
int i1,i2,i3,i4;
f>>ch>>i1>>dummy>>i2>>i3>>dummy>>i4;
cout<<ch<<endl<<i1<<endl<<i2<<endl<<i3<<endl<<i4<<endl;
return 0;
}
|
2,181,659 | 2,181,678 | Help understanding multidimensional array and pointer notation in c++ | I understand the basic idea that when an array is the sole operand of the & or sizeof() operator, it decays to a pointer to the first element in the array. I'm unsure how these notations work though. In our text, there is the 1-D case, vs the 3-D case for an array. The first example is the function declaration for a... | The parameter still decays to a pointer. The important part is that DIM1 and DIM2 specify the size of all but one dimension. So, if we have:
double average (double set[][DIM1][DIM2] myset)
myset[0][0] is DIM2 * sizeof(double) before myset[0][1]. Together, the two dimensions say that myset[0] is DIM1 * DIM2 * sizeof... |
2,181,742 | 2,181,757 | Identical Class Member Names and Function Argument Names in C++ | I have a simple object that holds some [public] data.
I want to keep my interface clean, so I don't want to pre-/post- fix anything to the names of the publically accessible variables nor to the names of my function arguments.
That said, I ended up doing something like this:
template<typename T> struct Foo
{
explicit... | Yes, that's fine, and perfectly standard.
Local variables always come first in a name lookup, but the x(...) in an initialization list can obviously only refer to member variables [edit:or a base class].
If you didn't use the initialization list, you would have to write:
explicit Foo(T x)
{
this->x = x;
}
|
2,181,920 | 2,232,375 | Qt::What needs to be included in the configuration to use dbus? | I'm using stripped down as much as possible configuration of Qt but now I need to use the dbus and can't figure out what I need to include to be able to use it? There doesnt seem to be anything obvious to me using the qconfig tool. The errors I get at the moment when making are:
qdbus_symbols.cpp:53: error: expected in... | QT += dbus
should be enough to include the dbus option in the .pro project file, ins't it?
I need more info to give apropriate answer.
|
2,181,933 | 2,181,941 | Is there a way to find the cardinality (size) of an enum in C++? | Could one write a function that returns the number of elements in an enum? For example, say I have defined:
enum E {x, y, z};
Then f(E) would return 3.
| Nope.
If there were, you wouldn't see so much code like this:
enum E {
VALUE_BLAH,
VALUE_OTHERBLAH,
...
VALUE_FINALBLAH,
VALUE_COUNT
}
Note that this code is also a hint for a (nasty) solution -- if you add a final "guard" element, and don't explicitly state the values of the enum fields, then the last "COUN... |
2,181,955 | 2,181,999 | Center an OpenGL window with GLUT | I have an openGL window that is 640x480 that I need to center in the middle of the screen. I previously used:
glutInitWindowPosition((GetSystemMetrics(SM_CXSCREEN)-640)/2,
(GetSystemMetrics(SM_CYSCREEN)-480)/2);
which WORKED.
But now all of a sudden when I compile...
Linking...
1>Project1.obj :... | Also, instead of linking user32.lib you can do it solely using glut:
glutGet(GLUT_SCREEN_WIDTH) // returns Screen width
and
glutGet(GLUT_SCREEN_HEIGHT) // returns Screen height
Why depend on Windows when you can be cross-platform?
Hence, your code would look:
glutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH)-640)/2... |
2,182,235 | 2,189,582 | OUTDATED - Error modes for OpenCV | I am using OpenCV 1 to do some image processing, and am confused about the cvSetErrMode function (which is part of CxCore).
OpenCV has three error modes.
Leaf: The program is terminated after the error handler is called.
Parent: The program is not terminated, but the error handler is called.
Silent: Similar to Pa... | I am going to answer my own question, because after some fiddling around I have worked out what happens.
When you switch to 'parent' mode instead of leaf mode, there is an error handler that gets called cvGuiBoxReport(). cvGuiBoxReport() is the default error handler. It seems that even in parent mode, cvGuiBoxReport() ... |
2,182,408 | 2,182,451 | Return a const reference or a copy in a getter function? | What's better as default, to return a copy (1) or a reference (2) from a getter function?
class foo {
public:
std::string str () { // (1)
return str_;
}
const std::string& str () { // (2)
return str_;
}
private:
std::string str_;
};
I know 2) could be faster but don't have to due ... | Well it really depends on what you expect the behaviour to be, by default.
Do you expect the caller to see changes made to str_ unbeknownst(what a word!) to them? Then you need to pass back a reference. Might be good if you can have a refcounted data member and return that.
If you expect the caller to get a copy, do 1)... |
2,182,454 | 2,182,473 | Why does this code using `::boost::bind` get a compiler error? | This code:
#include <boost/signals.hpp>
#include <boost/bind.hpp>
#include <boost/mem_fn.hpp>
#include <iostream>
class Recorder : public ::boost::signals::trackable {
public:
void signalled() {
const void *me = this;
::std::cerr << "Recorder at " << me << " signalled!\n";
}
};
void signalled()
{
... | sig.connect(::boost::bind(&Recorder::signalled, &r, _1));
What is the _1 placeholder left for here? It's unneeded, connect expects void -> void function. If you'll remove the needless placeholder, the code will compile.
You provide &Recorder::signalled -- a member function of type void Recorder::(void), correctly bind... |
2,182,598 | 2,182,667 | Static function access in other files | Is there any chance that a function defined with static can be accessed outside the file scope?
| It depends upon what you mean by "access". Of course, the function cannot be called by name in any other file since it's static in a different file, but you have have a function pointer to it.
$ cat f1.c
/* static */
static int number(void)
{
return 42;
}
/* "global" pointer */
int (*pf)(void);
void initialize(v... |
2,182,784 | 2,182,901 | Length of a BYTE array in C++ | I have a program in C++ that has a BYTE array that stores some values. I need to find the length of that array i.e. number of bytes in that array. Please help me in this regard.
This is the code:
BYTE *res;
res = (BYTE *)realloc(res, (byte_len(res)+2));
byte_len is a fictitious function that returns the length of the ... | Given your code:
BYTE *res;
res = (BYTE *)realloc(res, (byte_len(res)+2));
res is a pointer to type BYTE. The fact that it points to a contiguous sequence of n BYTES is due to the fact that you did so. The information about the length is not a part of the pointer. In other words, res points to only one BYTE, and if... |
2,183,067 | 2,185,691 | boost::Spirit Grammar for unsorted schema | I have a section of a schema for a model that I need to parse. Lets say it looks like the following.
{
type = "Standard";
hostname="x.y.z";
port="123";
}
The properties are:
The elements may appear unordered.
All elements that are part of the schema must appear, and no other.
All of the elements' synthesised at... | According to the Spirit forums, the following is the answer.
You might want to have a look at the
permutation parser:
a ^ b ^ c
Which matches a or b or c (or a
combination thereof) in any sequence.
If the objective is to parse into a struct, than the best way to test weather all essential members have been ini... |
2,183,087 | 2,183,106 | Why can't I use float value as a template parameter? | When I try to use float as a template parameter, the compiler cries for this code, while int works fine.
Is it because I cannot use float as a template parameter?
#include<iostream>
using namespace std;
template <class T, T defaultValue>
class GenericClass
{
private:
T value;
public:
GenericClass()
{
... | The current C++ standard does not allow float (i.e. real number) or character string literals to be used as template non-type parameters. You can of course use the float and char * types as normal arguments.
Perhaps the author is using a compiler that doesn't follow the current standard?
|
2,183,113 | 2,184,971 | using catch(...) (ellipsis) for post-mortem analysis | Someone in a different question suggested using catch(...) to capture all otherwise unhandled - unexpected/unforseen exceptions by surrounding the whole main() with the try{}catch(...){} block.
It sounds like an interesting idea that could save a lot of time debugging the program and leave at least a hint of what happe... | Yes it is a good idea.
If you let an exception escape main it is implementation defined weather the stack is unwound before the application is shut down. So in my opinion it is essential you catch all exceptions in main.
The question then becomes what to do with them.
Some OS (See MS and SE) provide some extra debuggin... |
2,183,119 | 2,183,156 | Should I use XML or Binary to send data from server to client? | I have two separate apps - one a client (in C#), one a server (in C++). They need to exchange data in the form of "structs" and ~ about 1 MB of data a minute is sent from server to client.
Whats better to use - XML or my own Binary format?
With XML:
Translating XML to a struct using a parser would be slow I believe? (... | 1MB of data per minute is pretty tiny if you've got a reasonable network connection.
There are other choices between binary and XML - other human-readable text serialization formats, such as JSON.
When it comes to binary, you don't have to have versioning problems - technologies like Protocol Buffers (I'm biased: I wor... |
2,183,129 | 2,183,337 | C# and C++ Synchronize between processes | We have 2 applications. One written in C# and the other in C++. We need to maintain a counter (in memory) shared between these processes. Every time one of these applications start, it needs to check for this counter and increase it and every time the application shut-down it needs to decrease the counter. If the appli... | You might get away with named semaphore. Semaphore is basically a count, it is here to allow developers limit the number of thread/processes that are accessing some resource. Usually it works like that
You create a semaphore with maximum count N.
N threads call waiting function on it, WaitForSingleObject or similar an... |
2,183,145 | 2,183,183 | Best C++ library to interact with ICQ? | I have a Qt-based windows application written in C++ that needs to report it's status via ICQ and react on some ICQ messages. Maybe anyone know a good library to interact with ICQ? I need to connect ICQ with registered login and password, send messages to specified contacts and receive messages from them.
| I know of two streamline options:
libpurple - The core library behind Pidgin
Telepathy - The core behind Empathy
|
2,183,505 | 2,183,609 | ways to improve the launch speed of C++ application | Recently, my boss asked me to improve the launch speed of our application, the AP was written with C++.
The AP is a little big, it used 200+ dll, Windows needs long time to enter the main() function. I tried these two ways, but still can't make our boss happy.
delay load dll http://msdn.microsoft.com/en-us/library/yx9... | You need to profile your application in order to determine the true cause of the slowdown. For example, it could be that you are spending most of the time in some initialization routine of one the .dll's you are loading. Go find yourself a good profiling tool and then determine where the bottleneck is.
|
2,183,557 | 2,183,593 | SMTP email on Windows using C++ | Is there any Windows Native API to send SMTP based message using C++
| There is not a native API. You will need a 3rd party component or to build this yourself.
Useful information in this thread:
https://stackoverflow.com/questions/58210/c-smtp-example
|
2,183,649 | 2,183,699 | what is invalidate,update methods do in VC++ | i have small doubt regarding the window functions in c++.
what exactly "invalidate()" function do?
what message does it sends?when we need to call this? also what is "update()" function?
is "invalidaterect()" works similar to "invalidate()" function?.
Thanks
| CWnd::Invalidate() invalidates the entire client area of a window, which indicates that the area is out of date, and should be repainted. You would typically call this on a control that needs to be redrawn. CWnd::InvalidateRect() invalidates only part of the window.
With the Invalidate functions, the WM_PAINT message w... |
2,183,650 | 2,183,797 | C# shared memory between C++ application and C# application using COM object | Is it OK/possible to have a shared memory in a COM object which will be consumed by applications built using C# and/or C++?
Can C# access shared memory in COM object without crash?
Thanks,
Adi Barda
| I don't really see what role the COM object plays in this. But, no, there isn't anything that makes MMFs fundamentally incompatible with managed code. They are merely very awkward to use since you need pointers to access them.
Support for MMFs is coming in .NET 4.0. It is probably too soon to use that in production ... |
2,183,712 | 2,183,739 | A little problem in handling 2-D arrays with class | class linklist4x4
{
private:
struct node4x4
{
double data[4][4];
node4x4 *link;
}*p;
public:
linklist4x4();
void append( double* num );
void add_as_first( double* num );
void addafter( int c, double* num );
//void del( double* num );
void display();
in... | You have defined the method append to take a 1-D array of type double. But in the function you are making use of it as a 2-D array.
The data in each of your link list node is a 2-D array of double.
So your all your member functions should accept a 2-D array of double as argument.
Change:
void append( double* num );
voi... |
2,183,961 | 2,184,244 | Is creating a base class for all applications of a particular type good design? | I am trying to write a graphics application in C++. It currently uses OGRE for display, but I'd like it to work with Irrlicht or any other engine, even a custom rendering engine which supports my needs. This is a rather long question, so I'd appreciate help on re-tagging/ cleanup (if necessary). I'll start with a littl... | You are mixing two unrelated functions in one class here. First, it serves as a syntactic shortcut for declaring and initializing StateManager and InputSystem members. Second, it declares abstract create_window function.
If you think there should be a common interface - write an interface (pure abstract class).
Additio... |
2,184,123 | 2,184,257 | Detect removable drive (e.g. USB flash drive) C/C++ | How can I detect when a removable disk drive is (dis)connected to the system? How to get the mount path (for Linux) and the drive letter (for windows)?
EDIT: Is there a way to detect the currently connected devices?
| For Windows, the API RegisterDeviceNotification will let you know when a USB device is added. The information about the volume is given in the DEV_BROADCAST_VOLUME structure. The dbcv_unitmask gives the drive letter.
|
2,184,125 | 2,184,140 | Getting input from user using cin | I am using Turbo C++ 3.0 Compiler
While using the following code ..
char *Name;
cin >> Name;
cout << Name;
When I gave input with space ... its only saving characters typed before space ..
like if I gave input "QWERT YUIOP" ... Name will contain "QWERT";
Any explaination why ??
| You need to allocate space for the char array into which you want to read the Name. char *Name; will not work as it only declares a char pointer not a char array. Something like char Name[30];
Also the cin << only allows us to enter one word into a string (char name[30]).
However, there is a cin function that ... |
2,184,276 | 2,184,723 | Modifying items of boost multi index container | struct tagEnumdef{}; struct tagName{}; struct tagWidget{};
template< class type > class ParamTags;
template<> class ParamTags<int> { public: typedef tagEnumdef tag; };
template<> class ParamTags<QString> { public: typedef tagName tag; };
template<> class ParamTags<QWidget*>{ public: typedef tagWidget tag; };
t... | It is my understanding that modify() should be called on an index, not on a container. So what you want to write is probably more like:
typedef typename ParamTags<T>::tag TagType;
// Get the proper index
ParamRegisterIndexContainer::index<TagType>::type& index = register_->get<TagType>();
// Modify a value found in t... |
2,184,421 | 2,184,431 | Problem compiling simple C++ progam | I was provided this simple C++ [I think] program to investigate the maximum size of int that can be stored:
#include <limits.h>
#include <iostream>
void main ( int argc , char * argv[])
{
cout << "INT_MAX " << INT_MAX << endl ;
cout << "INT_MAX +1 = " << INT_MAX + 1 << endl ;
cout << "INT_MAX -1 = " <<... | You are compiling C++ code with gcc in a file with .c extension?
// Use new C++ header files instead of their .h version.
#include <climits>
#include <iostream>
// cout and endl are declared in the std namespace.
using namespace std;
int main (int argc, char * argv[])
{
cout << "INT_MAX " << INT_MAX << e... |
2,184,656 | 2,184,756 | Making wide application (with plugins) | I'm going to make my application extensible.
Where I can read information about writing programs which support plugins?
C++
| A plug-in architecture is what you need to look-up and read about. A SO answer will not help beyond providing a few stray links. I'll try to explain as briefly as I can: Typically, plug-ins are a set of dynamic libraries that the host application loads (usually at start up, sometimes delay loaded for efficiency purpose... |
2,184,702 | 2,184,727 | How to generate a good random seed to pass to srand()? | I am writing a C++ program which needs to create a temporary file for its internal usage. I would like to allow concurrent executions of the program by running multiple processes, so the temporary file name needs to be randomized, that way each spawned process will generate a unique temporary file name for its own use.... | The question is actually asking how to create a uniquely-named temporary file.
The operating system probably provides an API for this, which means you do not have to generate your own name.
On Windows, its called GetTempFileName() and GetTempPath().
On Unix, use tmpfile().
(Windows supports tmpfile() too; however, I've... |
2,184,932 | 2,847,043 | Opaque object for template in another namespace | I know how to do an opaque object in C++ as following:
// my_class.hpp
class opaque_object;
class my_class {
my_class();
~my_class();
opaque_object *m_opaque_object;
};
// my_class.cpp
#include <my_class.hpp>
class opaque_object {
// ...
};
my_class::my_class() { m_opaque_object = new opaque_object(); ... | Need to declare each templated class as well as each class needed as for template (template argument) with the right namespace.
|
2,185,443 | 2,185,470 | Does C++ support constant arrays of type string? | I'm a programming student in my first C++ class, and for a recent project I did, I was unable to create an array of strings like I could do in C#:
string MONTHS[ARRAY_CAPACITY] = { "Jan", "Feb", "Mar", "April", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec" };
// this yields many compiler errors in C++
Is it... | If you initialise the array in C++ then it doesn't require a size to be set (although it'll accept one), so:
std::string months[] = { "Jan", "Feb", "Mar", "April", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec" };
compiles fine with g++ for me and I'd expect it to compile elsewhere too. I expect your errors... |
2,185,495 | 2,185,529 | use of char * vs std::string in different environments | I have been using std::string in my code. I was going to make a std::string and pass it by reference. However, someone suggested using a char * instead. Something about std::string is not reliable when porting code. Is that true? I have avoided using char * as I would need to do some memory management for it. Instead I... | In C++, almost every string should be std::string unless another library requires a cstring, in which case you should still be using an std::string and passing string.c_str(), unless you're using functions that work with buffers.
However, if you're writing a library and exporting functions, it's better to use const cha... |
2,185,583 | 2,185,992 | How to guard against memory leaks? | I was recently interviewing for a C++ position, and I was asked how I guard against creating memory leaks. I know I didn't give a satisfactory answer to that question, so I'm throwing it to you guys. What are the best ways to guard against memory leaks?
Thanks!
| What all the answers given so far boil down to is this: avoid having to call delete.
Any time the programmer has to call delete, you have a potential memory leak.
Instead, make the delete call happen automatically. C++ guarantees that local objects have their destructors called when they go out of scope. Use that guar... |
2,185,829 | 2,186,451 | Maven learning curve & overhead for small/medium projects? | what would be (rough estimation, average, of course) the initial learning and setup curve and subsequent overhead for using Maven for C++/Eclipse/Linux project of small to medium size?
We are 4 developers at the beginning of the way. We currently have ~20 native eclipse C++ (CDT) "projects", which we compile interactiv... | First, while Maven has some support to build C++ projects with the maven-native-plugin or, if you already are using Make, with the maven-make-plugin from the c-builds suite, this is not a common use case and there aren't widely used. So while it should be possible, you won't get support and find resources easily (just ... |
2,185,953 | 2,186,393 | machine precision and max and min value of a double-precision type | (1) I have met several cases where epsilon is added to a non-negative variable to guarantee nonzero value. So I wonder why not add the minimum value that the data type can represent instead of epsilon? What are the difference problems that these two can solve?
(2) Also I notice that the inverse of the maximum value of ... | You need to understand how floating point numbers are represented in the CPU. In the data type, 1 bit is reserved for the sign, i.e. whether it is a positive or negative number, (yes you can have positive and negative 0 in floating point numbers,) then a number of bits is reserved for the significand (or mantissa,) the... |
2,185,954 | 2,186,059 | Implications of template declaration & definition | From what I understand template classes and template functions (for the most part) must be declared and defined in the same header file. With that said:
Are there any other ways to achieve separate compilation of template files other than using particular compilers? If yes, what are those?
What, if any, are the drawba... | How To Organize Template Source Code
Basically, you have the following options:
Make the template definition visible to compiler in the point of instantiation.
Instantiate the types you need explicitly in a separate compile unit, so that linker can find it.
Use keyword export (if available)
|
2,185,960 | 2,188,368 | Particle stream should be the same length regardless of emitter speed | I'm writing a particle system for our student game, and I've run into a bit of a snag. I want to improve the effect on the ships' rockets, but I can't seem to figure out how.
Here's how the effect looks on a stationary ship:
And here's how it looks on a moving ship:
I want the flames to be the same length consistentl... | You're making the particles move faster or slower according to the parent ship's speed, but their lifetime is some constant that you decrement by one until you reach zero, correct?
What you probably want to do is set the lifetime to a distance value, rather than some number of ticks. Then, subtract the ship's speed (or... |
2,186,122 | 2,188,033 | Using enum with string variables | I'm trying to do something like this,
enum Data_Property
{
NAME,
DATETIME,
TYPE,
};
struct Item_properties
{
char* Name;
char* DateTime;
int Type;
};
int main() {
std::string data = "/Name Item_Name /DATETIME [TimeStamp] /TYPE [Integer value]";
std::list <std::string> known_properties;
known_properties.... | First, let me say that there is always another alternative, one of my philosophies.
Let's look at the Big Picture. You are trying read an Item from string. The Item is a container of datums. In Object Oriented terms, the Item would like each datum to load its own data from a string. The Item doesn't need to know ... |
2,186,150 | 2,192,336 | Objective C in C++ – Out of Scope | I have a little problem with the WOsclib. Not particularly with the library, it's more the callback function. The listen to specific osc commands i have to put up some callback method like
void TheOscStartMethod::Method(
const WOscMessage *message,
const WOscTimeTag& ... | The Solution:
I don't know if this is the best way to do it, but it works.
There must be an empty c object, which later will become our objective c object that holds all the stuff we want to access.
static gsSearchForIp* delegate = NULL;
We must define a function to set the objective c object
void setCallbackDelegate(... |
2,186,197 | 2,186,265 | Static library API question (std::string vs. char*) | I have not worked with static libraries before, but now I need to.
Scenario:
I am writing a console app in Unix. I freely use std::string everywhere because it's easy to do so. However, I recently found out that I have to support it in Windows and a third party application would need API's to my code (I will not be sha... | Yep. Use std::string internally and then just use const char * on the interface functions (which will be converted to std::strings on input.
|
2,186,301 | 2,186,339 | inverse distance weighting interpolation | I would like to compute a weight as reciprocal of a distance for something like inverse distance weighting interpolation.
double wgt = 0, wgt_tmp, result = 0;
for (int i = 0; i < num; i++) {
wgt_tmp = 1.0/dist[i];
wgt += wgt_tmp;
result += wgt_tmp * values[i];
}
results /= wgt;
However the distance can be 0 a... | I don't see any way besides piecewise - you need a different function than reciprocal distance for small distances. The simplest thing would be to just chop off the top:
modified_dist[i] = dist[i] < MIN_DIST ? MIN_DIST : dist[i]
but you could replace that with something still decreasing if you want, like (MIN_DIST + d... |
2,186,438 | 2,215,574 | Read() from file descriptor hangs | Hey, hopefully this should be my last PTY-related question and I can move onto more exciting issues. (c;
Here's a set of small functions I have written for creating and reading/writing to a pty: http://pastebin.com/m4fcee34d The only problem is that they don't work! After I run the initializer and writeToPty( "ls -l"... | I'm note entirely familiar with posix, but after reading this page http://pwet.fr/man/linux/fonctions_bibliotheques/posix/read I had some insight. What's more, I don't see you adjusting your M_nBytes value if you haven't read as much as you were expecting on the first pass of the loop.
edit: from that link, perhaps thi... |
2,186,788 | 2,187,054 | Is there an open-source c/c++ implementation of IEEE-754 operations? | I am looking for a reference implementation of IEEE-754 operations. Is there such a thing?
| I believe the C libraries SoftFloat and fdlibm are suitable for what you are looking for. Others include Linux (GNU libc, glibc) or *BSD libc's math functions. Finally, CRlibm should also be of interest to you.
Ulrich Drepper has a interesting look at different math libraries, that might be also worth reading through.
|
2,186,825 | 2,187,020 | C/C++: How to store data in a file in B tree | It appears to me that one way of storing data in a B-tree as a file can be done efficiently with C using binary file with a sequence (array) of structs, with each struct representing a node. One can thus connect the individual nodes with approach that will be similar to creating linked lists using arrays. But then the ... | I did a very quick search and dug up this: http://people.csail.mit.edu/jaffer/WB C source: http://cvs.savannah.gnu.org/viewvc/wb/wb/c/ - it seems to offer disk-based B-tree style databases - although taking a look at "delete.c" it seemed to imply if you delete a node everything down from it would be taken out - if that... |
2,186,829 | 2,189,487 | Is it possible to package WPF window as COM Object | I am trying to use a WPF window from a legacy c++ unmanaged gtk gui application. Is it possible to package the WPF window (including the xaml file) and use it in the c++ gui application as a regular com object. Do you foresee any issues or problems with this approach?
If possible any links or tutorials or any suggestio... | I'm not aware of any tutorials online for doing this; but it shouldn't be a big problem at all. I've tried implementing smth like this and it worked fine for me, below is sequence if steps I've done:
1.add a "wpf user control" or "wpf custom control" library to your solution.
2.add a new WPF Window class (Add->Window... |
2,187,068 | 2,187,082 | How can I assign to an instance variable in C++ when a local variable has same name? | I have a class defined like this:
class MyClass
{
int x;
public:
MyClass(int x);
};
MyClass::MyClass(int x)
{ //Assign x here
}
However, I can't initialize x in the constructor because it has the same name as an instance variable. Is there any way around this(other than changing the name of the ar... | The best option is to use the constructor's initializer list:
MyClass::MyClass(int x) : x( x ) { // Body }
But you could also try this approach:
MyClass::MyClass(int x) { this->x = x; }
|
2,187,128 | 2,187,232 | where to store .properties file for use in c++ dll | I created a .properties file that contains a few simple key = value pairs.
I tried it out from a sample c++ console application, using imported java classes, and I was able to access it, no problem.
Now, I am trying to use it in the same way, from a C++ dll, which is being called by another (unmanaged) c++ project.
For... | As you are mentioning "DLL" i guess, that you are using MS Windows. Finding a file there from a DLL, and independently from the logged on user is a restricted item. The best way is to store the file in a path assembled from the environment variable ALLUSERSPROFILE. This is the only location that is equal to all users a... |
2,187,189 | 2,188,050 | creating arrays in nvidia cuda kernel | hi I just wanted to know whether it is possible to do the following inside the nvidia cuda kernel
__global__ void compute(long *c1, long size, ...)
{
...
long d[1000];
...
}
or the following
__global__ void compute(long *c1, long size, ...)
{
...
long d[size];
...
}
| You can do the first example, I haven't tried the second.
However, if you can help it, you might want to redesign your program not to do this. You do not want to allocate 4000 bytes of memory in your kernel. That will lead to a lot of use of CUDA local memory, since you will not be able to fit everything into registers... |
2,187,263 | 2,187,297 | What is the best technique to create a thread in C++ while passing the class and an index? | I am creating a data-parallel program using pthreads and C++. From pthread function from a class, I found out how to supply pthread_create with a function pointer to a static C++ function(and supply it a this argument).
However, I also need to supply the thread with an index, so it knows what data it's working on. I co... | You can use Boost.Thread. It provides a type-safe way for you to pass more than one argument into your callable.
Yes, it has similar kinds of bookkeeping as your question stated, but it uses C++ mechanisms to ensure that it doesn't leak.
|
2,187,425 | 2,187,865 | How do I use a COM DLL with LoadLibrary in C++ | First, COM is like black magic for me. But I need to use COM dll in one project I'm working on.
So, I have a DLL I am developing and I need some functionalities that are available in a separate COM DLL. When I look to the COM DLL with Depends.exe I see methods like DllGetClassObject() and other functions but none of t... | Typically you would use CoCreateInstance() to instantiate an object from a COM DLL. When you do this, there's no need to load the DLL first and get proc addresses like you would need to do with a normal DLL. This is because Windows "knows" about the types that a COM DLL implements, what DLL they are implemented in, a... |
2,187,609 | 2,187,640 | c and c++ operators help | can someone explain to me why the following results in b = 13?
int a, b, c;
a = 1|2|4;
b = 8;
c = 2;
b |= a;
b&= ~c;
| It is using binary manipultaors. (Assuming ints are 1 byte, and use Two's complement for storage, etc.)
a = 1|2|4 means a = 00000001 or 00000010 or 00000100, which is 00000111, or 7.
b = 8 means b = 00001000.
c = 2 means c = 00000010.
b |= a means b = b | a which means b = 00001000 or 00000111, which is 00001111, or 1... |
2,187,648 | 2,188,001 | How can I use a std::valarray to store/manipulate a contiguous 2D array? | How can I use a std::valarray to store/manipulate a 2D array?
I'd like to see an example of a 2D array with elements accessed by row/column indices. Something like this pseudo code:
matrix(i,j) = 42;
An example of how to initialize such an array would also be nice.
I'm already aware of Boost.MultiArray, Boost.uBlas, a... | Off the top of my head:
template <class element_type>
class matrix
{
public:
matrix(size_t width, size_t height): m_stride(width), m_height(height), m_storage(width*height) { }
element_type &operator()(size_t row, size_t column)
{
// column major
return m_storage[std::slice(column, m_heigh... |
2,187,679 | 2,187,735 | C++ containers behavior | My question is simple. When I use STL containers, do they copy the value I store there (by using copy constructor) or not? What if I give them array of characters (char *) instead of string instance? How do they behave? Is guaranteed that information will be stored in heap instead of system stack?
Thanks for answers.
| Values in STL containers are stored by-value. If you have a vector like this:
class BigObject
{
...
};
vector<BigObject> myObjs;
myObjs.push_back(obj1);
myObjs.push_back(obj2);
...
The vector will make a copy of the object you're pushing in. Also in the case of a vector, it may make new copies later when it has to ... |
2,187,724 | 2,187,757 | X-Macros Redefinition | When i include the "xmacro.h" in header file which is used by multiple header files i get linking error:
Error LNK2005: "char const * * iD_Strings" (?iD_Strings@@3PAPBDA)
already defined in header_file.obj
1.//"xmacro.h"
2.
3.// (1) Define code generating macro
4.
5. #ifndef XMACRO_H
6. #define XMACRO_H
7.
8. ... | Your header file contains the definition of iD_Strings. When you include it from different source files, it gets linked in multiple times. That results in a conflict even if the definitions are identical.
You could declare iD_Strings as static (the C way) or wrap it in an anonymous namespace (the C++ way) to get around... |
2,187,927 | 2,188,123 | ICU Unicode Normal vs Fullwidth | I am somewhat new to unicode and unicode strings. I'm trying to determine the difference between "fullwidth" symbol and a normal one.
Take these two for example:
Normal: http://www.fileformat.info/info/unicode/char/20a9/index.htm
Fullwidth: http://www.fileformat.info/info/unicode/char/ffe6/index.htm
I notice that the f... | U+number is a notational convention for a Unicode code point. There is no 'value' of U.
U+0020, for example, is a space. The value in memory is 32 decimal, 20 hex.
Full width characters are a whole other story.
Back in the days of the 3270, Hanzi took up two positions in memory in the display. So they also took up two ... |
2,188,024 | 2,188,324 | C++ calling managed COM object can't find dependent assemblies | I've created and registered a managed COM library in C# on my development machine. I've successfully registered it and created a .tlb file with regasm, and successfully imported the tlb into a c++ console app used for testing.
My COM assembly is called "efcAPI.dll" and it references another assembly that has not been s... | Yes, this is a problem with COM components having non-COM dependencies. Windows doesn't consider the location of the COM DLL when it searches for dependent DLLs. The normal search rules are in effect, the folder that contains the EXE first, Windows directories, current working directory, PATH environment. The locati... |
2,188,490 | 2,188,531 | Static library inspector for windows? | I know there are tools like PE Explorer for inspecting the contents of DLLs on windows (exported symbols, etc). Is there something similar for static libraries? I'm linking against a third party library that's generating some linking errors, and I want to double check that the symbols I expect are indeed being provid... | Dumpbin
The DUMPBIN utility, which is provided with the 32-bit version of Microsoft Visual C++, combines the abilities of the LINK, LIB, and EXEHDR utilities. The combination of these tools features the ability to provide information about the format and symbols provided in executable, library, and DLL files.
|
2,188,559 | 2,188,573 | C++ How to use and pass a 3-dimensional char array? | I'm trying to build a char array for storing the return value of a function. In the following function the data is stored in *****valv**. How to build a extern variable to access the data?
int credis_lrange(REDIS rhnd, const char *key,
int start, int end, char ***valv)
{
int rc;
if ((rc = cr_... | char ***element[size];
Is not exactly a 3D array, but an array of size elements of pointers-to-pointers-to-pointers to char.
Use any one of the following:
char e[ D1 ][ D2 ][ D3 ]; /* D1, D2, D3 are integral constants */
char *e[ D2 ][ D3 ];
char e[][ D2 ][ D3 ];
Also, you can pass it on by simply speficying e as the... |
2,188,680 | 2,188,723 | Is fastcall really faster? | Is the fastcall calling convention really faster than other calling conventions, such as cdecl?
Are there any benchmarks out there that show how performance is affected by calling convention?
| It depends on the platform. For a Xenon PowerPC, for example, it can be an order of magnitude difference due to a load-hit-store issue with passing data on the stack. I empirically timed the overhead of a cdecl function at about 45 cycles compared to ~4 for a fastcall.
For an out-of-order x86 (Intel and AMD), the impac... |
2,188,698 | 2,188,753 | A method of creating simple game GUI | I have been able to find a lot of information on actual logic development for games. I would really like to make a card game, but I just dont understand how, based on the mouse position, an object can be selected (or atleast the proper way) First I thought of bounding box checking but not all my bitmaps are rectangles.... | Your question is how to tell if the mouse is above a non-rectangular bitmap. I am assuming all your bitmaps are really rectangular, but they have transparent regions. You must already somehow be able to tell which part of your (rectangular) bitmap is transparent, depending on the scheme you use (e.g. if you designate a... |
2,188,751 | 2,188,765 | linking <iostream.h> in linux using gcc | I'm trying to run my very first c++ program in linux (linux mint 8). I use either gcc or g++, both with the same problem: the compiler does not find the library I am trying to import.
I suspect something like I should either copy the iostream.h file (which I don't know where to look for) in the working folder, move m... |
cout is defined in the std:: namespace, you need to use std::cout instead of just cout.
You should also use #include <iostream> not the old iostream.h
use g++ to compile C++ programs, it'll link in the standard c++ library. gcc will not. gcc will also compile your code as C code if you give it a .c suffix. Give your f... |
2,188,879 | 2,188,942 | C C++ array.... need help understanding code | Can you please explain this code? It seems a little confusing to me
Is "a" a double array? I would think it's just an integer, but then in the cout statement it's used as a double array. Also in the for loop condition it says a<3[b]/3-3, it makes no sense to me, however the code compiles and runs. i'm just having troub... | Wow. This is really funky. This isn't really 2 dimensional array. it works because c is an array and there is an identity in the C language that treats this
b[3]
as the same as this
3[b]
so this code translates into a loop that increments a while a < (24/3-3) since 3[b] is the same as b[3] and b[3] is 24. Then it ... |
2,188,980 | 2,189,002 | Dock a control in native C++ | I know how to do this in .Net but in native Win32, how does one dock a control. I'm trying to dock a trackbar I made like vlc's trackbar.
Thanks
dock it to the bottom of its parent window
| You write the code to do it, or use a library which provides that functionality. If you are intent on using raw Win32, handle the WM_SIZE message for the container, calculate where the trackbar should be, and put it there. Roughly (0,height-trackbar_height,width,trackbar_height).
Apparently, Pearl Jam are still touring... |
2,188,991 | 2,189,018 | What is useful about a reference-to-array parameter? | I recently found some code like this:
typedef int TenInts[10];
void foo(TenInts &arr);
What can you do in the body of foo() that is useful, that you could not do if the declaration was:
void foo(int *arr); // or,
void foo(int arr[]); // or,
void foo(int arr[10]); // ?
I found a question that asks how to pass a r... | The reference-to-array parameter does not allow array type to decay to pointer type. i.e. the exact array type remains preserved inside the function. (For example, you can use the sizeof arr / sizeof *arr trick on the parameter and get the element count). The compiler will also perform type checking in order to make su... |
2,189,189 | 2,189,206 | map vs. hash_map in C++ | I have a question with hash_map and map in C++. I understand that map is in STL, but hash_map is not a standard. What's the difference between the two?
| They are implemented in very different ways.
hash_map (unordered_map in TR1 and Boost; use those instead) use a hash table where the key is hashed to a slot in the table and the value is stored in a list tied to that key.
map is implemented as a balanced binary search tree (usually a red/black tree).
An unordered_map s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.