question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,158,410 | 2,158,437 | Memory leaks in Debug mode | Is there any reason for a program to leak when compiled in Debug mode and not in release?
(Debug means debug informations, and compiler optimization disabled, Release means no debug info / full optimization)
That's what it seems to do but I can't figure out why. Btw purify is not being helpful here
| A lot of pointer type errors, including memory leaks, can seem to appear or disappear when switching between debug and release mode. A couple of reasons might be:
Conditional code compiled in one version or the other
Memory locations of things move around
Special formatting of uninitialized data in the debug version
|
2,158,438 | 2,158,531 | How do I get specific error information from GetFile()? | void GetFtpFile(LPCTSTR pszServerName, LPCTSTR pszRemoteFile, LPCTSTR pszLocalFile)
{
CInternetSession session(_T("My FTP Session"));
CFtpConnection* pConn = NULL;
pConn = session.GetFtpConnection(pszServerName);
//get the file
if (!pConn->GetFile(pszRemoteFile, pszLocalFile))
{
//display an error
}
delete pConn;
session.Close();
}
How do I get specific error information from GetFile()?
Thank You.
| According to MSDN:
Return Value
Nonzero if successful;
otherwise 0. If the call fails, the
Win32 function GetLastError may be
called to determine the cause of the
error.
GetLastError() returns an error code, but you can call FormatMessage() to get a human-readable string from the error code. Here's a utility function that does that for you:
std::string formatwinerr(unsigned long errCode)
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM ,
0,
errCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
std::string ret((const char*)lpMsgBuf);
LocalFree(lpMsgBuf);
return ret;
}
|
2,158,512 | 2,158,697 | more c++ multiple inheritance fun |
Possible Duplicate:
C++ pointer multi-inheritance fun.
(Follow up on: C++ pointer multi-inheritance fun )
I'm writing some code involving inheritance from a basic ref-counting pointer class; and some intricacies of C++ popped up. I've reduced it as follows:
Suppose I have:
class A{int x, y;};
class B{int xx, yy;};
class C: public A, public B {int z;};
C c;
C* pc = &c;
B* pb = &c;
A* pa = &c;
// does pa point to a valid A object?
// does pb point to a valid B object?
// does pa == pb ?
Furthermore, does:
// pc == (C*) pa ?
// pc == (C*) pb ?
Thanks!
Here, "==" means points at the same value.
|
Yes
Yes
No
Yes
No*
But you need to know how C++ organises memory. The layout of a class, CClass, is as follows:
offset
0 First base class in list of base classes
sizeof first base class Next base class
sizeof first N-1 base classes Nth base class
sizeof all base classes CClass
OK, it's a bit more complex than that if there is an inheritance tree, but you should get the basic idea. Assuming an int is four bytes then class C is laid out like:
offset
0 A::x
4 A::y
8 B::xx
12 B::yy
16 C:z
But the an object of type C is all of the above, so a pointer to a C is pointing to offset 0. However, C++ allows implicit downcasting, so a pointer to a C can be converted to a pointer to an A or a pointer to a B. But if you look at the above, a pointer to a B is at offset 8 rather than 0 (a pointer to a C) and that a pointer to an A is at offset 0. So, casting a pointer to a C to a pointer to a B adds 8 to the pointer value. This is because the methods of B assume the 'this' pointer points to B's first member (B::xx), but a pointer to a C if reinterpreted as a pointer to a B (i.e. the value is the same) would be pointer to an address eight bytes before where B actually is, so that all of B's methods would be using, in this instance, A's members.
Upcasting (the final two conversions) is different kettle of fish. Going from a pointer to a B to a pointer to a C is really hard because you don't know if the pointer to a B is just pointing to an instance of B or at an instance of C plus eight. This is where RTTI and the dynamic cast comes in. With RTTI (Run Time Type Information) enabled, the pointer to B contains additional information that describes what B really is - a simple B or a B as part of a C. This does have additional cost, both execution time and memory usage.
Finally, this does highlight the ambiguity of the C style cast. You really should use the C++ style casts (static_cast <>, etc) as this clarifies the way the conversion should be done.
*This could also be a yes, I guess it depends on the compiler and if RTTI is on or off. You would need to get into the details of the standard and the compiler implementation to say for sure.
|
2,158,638 | 2,158,684 | c++ multiple-inheritance |
Possible Duplicates:
C++ pointer multi-inheritance fun.
more c++ multiple inheritance fun
This is a problem that arose from dealing with ref-counted pointer base class and threading fun.
Given:
class A{int x, y;};
class B{int xx, yy;};
class C: public A, public B {int z;};
C c;
C* pc = &c;
B* pb = CtoB(pc);
A* pa = CtoA(pc);
assert(pc == AtoC(pa));
assert(pc == BtoC(pb));
How do I write CtoB and CtoA to get the B & A parts of C?
How to I write AtoC and BtoC to get back the original C?
Thanks!
Why the votes to close?
My previous two questions asked if something was valid (the answer was "no"); this question asks "what is the valid way to do pointer conversion."
| You don't need any function, since C only derives once from A and B. Unless you derive from A or B multiple times (without virtual inheritance), you only need to use:
A *pbb = pc;
B *pba = pc;
AtoC and BtoC are only safe through:
C *c = dynamic_cast<C*>(a_or_b_pointer);
|
2,158,839 | 2,158,907 | Notify a C++ application when a change in a SQL Server table is made | I've posted this before but haven't obtained a suitable answer that fits my requirements. I'm looking for a technology to notify a C++ application when a change to a SQL Server table is made. Our middle-tier is C++ and we're not looking to move onto .NET infrastructure which means we can't use SQLDependency, or SQL Notification Servers. We're also stuck with SQL Server 2005 for the time being which also eliminates SQL Service Broker External Activation (that is introduced in SQL 2008).
To give a broader understanding of what I'm trying to achieve: our database is being updated with new information; Whenever a new piece of information is received, we'd like to push this to the C++ application so that its dashboard reflects up-to-date data for the user.
We know we can do this by having the C++ application polling the database but I see this as inefficient architecture and would like to have SQL push the information or a notification to C++.
| You can actually use Query Notifications from C++. Both the OleDB and the ODBC clients for SQLNCLI10 and SQLNCLI providers support Query Notifications. See Working with Query Notifications, at the second half of the page you'll find the SSPROP_QP_NOTIFICATION... stuff for the OleDB rowsets and the SQL_SOPT_SS_QUERYNOTIFICATION... stuff for ODBC statements. So subscribing for notifications from a C++ mid tier is absolutely doable. And the second piece of the puzzle is to actually get the notifications, which is nothing else than posting a RECEIVE and waiting. In other words you can roll your own SqlDepdency in pure C++ over OleDB or ODBC. Once you have the mid-tier notified, it's a piece of cake (well, sort of) to update the client displays.
Between all the alternatives to detect data changes, you won't find anything better than Query Notifications.
BTW, one thing you should absolutely avoid is notifying the clients from triggers (oh, the horror...).
|
2,158,901 | 2,161,027 | Connected Component Labeling in C++ | I need to use the connected component labeling algorithm on an image in a C++ application. I can implement that myself, but I was trying to use Boost's union-find/disjoint sets implementation since it was mentioned in the union-find wiki article.
I can't figure out how to create the disjoint_sets object so that it'll work with the image data I have (unsigned shorts). What am I missing? The examples in the Boost documentation aren't making any sense to me. Do I need all the extra Graph mumbo-jumbo in those examples when I have an image? OR, is there already an OpenCV connected component labeling implementation. Currently we're using OpenCV 1.1pre1 and Boost 1.37.
| Surprisingly, there is no CCL in OpenCV. However, there is a workaround that is described in the reference manual. See the example for cvDrawContours. When I tried to use it, I had some strange behaviour on first and last rows and columns of an image, but I probably did something wrong.
An alternative way is to use cvBlobs library.
|
2,158,928 | 2,158,965 | Inherit from two polymorphic classes | Given the following code
class T {
public:
virtual ~T () {}
virtual void foo () = 0;
};
class U {
public:
U() {}
~U() {}
void bar () { std::cout << "bar" << std::endl; }
};
class A : public U, public T {
public:
void foo () { std::cout << "foo" << std::endl; }
};
int main () {
A * a = new A;
std::vector<U*> u;
std::vector<T*> t;
u.push_back(a);
t.push_back(reinterpret_cast<T*>(u[0]));
u[0]->bar ();
t[0]->foo ();
delete a;
return 0;
}
I get the output I would expect
bar
foo
However, if I change the definition of U to
class U {
public:
U() {}
virtual ~U() {}
virtual void bar () { std::cout << "bar" << std::endl; }
};
I still compile fine and without warnings/errors but the output is now
bar
bar
What is it about the virtual declaration that prevents me from calling into the foo?
| Firstly, there are no virtual base classes in your example. Classes that contain virtual functions are called polymorphic. (There is such thing as "virtual base classes" in C++ but it has nothing to do with your example.)
Secondly, the behavior of your code does not depend on any virtual declarations. You have deliberately destroyed the integrity of the base pointer by using reinterpret_cast. For this reason the behavior of the code is undefined.
A direct cast from one base pointer to another (which is what you are trying to do in your code) is called cross-cast. The only cast in C++ that can carry out a cross-cast is dynamic_cast.
t.push_back(dynamic_cast<T *>(u[0]));
You can perform an indirect cross-cast without dynamic_cast, but for that you have to downcast the pointer to the derived type first (A *) using static_cast and then upconvert it to another base pointer type
t.push_back(static_cast<A *>(u[0])); // upconversion to `T *` is implicit
|
2,158,943 | 2,158,953 | Split string into array of chars | I'm writing a program that requires a string to be inputted, then broken up into individual letters. Essentially, I need help finding a way to turn "string" into ["s","t","r","i","n","g"]. The strings are also stored using the string data type instead of just an array of chars by default. I would like to keep it that way and avoid char but will use it if necessary.
| string a = "hello";
cout << a[1];
I hope that explains it
|
2,158,949 | 2,159,093 | How to use colors in Motif | I'm new to GUI programming in C and Linux, and I'm having a hard time with it. It seems like a fairly simple/straightforward thing, but I can't find any answers googling. I want to add a background color to a widget. XmNbackground seems to be what I want to use, but I don't understand what I set it to, like a simple color blue, how do I get "blue" to set XmNbackground color to that?
| See here for an answer in the function Pixel convert_color_name_to_pixel, and also here.
Hope this helps.
|
2,159,108 | 2,159,136 | C++ classes and nested members | I'm not sure how to call this. Basically I want to make a class with nested members.
Example:
ball->location->x;
or
ball->path->getPath();
right now I only know how to make public and private members such as
ball->x;
ball->findPath();
Thanks
| Something like this:
class Plass
{
public:
Plass(Point *newPoint, Way *newWay)
{
moint = newPoint;
bay = newWay;
// or instantiate here:
// moint = new Point();
// bay = new Way();
// just don't forget to mention it in destructor
}
Point *moint;
Way *bay;
}
From here you can do:
Plass *doxy = new Plass();
doxy->moint->x;
doxy->bay->path->getPath();
|
2,159,147 | 2,159,157 | Program unexpectedly quits for unknown reason (C++) | For some reason, whenever I run this program it exits at permute(permutater, length, lenth); . This doesn't happen whenever I comment out the line and the function doesn't even run. Any help?
| First thing I noticed - you're not initializing the index variable hor.
int permute(string permutater,int length,int lenth)
{
int hor,hor2,marker;
cout << length/lenth;
for (marker=0;marker !=(length/lenth);marker++)
{
hor2 = permutater[hor]; // <== hor is not initialized
permutater[hor] = permutater[hor-1];
permutater[hor] = hor2;
hor--;
cout << permutater;
}
}
|
2,159,338 | 2,159,346 | What is the Java equivalent of C++'s templates? | What is the Java equivalent of C++'s templates?
I know that there is an interface called Template. Is that related?
| Templates as in C++ do not exist in Java. The best approximation is generics.
One huge difference is that in C++ this is legal:
<typename T> T sum(T a, T b) { return a + b; }
There is no equivalent construct in Java. The best that you can say is
<T extends Something> T Sum(T a, T b) { return a.add(b); }
where Something has a method called add.
In C++, what happens is that the compiler creates a compiled version of the template for all instances of the template used in code. Thus if we have
int intResult = sum(5, 4);
double doubleResult = sum(5.0, 4.0);
then the C++ compiler will compile a version of sum for int and a version of sum for double.
In Java, there is the concept of erasure. What happens is that the compiler removes all references to the generic type parameters. The compiler creates only one compiled version of the code regardless of how many times it is used with different type parameters.
Other differences
C++ does not allow bounding of type parameters whereas Java does
C++ allows type parameters to be primitives whereas Java does not
C++ allows templates type parameters to have defaults where Java does not
C++ allows template specialization whereas Java does not
And, as should be expected by this point, C++ style template metaprogramming is impossible with Java generics.
Forget about seeing the curiously recurring template pattern in Java
Policy-based design is impossible in Java
|
2,159,390 | 2,159,405 | In C++, is it possible to forward declare a class as inheriting from another class? | I know that I can do:
class Foo;
but can I forward declare a class as inheriting from another, like:
class Bar {};
class Foo: public Bar;
An example use case would be co-variant reference return types.
// somewhere.h
class RA {}
class RB : public RA {}
... and then in another header that doesn't include somewhere.h
// other.h
class RA;
class A {
public:
virtual RA* Foo(); // this only needs the forward deceleration
}
class RB : public RA; // invalid but...
class B {
public:
virtual RB* Foo(); //
}
The only information the compiler should need to process the declaration of RB* B:Foo() is that RB has RA as a public base class. Now clearly you would need somewhere.h if you intend to do any sort of dereferencing of the return values from Foo. However, if some clients never calls Foo, then there is no reason for them to include somewhere.h which might significantly speed compilation.
| A forward declaration is only really useful for telling the compiler that a class with that name does exist and will be declared and defined elsewhere. You can't use it in any case where the compiler needs contextual information about the class, nor is it of any use to the compiler to tell it only a little bit about the class. (Generally, you can only use the forward declaration when referring to that class without other context, e.g. as a parameter or return value.)
Thus, you can't forward declare Bar in any scenario where you then use it to help declare Foo, and it flat-out doesn't make sense to have a forward declaration that includes the base class -- what does that tell you besides nothing?
|
2,159,452 | 2,159,469 | C++: assign cin to an ifstream variable? | You know the common stdio idiom that stdin is specified by
a filename of "-", e.g.
if ((strcmp(fname, "-"))
fp = fopen(fname);
else
fp = stdin;
What's the best way to do this with an ifstream instance? I've received
a bit of code that has an ifstream as part of a class and I'd
like to add code to do the equivalent, something like:
if ( filename == "-")
logstream = cin; // **how do I do this*?*
else
logstream.open( filename.c_str() );
| cin is not an ifstream, but if you can use istream instead, then you're in to win. Otherwise, if you're prepared to be non-portable, just open /dev/stdin or /dev/fd/0 or whatever. :-)
If you do want to be portable, and can make your program use istream, here's one way to do it:
struct noop {
void operator()(...) const {}
};
// ...
shared_ptr<istream> input;
if (filename == "-")
input.reset(&cin, noop());
else
input.reset(new ifstream(filename.c_str()));
The noop is to specify a deleter that does nothing in the cin case, because, well, cin is not meant to be deleted.
|
2,159,490 | 2,159,504 | C++, twenty numbers not random? | Why are my C++ numbers not random?
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int randomNumber = rand() % 100;
for (randomNumber = 0; randomNumber < 20; randomNumber++)
{
cout << randomNumber << endl;
}
return 0;
}
//Why are my 20 numbers not random?
| You need to call rand() each time you want a random number. As you have it now you're generating one random number, then incrementing it and printing it out 20 times so you're going to get 20 sequential numbers.
Try something like
srand(time(NULL)); // Seeding the random number generator
for(int i=0; i<20; ++i)
{
cout << (rand() % 100) << endl;
}
The seeding of the random number generator is important, without that you would generate the same numbers every time you ran the program.
|
2,159,496 | 2,159,524 | c++ problem with function overloading | i have a problem with function overloading. I will show you with some simple example:
class A {};
class B : public A{};
void somefunction(A&, A&);
void somefunction(B&, B&);
void someotherfunction() {
...
A& a1 = ...
A& a2 = ...
...
}
Both a1 and a2 are instances of B but
somefunction(a1,a2);
calls
void somefunction(A&, A&);
What did i do wrong? I mean polymorphism and overloading are for stuff like that, arent they?
edit: Ok now i know it does not work (thanks for your answers).
Any solution how to do this? Without casting.
edit2: Ok left it as it is, with type casting, since something i would like to have is not possible. Thanks all for your help.
| Cast them statically so that the compiler knows which one to pick:
void somefunction((B&)a1, (B&)a2);
The reason why you are having this problem is with the program design, not the language. Compiler picks which which function is used based on the types that are passed in. C# will behave in exactly the same way (pretty sure Java will too).
It seems to me that you are implementing polymorphism in the wrong place. somefunction really belongs inside class a and should be virtual. Then whenever it's called on the instance of a at runtime the override in the right class will be called.
So, really it should be something like this:
class a {
public:
virtual somefunction(a& a2) {
//do stuff
}
}
class b : public a {
virtual somefunction(a& a2) {
b& b2 = (b&)a2;
//do stuff
}
}
class c : public b {
virtual somefunction(a& a2) {
c& c2 = (c&)a2;
//do stuff
}
}
The above solution uses minimal casting inside the virtual function and assumes that the two instance of the same type. This means that b.somefunction(a()) will have undefined behaviour.
A better solution is to rely on C++ RTTI and use dynamic_cast, which will return NULL if the downcast is not possible.
This problem is known as double dispatch problem and is described in the wikipedia article pretty much as you described it. Furthermore, the only solution that wikipedia gives for multiple dispatch is to use dynamic_cast.
EDIT OK, this has been bugging me, here is the solution for full double dispatch between a base class and two subclasses. It aint pretty and uses a bit of C++ trickery like friend classes (for better encapsulation actually, rather than the reverse) and forward declarations.
class b;
class c;
class a {
protected:
virtual void somefunction(a& a2); //do stuff here
virtual void somefunction(b& b2); //delegate to b
virtual void somefunction(c& c2); //delegate to c
public:
virtual void doFunc(a& a2) {
a2.somefunction(*this);
}
friend class b;
friend class c;
};
class b : public a {
protected:
virtual void somefunction(a& a2); //do stuff here
virtual void somefunction(b& b2); //do stuff here
virtual void somefunction(c& c2); //delegate to c
public:
virtual void doFunc(a& a2) {
a2.somefunction(*this);
}
friend class a;
};
class c : public b {
protected:
virtual void somefunction(a& a2); //do stuff here
virtual void somefunction(b& b2); //do stuff here
virtual void somefunction(c& c2); //delegate to c
public:
virtual void doFunc(a& a2) {
a2.somefunction(*this);
}
friend class a;
friend class b;
};
//class a
void a::somefunction(a& a2) {
printf("Doing a<->a");
}
void a::somefunction(b& b2) {
b2.somefunction(*this);
}
void a::somefunction(c& c2) {
c2.somefunction(*this);
}
//class b
void b::somefunction(a& a2) {
printf("Doing b<->a");
}
void b::somefunction(b& b2) {
printf("Doing b<->b");
}
void b::somefunction(c& c2) {
c2.somefunction(*this);
}
//class c
void c::somefunction(a& a2) {
printf("Doing c<->a");
}
void c::somefunction(b& b2) {
printf("Doing c<->b");
}
void c::somefunction(c& c2) {
printf("Doing c<->c");
}
|
2,159,538 | 2,159,558 | c++ publicly inherited class member cannot be used as default argument | A schematic of my problem...
class A
{
public:
// etc.
protected:
uint num;
};
class B : public A
{
public:
void foo(uint x = num); //bad
};
gives this error:
error: invalid use of non-static data member ‘A::num’
error: from this location
Why does this happen, and what can I do to work around this?
| I suspect this happens (based on the complaint about non-staticness) because there is no this pointer for it to use to know which instance of B it should get num from.
The Microsoft compiler (at least) allows you to specify an expression, but not a non-static member. From MSDN:
The expressions used for default
arguments are often constant
expressions, but this is not a
requirement. The expression can
combine functions that are visible in
the current scope, constant
expressions, and global variables. The
expression cannot contain local
variables or non-static class-member
variables.
Work-arounds for this are numerous and others have pointed out a few. Here's one more which you may or may not like:
void foo(uint* x = NULL) {
uint y = (x == NULL ? num : *x);
// use y...
}
|
2,159,713 | 2,159,732 | Overloading Output operator for a class template in a namespace | I've this program
#include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std ;
#if 0
namespace skg
{
template <class T>
struct Triplet ;
}
template <class T>
ostream& operator<< (ostream& os, const skg::Triplet<T>& p_t) ;
#endif
namespace skg
{
template <class T>
struct Triplet
{
// friend ostream& ::operator<< <> (ostream& os, const Triplet<T>& p_t) ;
private:
T x, y, z ;
public:
Triplet (const T& p_x, const T& p_y, const T& p_z)
: x(p_x), y(p_y), z(p_z) { }
} ;
}
template <class T>
ostream& operator<< (ostream& os, const skg::Triplet<T>& p_t)
{
os << '(' << p_t.x << ',' << p_t.y << ',' << p_t.z << ')' ;
return os ;
}
namespace {
void printVector()
{
typedef skg::Triplet<int> IntTriplet ;
vector< IntTriplet > vti ;
vti.push_back (IntTriplet (1, 2, 3)) ;
vti.push_back (IntTriplet (5, 5, 66)) ;
copy (vti.begin(), vti.end(), ostream_iterator<IntTriplet> (cout, "\n")) ;
}
}
int main (void)
{
printVector() ;
}
Compilation fails because compiler could not find any output operator for skg::Triplet. But output operator does exist.
If I move Triplet from skg namespace to global namespace everything works fine. what is wrong here ?
| You need to move your implementation of operator<< into the same namespace as your class. It's looking for:
ostream& operator<< (ostream& os, const skg::Triplet<T>& p_t)
But won't find it because of a short-coming in argument-dependent look-up (ADL). ADL means that when you call a free function, it'll look for that function in the namespaces of it's arguments. This is the same reason we can do:
std::cout << "Hello" << std::endl;
Even though operator<<(std::ostream&, const char*) is in the std namespace. For your call, those namespaces are std and skg.
It's going to look in both, not find one in skg (since yours is in the global scope), then look in std. It will see possibilities (all the normal operator<<'s), but none of those match. Because the code running (the code in ostream_iterator) is in the namespace std, access to the global namespace is completely gone.
By placing your operator in the same namespace, ADL works. This is discussed in an article by Herb Sutter: "A Modest Proposal: Fixing ADL.". (PDF). In fact, here's a snippet from the article (demonstrating a shortcoming):
// Example 2.4
//
// In some library header:
//
namespace N { class C {}; }
int operator+( int i, N::C ) { return i+1; }
// A mainline to exercise it:
//
#include <numeric>
int main() {
N::C a[10];
std::accumulate( a, a+10, 0 ); // legal? not specified by the standard
}
Same situation you have.
The book "C++ Coding Standards" by Sutter and & Alexandrescu has a useful guideline:
Keep a type and its nonmember function interface in the same namespace.
Follow it and you and ADL will be happy. I recommend this book, and even if you can't get one at least read the PDF I linked above; it contains the relevant information you should need.
Note that after you move the operator, you'll need your friend directive (so you can access private variables):
template <typename U>
friend ostream& operator<< (ostream& os, const Triplet<U>& p_t);
And ta-da! Fixed.
|
2,159,801 | 2,159,835 | Application wide periodic tasks with Dialog Based MFC application | In Single Document Interface (SDI) or Multiple Document Interface (MDI) MFC application, I created an application wide timer in the View. The timer will tick as long as the application is running and trigger some periodic actions.
How can I do the same with Dialog Based MFC application?
Should I create Thread's Timer (SetTimer with NULL HWND) and pass a callback function to it?
Should I create worker threads? My experience with other projects was when I tried to display some feedback GUI from non-GUI/worker threads, I need to roll out my own "delegate"/command pattern and a "delegate invoker"/command invoker. The worker thread will send message (I think using message is safer than direct function call when dealing across thread-boundary, CMIIW) to the UI-thread. and the UI-thread will be the "delegate"/command invoker. Failing to do this and to make sure that the windows/dialogs have the correct parent will result in bizzare behaviors such as the Application suddenly disappears to the background; Window/Dialog that is shown behind the current window/dialog and causing the current window to be unresponsive/unclickable. Probably I was doing something wrong but there were so much problems when dealing with threads.
Are there best practices for this?
| A timer works as well in a dialog-based application as an SDI or MDI app. OTOH, timers are (mostly) a leftover from 16-bit Windows. If you want to do things periodically, a worker thread is usually a better way to do it (and yes, Windows Mobile supports multiple threads).
Edit: in a dialog-based application, the main dialog exists for (essentially) the entire life of the application. Unless you really need the timer during the milliseconds between application startup and dialog creation or dialog destruction and application exit, just attach it to the dialog. Otherwise, you can attach it to the main window -- which MFC creates and destroys, even though it's never displayed.
|
2,159,986 | 2,160,315 | gcc code::blocks shared library questions | I'm using code::blocks on a linux system with the gcc compiler, and I want to be able to use the shared library template to make a shared library with classes, then make another project that accesses that shared library(at compile time, not dynamically) and classes.
I'm sure that code::blocks has simple way of doing this without making custom makefiles and manually setting link options, but I don't know how. How do I do this.
Shared Library
sl.h
class clsClass
{
public:
static bool bolReturnTrue(char * chWhatever);
};
sl.cpp
bool clsClass::bolReturnTrue(char * chWhatever)
{
return true;
}
Program Accessing Shared Library
main.cpp
int main(int argc, char * argv[])
{
bool Face = clsClass::bolReturnTrue(argv[0]);
if(Face)
{
printf("True.\n");
}
else
{
printf("False.\n");
}
return 0;
}
| You can have more then one project in your workspace and set project dependencies, there are no custom makefiles needed.
The basic steps with Code::Blocks are the following:
make sure your shared library project generates an import library (project properties->build targets)
make the shared lib project a dependency of the project in question (project settings->project dependencies)
link to the import library
include your shared libraries headers in the relevant source files
|
2,160,187 | 2,160,540 | C++ compilation for iPhone (STL issue?) | I am trying to compile some C++ code as a static library to use on the iPhone. If I compile things for the simulator (i386 architecture), everything compiles just peachy, but when I switch the architecture to arm, I get all these include errors, seemingly within the iPhone SDK STL headers. Any idea what's going on?
First of the errors:
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.0.sdk/usr/include/c++/4.2.1/string:45:0 Bits/c++config.h: No such file or directory in
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.0.sdk/usr/include/c++/4.2.1/string
| Add /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.0.sdk/usr/include/c++/4.2.1/armv6-apple-darwin9/ as the include path.
Also, please file a bug to Apple.
|
2,160,334 | 2,160,422 | Boost weak_ptr's in a multi-threaded program to implement a resource pool | I'm thinking of using boost::weak_ptr to implement a pool of objects such that they will get reaped when nobody is using one of the objects. My concern, though, is that it's a multi-threaded environment, and it seems there's a race condition between the last shared_ptr to an object going out of scope and a new shared_ptr being constructed from the weak_ptr. Normally, you'd protect such operations with lock or something; however, the whole point here is that you don't know when the shared_ptr might be going out of scope.
Am I misunderstanding something about boost::shared_ptr and boost::weak_ptr? If not, does anybody have any good suggestions on what to do?
Thanks.
Andrew
| To use a weak_ptr, you normally have to grab a strong reference by constructing a shared_ptr with it. This last step is atomic: you either get a strong reference back, or you get a bad_weak_ptr exception thrown. (Alternatively, call lock() on the weak_ptr, and either get a strong reference or null.)
Example (with lock(); easy enough to adapt to the other style):
void do_something(weak_ptr<foo> weak) {
// Grab strong reference
shared_ptr<foo> strong(weak.lock());
if (strong) {
// We now have a strong reference to use
} else {
// No strong references left; object already freed
}
}
|
2,160,565 | 2,160,797 | Is there any charting lib for C++? | I have a C++ program that generates some data and i need to generate some charts for that data and to plot some functions.
Is there any free library available that can do that and just generate a png/jpeg(format doesn't matter)?
Google charts is not an option as i want to be able to generate charts even when offline.
| Check out http://qwt.sourceforge.net/. It's Qt-based.
|
2,160,616 | 2,160,632 | Convert C++ to Python (For Loop multiple assignment) | Convert to python:
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
for (int i = 0, j = i + 3; i < 100; ++i, j= i+3)
cout << i << " j: " << j << endl;
getchar();
return 0;
}
I try:
for i in range(99):
j = i + 3
print i, " j: ", j
How to make it one for loop?
| Just change 99 to 100
for i in range(100):
j = i + 3
print i, " j: ", j
Or
for i,j in [(i, i+3) for i in range(100)]:
|
2,160,720 | 2,160,769 | Any smarter way to extract from array of bits? | I have areas of memory that could be considered "array of bits". They are equivalent to
unsigned char arr[256];
But it would be better thought of as
bit arr[2048];
I'm accessing separate bits from it with
#define GETBIT(x,in) ((in)[ ((x)/8) ] & 1<<(7-((x)%8)))
but I do it a lot in many places of the code, often in performance-critical sections and I wonder if there are any smarter, more optimal methods to do it.
extra info: Architecture: ARM9 (32 bit); gcc/Linux. The physical data representation can't be changed - it is externally provided or mapped for external use.
| For randomly accessing individual bits, the macro you've suggested is as good as you're going to get (as long as you turn on optimisations in your compiler).
If there is any pattern at all to the bits you're accessing, then you may be able to do better. For example, if you often access pairs of bits, then you may see some improvement by providing a method to get two bits instead of one, even if you don't always end up using both bits.
As with any optimisation problem, you will need to be very familiar with the behaviour of your code, in particular its access patterns in your bit array, to make a meaningful improvement in performance.
Update: Since you access ranges of bits, you can probably squeeze some more performance out of your macros. For example, if you need to access four bits you might have macros like this:
#define GETBITS_0_4(x,in) (((in)[(x)/8] & 0x0f))
#define GETBITS_1_4(x,in) (((in)[(x)/8] & 0x1e) >> 1)
#define GETBITS_2_4(x,in) (((in)[(x)/8] & 0x3c) >> 2)
#define GETBITS_3_4(x,in) (((in)[(x)/8] & 0x78) >> 3)
#define GETBITS_4_4(x,in) (((in)[(x)/8] & 0xf0) >> 4)
#define GETBITS_5_4(x,in) ((((in)[(x)/8] & 0xe0) >> 5) | (((in)[(x)/8+1] & 0x01)) << 3)
#define GETBITS_6_4(x,in) ((((in)[(x)/8] & 0xc0) >> 6) | (((in)[(x)/8+1] & 0x03)) << 2)
#define GETBITS_7_4(x,in) ((((in)[(x)/8] & 0x80) >> 7) | (((in)[(x)/8+1] & 0x07)) << 1)
// ...etc
These macros would clip out four bits from each bit position 0, 1, 2, etc. (To cut down on the proliferation of pointless parentheses, you might want to use inline functions for the above.) Then perhaps define an inline function like:
inline int GETBITS_4(int x, unsigned char *in) {
switch (x % 8) {
case 0: return GETBITS_0_4(x,in);
case 1: return GETBITS_1_4(x,in);
case 2: return GETBITS_2_4(x,in);
// ...etc
}
}
Since this is a lot of tedious boilerplate code, especially if you've got multiple different widths, you may want to write a program to generate all the GETBIT_* accessor functions.
(I notice that the bits in your bytes are stored in the reverse order from what I've written above. Apply an appropriate transformation to match your structure if you need to.)
|
2,160,889 | 2,161,288 | How to detect the device name for a capture device? | I am writing a GStreamer application (GStreamer uses DirectShow under the hood on Windows) that captures a computer's microphone and videocamera. It works fine, but requires me to specify the device names manually. I would like to have my program detect these automatically. Does anyone know how to do that?
| It would surprise me if GStreamer doesn't have capabilities to enumerate devices, but DirectShow definitely has.
See the article on using the system device enumerator and use it with the correct filter categories - in your case CLSID_AudioInputDeviceCategory and CLSID_VideoInputDeviceCategory.
|
2,160,920 | 2,160,944 | Why can't we declare a std::vector<AbstractClass>? | Having spent quite some time developping in C#, I noticed that if you declare an abstract class for the purpose of using it as an interface you cannot instantiate a vector of this abstract class to store instances of the children classes.
#pragma once
#include <iostream>
#include <vector>
using namespace std;
class IFunnyInterface
{
public:
virtual void IamFunny() = 0;
};
class FunnyImpl: IFunnyInterface
{
public:
virtual void IamFunny()
{
cout << "<INSERT JOKE HERE>";
}
};
class FunnyContainer
{
private:
std::vector <IFunnyInterface> funnyItems;
};
The line declaring the vector of abstract class causes this error in MS VS2005:
error C2259: 'IFunnyInterface' : cannot instantiate abstract class
I see an obvious workaround, which is to replace IFunnyInterface with the following:
class IFunnyInterface
{
public:
virtual void IamFunny()
{
throw new std::exception("not implemented");
}
};
Is this an acceptable workaround C++ wise ?
If not, is there any third party library like boost which could help me to get around this ?
Thank you for reading this !
Anthony
| You can't instantiate abstract classes, thus a vector of abstract classes can't work.
You can however use a vector of pointers to abstract classes:
std::vector<IFunnyInterface*> ifVec;
This also allows you to actually use polymorphic behaviour - even if the class wasn't abstract, storing by value would lead to the problem of object slicing.
|
2,160,935 | 2,164,881 | Programmatically fetch GPU utilization | Is there a standard way of getting the current load on the GPU? I'm looking for something similar to the Task Manager showing CPU%. Utilities such as GPU-Z show this value but I'm not sure how it gets this. I'm specifically interested in AMD graphics cards at the moment, any pointers would be helpful.
If there's no clean API way of doing it, are there any programs whose output I can capture to get this info?
| For AMD/ATI cards, check out GPU PerfStudio. http://developer.amd.com/gpu/Pages/default.aspx
For NVidia cards, look at PerfHUD. http://developer.nvidia.com/object/nvperfhud_home.html
There is also a more generic tool in the DirectX SDK from MS called Pix that overlaps partially with these tools.
AFAIK there's no way to get something as simple as a %-use number for the GPU because it isn't that simple. But these tools will help in debugging and profiling what's going on in the GPU. Both ATI and NVidia provide public documentation with recommended steps to find and fix specific types of GPU bottlenecks.
|
2,161,002 | 2,161,025 | Restricting the size of an array when passed to a function | Is there anyway to restrict the size of an array when passed as an argument to a function?
I mean is something like this possible?
/*following will lead to compile time error */
template<typename T, size_t n>=20> // or template<typename T,size_t n<=20>
void func(T (&a)[n])
{
// do something with a
}
I want the size of my array to be at least(or at most) n(n can have any value).
For example:
When n=20 I must pass an array with at least(or at most) 20 elements. Is there any way in C++ for this?
| You can simply make the requirement a static assertion - e.g. with Boosts static assert:
template<typename T, size_t n>
void func(T (&a)[n]) {
BOOST_STATIC_ASSERT(n >= 20);
// ...
}
A basic custom implementation (not solving the problem of using it more then once per scope) might look like the following:
template<bool b> struct StaticAssert;
template<> struct StaticAssert<true> {};
#define STATIC_ASSERT(x) StaticAssert<(x)> static_asserter
If you want different behaviour if the requirement is met, use something like enable_if or tag-based specialization. Example using enable_if:
template<class T, size_t n>
typename boost::enable_if<(n >= 20), void>::type
func(T (&a)[n]) { /* ... */ }
template<class T, size_t n>
typename boost::disable_if<(n >= 20), void>::type
func(T (&a)[n]) { /* ... */ }
|
2,161,397 | 2,161,474 | Is this ambiguous or is it perfectly fine? | Is this code ambiguous or is it perfectly fine (approved by standards/has consistent behavior for any compilers in existence)?
struct SCustomData {
int nCode;
int nSum;
int nIndex;
SCustomData(int nCode, int nSum, int nIndex)
: nCode(nCode)
, nSum(nSum)
, nIndex(nIndex)
{}
};
edit:
yes, I am referring to the fact that the member variables have the same name with formal parameters of the constructor.
| No, in this case there are no ambiguity, but consider following:
struct SCustomData {
//...
void SetCode(int nCode)
{
//OOPS!!! Here we do nothing!
//nCode = nCode;
//This works but still error prone
this->nCode = nCode;
}
};
You should draw attention to one of existing coding styles. For instance General Naming Rule in Google C++ Coding Styles or read excellent book "C++ Coding Standards: 101 Rules, Guidelines, and Best Practices" by Herb Sutter and Andrei Alexandrescu.
|
2,161,410 | 2,161,429 | Big Endian and Little Endian for Files in C++ | I am trying to write some processor independent code to write some files in big endian. I have a sample of code below and I can't understand why it doesn't work. All it is supposed to do is let byte store each byte of data one by one in big endian order. In my actual program I would then write the individual byte out to a file, so I get the same byte order in the file regardless of processor architecture.
#include <iostream>
int main (int argc, char * const argv[]) {
long data = 0x12345678;
long bitmask = (0xFF << (sizeof(long) - 1) * 8);
char byte = 0;
for(long i = 0; i < sizeof(long); i++) {
byte = data & bitmask;
data <<= 8;
}
return 0;
}
For some reason byte always has the value of 0. This confuses me, I am looking at the debugger and see this:
data = 00010010001101000101011001111000
bitmask = 11111111000000000000000000000000
I would think that data & mask would give 00010010, but it just makes byte 00000000 every time! How can his be? I have written some code for the little endian order and this works great, see below:
#include <iostream>
int main (int argc, char * const argv[]) {
long data = 0x12345678;
long bitmask = 0xFF;
char byte = 0;
for(long i = 0; i < sizeof(long); i++) {
byte = data & bitmask;
data >>= 8;
}
return 0;
}
Why does the little endian one work and the big endian not? Thanks for any help :-)
| In your example, data is 0x12345678.
Your first assignment to byte is therefore:
byte = 0x12000000;
which won't fit in a byte, so it gets truncated to zero.
try:
byte = (data & bitmask) >> (sizeof(long) - 1) * 8);
|
2,161,462 | 2,161,501 | C++ inheritance and function overriding | In C++, will a member function of a base class be overridden by its derived class function of the same name, even if its prototype (parameters' count, type and constness) is different? I guess this a silly question, since many websites says that the function prototype should be the same for that to happen; but why doesn't the below code compile? It's a very simple case of inheritance, I believe.
#include <iostream>
using std::cout;
using std::endl;
class A {};
class B {};
class X
{
public:
void spray(A&)
{
cout << "Class A" << endl;
}
};
class Y : public X
{
public:
void spray(B&)
{
cout << "Class B" << endl;
}
};
int main()
{
A a;
B b;
Y y;
y.spray(a);
y.spray(b);
return 0;
}
GCC throws
error: no matching function for call to `Y::spray(A&)'
note: candidates are: void Y::spray(B&)
| The term used to describe this is "hiding", rather than "overriding". A member of a derived class will, by default, make any members of base classes with the same name inaccessible, whether or not they have the same signature. If you want to access the base class members, you can pull them into the derived class with a using declaration. In this case, add the following to class Y:
using X::spray;
|
2,161,567 | 2,230,857 | I need a tree dump option, which doesn't exist any more in current gcc versions | Older versions of GCC (for example 4.0.2 or 4.1.2) had the option -df (see Options for Debugging Your Program or GCC for 4.1.2). I used this option to dump the files filename.c.134r.life2 and filename.c.126r.life1, because I want to extract some values out of these files (for example the register count for every method).
The problem is, that in current versions of GCC (for example, 4.2.2) this option doesn't exist any more. There are other options and the tree dump with the name filename.c.135r.jump is pretty much the same. But the register count is missing in this dump, too and I couldn't find a dump which has that values.
Is there still a parameter, which gives me the old dumps in current GCC versions?
| GCC 4.2-4.3 does really have the dump_flow_info function, which reports number of register used.
I'll search, how it can be called. Oh, yes:
gcc-4.3.1 file.c -fdump-rtl-all-all
produces
file.c.175r.lreg
with
file.c.175r.lreg:81 registers.
More specific option: -fdump-rtl-lreg-all. It was wested with 4.3.
|
2,161,770 | 2,161,802 | Visual C++ Automatically Appending A or W to end of Function | In C++ I have defined a class that has this as a member:
static const std::basic_string<TCHAR> MyClass_;
There is also a getter function for this value:
LPCTSTR CClass::GetMyClassName()
{
return MyClass_.c_str();
}
When I create an instance of this class and then try and access it intellisense pops up but the name has been changed depending on whether the project has been compiled for Unicode or Multibyte. If it has been compiled for Unicode the function appears as:
aClass.GetMyClassNameW();
else it is:
aClass.GetMyClassNameA();
What I'd like to know is how is the name getting changed?
Also I would like to know is it possible for intellisense to show the correct name of the function? So that I can access it like this:
aClass.GetMyClassName()
EDIT: The precise member function name I've used in my code is:
WinClass::GetClassName()
| Your method name is literally "GetMyClassName" or is it "GetClassName"?
GetClassName is in the SDK (winuser.h) and is redefined based on the UNICODE defines. If you are using "GetClassName" the intellisense is probably getting confused; in fact the compiler is generating the A/W suffix for the actual compiled method as well but that would all work because everyone (Linker/Compiler) agrees on the redefined name (even if its not visible).
|
2,161,940 | 2,161,947 | Two enums have some elements in common, why does this produce an error? | I have two enums in my code:
enum Month {January, February, March, April, May, June, July,
August, September, October, November, December};
enum ShortMonth {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
May is a common element in both enums, so the compiler says:
Redeclaration of enumerator 'May'.
Why does it say so? And how can I circumvent this?
| Enum names are in global scope, they need to be unique. Remember that you don't need to qualify the enum symbols with the enum name, you do just:
Month xmas = December;
not:
Month xmas = Month.December; /* This is not C. */
For this reason, you often see people prefixing the symbol names with the enum's name:
enum Month { Month_January, Month_February, /* and so on */ };
|
2,162,016 | 2,162,124 | How do I treat a pointer as a multi array? | I have this loop which gives seg. fault.
s->c = malloc(width * height * sizeof(double));
if (s->c == NULL) { puts("malloc failed"); exit(1); }
for (int n = 0; n < width; n++) {
for (int m = 0; m < height; m++) {
d = (&s->c)[m][n];
printf("d %f\n", d);
printf("m %i\n", m);
printf("n %i\n", n);
}
}
Inside s->c is:
double* c;
When executed it just outputs:
d 27.000000
m 0
n 0
and then seg. fault.
It worked when I treated the s->c as a 1D array, but I would really like to treat it as a 2D array.
Is that possible, when the c pointer is in a struct?
If so, is (&s->c)[m][n] then the correct way to access the elements?
Sandra
| The problem is that the compiler doesn't know the dimensions of your matrix.
When you have: double tab[m][n] you can access the element tab[row][col] as *(tab + (row * n) + col)
In your case you only have double *tab; that can be considered as the pointer to the element tab[0][0] with no information on the matrix dimensions and the compiler can't compute the right address.
You could compute the address yourself (for example using a macro) but would lose the nice tab[x][y] syntax.
I`m surprised it compiles. You should have received at least a warning about implicitly casting a double to a pointer.
|
2,162,022 | 2,162,116 | Downloading all files in directory using libcurl | I am new to the libcurl and found a way to download a single file from the ftp server. Now my requirement is to download all files in a directory and i guess it was not supported by libcurl. Kindly suggest on libcurl how to download all files in directory or is there any other library similar to libcurl?
Thanks in advance.
| You need the list of files on the FTP server. Which isn't straightforward as each FTP server might return a different format of file listing...
Anyway, the ftpgetresp.c example shows a way to do it, I think. FTP Custom CUSTOMREQUEST suggests another way.
|
2,162,099 | 2,186,504 | Winsock accept event sometimes stops signaling (WSAEventSelect) | I have a problem with a piece of legacy c++/winsock code that is part of a multi-threaded socket server. The application creates a thread that handles connections from clients, of which there are typically a couple of hundred connected at any one time. It typically runs without a problem for several days (continuously), and then suddenly stops accepting connections. This only happens in production, never test.
It uses WSAEventSelect() to detect FD_ACCEPT network events. The (simplified) code for the connection handler is:
SOCKET listener;
HANDLE hStopEvent;
// ... initialise listener and hStopEvent, and other stuff ...
HANDLE hAcceptEvent = WSACreateEvent();
WSAEventSelect(listener, hAcceptEvent, FD_ACCEPT);
HANDLE rghEvents[] = { hStopEvent, hAcceptEvent };
bool bExit = false;
while(!bExit)
{
DWORD nEvent = WaitForMultipleObjects(2, rghEvents, FALSE, INFINITE);
switch(nEvent)
{
case WAIT_OBJECT_0:
bExit = true;
break;
case WAIT_OBJECT_1:
HandleConnect();
WSAResetEvent(hAcceptEvent);
break;
case WAIT_ABANDONED_0:
case WAIT_ABANDONED_0 + 1:
case WAIT_FAILED:
LogError();
break;
}
}
From detailed logging I know that, when the problem occurs, the thread enters WaitForMultipleObjects() and never emerges, even though there are clients attempting to connect and waiting for an accept. The WAIT_FAILED and WAIT_ABANDONED_x conditions never occur.
While I haven't ruled-out a config problem on the server, or even some kind of resource leak (can't find anything), I am also wondering if the event created by WSACreateEvent() is somehow being 'dissassociated' from the FD_ACCEPT network event - causing it to never fire.
So, am I doing something wrong here? Is there something I should be doing that I'm not? Or a better way? I'd appreciate any suggestions! Thanks.
EDIT
The socket is a non-blocking socket.
EDIT
Problem solved by using the approach suggested by kipkennedy (below). Changed hAcceptEvent to be an auto-reset event, and removed the call to WSAResetEvent() which was no-longer needed.
| Maybe an FD_ACCEPT is signaling during HandleConnect() after the accept() and before the return and subsequent ResetEvent(). Then, ResetEvent() ends up resetting all signals and no re-enabling accept() is ever called. For example, the following sequence is possible:
Event signaled, WaitForMultipleObjects() returns
During HandleConnect(), sometime after accept() is called, the Event is signaled again
HandleConnect() returns
ResetEvent() resets the event, masking the second signal
WaitForMultipleObjects() never returns since as far as Windows is concerned, it has already signaled the subsequent event and no subsequent accepts() have re-enabled it
A couple possible solutions: 1) loop on accept() in HandleConnect() until WSAEWOULDBLOCK is returned 2) use an auto-reset event or immediately reset the event before calling HandleConnect()
|
2,162,390 | 2,167,897 | iconv encoding conversion problem | I am having trouble converting strings from utf8 to gb2312. My convert function is below
void convert(const char *from_charset,const char *to_charset, char *inptr, char *outptr)
{
size_t inleft = strlen(inptr);
size_t outleft = inleft;
iconv_t cd; /* conversion descriptor */
if ((cd = iconv_open(to_charset, from_charset)) == (iconv_t)(-1))
{
fprintf(stderr, "Cannot open converter from %s to %s\n", from_charset, to_charset);
exit(8);
}
/* return code of iconv() */
int rc = iconv(cd, &inptr, &inleft, &outptr, &outleft);
if (rc == -1)
{
fprintf(stderr, "Error in converting characters\n");
if(errno == E2BIG)
printf("errno == E2BIG\n");
if(errno == EILSEQ)
printf("errno == EILSEQ\n");
if(errno == EINVAL)
printf("errno == EINVAL\n");
iconv_close(cd);
exit(8);
}
iconv_close(cd);
}
This is an example of how I used it:
int len = 1000;
char *result = new char[len];
convert("UTF-8", "GB2312", some_string, result);
edit: I most of the time get a E2BIG error.
| outleft should be the size of the output buffer (e.g. 1000 bytes), not the size of the incoming string.
When converting, the string length usually changes in the process and you cannot know how long it is going to be until afterwards. E2BIG means that the output buffer wasn't large enough, in which case you need to give it more output buffer space (notice that it has already converted some of the data and adjusted the four variables passed to it accordingly).
|
2,162,510 | 2,162,593 | strange template namespace problem | I've got a strange problem with templates and namespaces...
I have the following code which compiles fine..
using namespace boost::multi_index;
template < typename OT, typename KT, KT (OT::* KM)() const, typename KC, typename CMP >
class OrderBook
{
public:
OrderBook() {}
~OrderBook() {}
typedef multi_index_container<
OT,
indexed_by<
ordered_unique<
const_mem_fun< OT, KT, KM >,
KC
>,
ordered_unique<
identity< OT >,
CMP
>
>
> Container;
typedef typename Container::template nth_index< 0 >::type index_0;
typedef typename Container::template nth_index< 1 >::type index_1;
typedef typename index_0::const_iterator const_iterator_0;
typedef typename index_1::const_iterator const_iterator_1;
const_iterator_0 begin0() const { return _container.get<0>().begin(); }
const_iterator_0 end0() const { return _container.get<0>().end(); }
public:
Container _container;
};
However, due to a namespace collision when I insert this code into another project I have to have... (Notice how I've had to remove the using namespace boost::multi_index and manually specify it where needed
template < typename OT, typename KT, KT (OT::* KM)() const, typename KC, typename CMP >
class OrderBook
{
public:
OrderBook() {}
~OrderBook() {}
typedef boost::multi_index::multi_index_container<
OT,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<
boost::multi_index::const_mem_fun< OT, KT, KM >,
KC
>,
boost::multi_index::ordered_unique<
boost::multi_index::identity< OT >,
CMP
>
>
> Container;
typedef typename Container::template nth_index< 0 >::type index_0;
typedef typename Container::template nth_index< 1 >::type index_1;
typedef typename index_0::const_iterator const_iterator_0;
typedef typename index_1::const_iterator const_iterator_1;
const_iterator_0 begin0() const { return _container.get<0>().begin(); }
const_iterator_0 end0() const { return _container.get<0>().end(); }
public:
Container _container;
};
Which gives me the following error from g++.
In member function 'typename boost::multi_index::multi_index_container<OT, boost::multi_index::indexed_by<boost::multi_index::ordered_unique<boost::multi_index::const_mem_fun<OT, KT, KM>, KC, mpl_::na>, boost::multi_index::ordered_unique<boost::multi_index::identity<Value>, CMP, mpl_::na>, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na>, std::allocator<_CharT> >::nth_index<0>::type::const_iterator OrderBook<OT, KT, KM, KC, CMP>::begin0() const':
error: expected primary-expression before ')' token
In member function 'typename boost::multi_index::multi_index_container<OT, boost::multi_index::indexed_by<boost::multi_index::ordered_unique<boost::multi_index::const_mem_fun<OT, KT, KM>, KC, mpl_::na>, boost::multi_index::ordered_unique<boost::multi_index::identity<Value>, CMP, mpl_::na>, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na>, std::allocator<_CharT> >::nth_index<0>::type::const_iterator OrderBook<OT, KT, KM, KC, CMP>::end0() const':
error: expected primary-expression before ')' token
Sorry for the long error messages, I did consider cleaning them up but I thought I'd better leave them intact in case I removed something crucial.
I tried this...
typedef typename Container::template boost::multi_index::nth_index< 0 >::type index_0;
typedef typename Container::template boost::multi_index::nth_index< 1 >::type index_1;
and it just made g++ even madder :(
Any ideas?
| Prefix get<0>() with template:
const_iterator_0 begin0() const { return _container.template get<0>().begin(); }
const_iterator_0 end0 () const { return _container.template get<0>().end(); }
Similar to typename for dependent types, dependent templates have to be prefixed by template:
struct X {
template<class T> void f();
};
template<class T>
void test() {
T::f<int>(); // ill-formed
T::template f<int>(); // ok
}
// ...
test<X>();
And for the curious, that is §14.2/4:
When the name of a member template
specialization appears after . or ->
in a postfix-expression, or after
nested-name-specifier in a
qualified-id, and the
postfix-expression or qualified-id
explicitly depends on a
template-parameter (14.6.2), the
member template name must be prefixed
by the keyword template. Otherwise the
name is assumed to name a
non-template.
|
2,162,646 | 2,162,670 | Is there a C/C++ project similar to portablepython? | I've searched the internet for this but couldn't find anything useable, I was just wondering if there exists a C/C++ project similar to portablepython?
EDIT
I guess the question becomes: is there a portable C/C++ compiler I can stick onto a usb key?
| Python is an interpreter that can run "scripts" (.py files). Therefore portablepython makes sense - if you don't want to install Python everywhere, but still want to run the small Python files. This helps if the target PC doesn't have Python installed (or you can't even do it because of privileges).
For C/C++ this doesn't make much sense as these are compiled languages. Just compile them to executables and you have your "portability".
If you need to "program C/C++ anywhere", just place your favorite compiler and code editor on a USB stick, and you're done. portableapps is a nice place to find portable (as in "USB carry-able" applications), and it has this link for a portable C++ IDE/Compiler.
P.S. Python programs can also be bundled into (rather large) executables using tools like py2exe and PyInstaller.
|
2,162,819 | 2,162,881 | can someone help me translate this c++ code to c? | this is a magic square generator, but do not know C++, I have some difficulties to convert this code:
#include <vector>
#include <iostream>
using namespace std;
//There two series will be on even in case of magic square
// One of even order will be for multiple of 4
void BuildDoublyEvenMagicSquare(vector<vector<int> > &mat, int Order);
//Other of even order will be for multiple of 2
void SinglyEvenMagicSquare(vector<vector<int> > &mat, int order);
// For odd order
void BuildOddMagicSquare(vector<vector<int> > &mat, int Order);
// For odd order
void BuildOddMagicSquare(vector<vector<int> > &mat, int Order)
{
int SqrOfOrder = Order * Order;
int start=0, mid=Order/2; // start position
for (int loop=1; loop<=SqrOfOrder; ++loop)
{
mat[start--][mid++] = loop;
if (loop % Order == 0)
{
start += 2;
--mid;
}
else
{
if (mid==Order)
mid -= Order;
else if (start<0)
start += Order;
}
}
}
void BuildDoublyEvenMagicSquare(vector<vector<int> > &mat, int Order)
{
vector<vector<int> > A(Order, vector<int> (Order, 0));
vector<vector<int> > B(Order, vector<int> (Order, 0));
int i, j;
//Building of matrixes I and J
int index=1;
for (i=0; i<Order; i++)
for (j=0; j<Order; j++)
{
A[i][j]=((i+1)%4)/2;
B[j][i]=((i+1)%4)/2;
mat[i][j]=index;
index++;
}
for (i=0; i<Order; i++)
for (j=0; j<Order; j++)
{
if (A[i][j]==B[i][j])
mat[i][j]=Order*Order+1-mat[i][j];
}
}
void BuildSinglyEvenMagicSquare(vector<vector<int> > &mat, int order)
{
int ho=order/2;
vector<vector<int> > C(ho, vector<int> (ho, 0));
// For Order is Odd
if (order%2==1)
BuildOddMagicSquare(C, order);
// For Order is Even
else
{
//For Order is Doubly Even Order
if (order % 4==0)
BuildDoublyEvenMagicSquare(C, order);
//For Order is Singly Even Order
else
BuildSinglyEvenMagicSquare(C, order);
}
int i, j, k;
for (i=0; i<ho; i++)
for (j=0; j<ho; j++)
{
mat[i][j]=C[i][j];
mat[i+ho][j]=C[i][j]+3*ho*ho;
mat[i][j+ho]=C[i][j]+2*ho*ho;
mat[i+ho][j+ho]=C[i][j]+ho*ho;
}
if (order==2)
return;
vector<int> A(ho, 0);
vector<int> B;
for (i=0; i<ho; i++)
A[i]=i+1;
k=(order-2)/4;
for (i=1; i<=k; i++)
B.push_back(i);
for (i=order-k+2; i<=order; i++)
B.push_back(i);
int temp;
for (i=1; i<=ho; i++)
for (j=1; j<=B.size(); j++)
{
temp=mat[i-1][B[j-1]-1];
mat[i-1][B[j-1]-1]=mat[i+ho-1][B[j-1]-1];
mat[i+ho-1][B[j-1]-1]=temp;
}
i=k;
j=0;
temp=mat[i][j]; mat[i][j]=mat[i+ho][j]; mat[i+ho][j]=temp;
j=i;
temp=mat[i+ho][j]; mat[i+ho][j]=mat[i][j]; mat[i][j]=temp;
}
int main()
{
int Order;
cout<<"Enter the order of square which you wanna: ";
cin>>Order;
vector<vector<int> > mat(Order, vector<int> (Order, 0));
// For order less than 3 is meaningless so printing error
if (Order<3)
{
cout<<" Order Of Square must be greater than 2";
return -1;
}
// For Order is Odd
if (Order%2==1)
BuildOddMagicSquare(mat, Order);
// For Order is Even
else
{
//For Order is Doubly Even Order
if (Order % 4==0)
BuildDoublyEvenMagicSquare(mat, Order);
//For Order is Singly Even Order
else
BuildSinglyEvenMagicSquare(mat, Order);
}
// Display Results
for (int i=0; i<Order; i++)
{
for (int j=0; j<Order; j++)
{
cout<< mat[i][j]<<" " ;
}
cout<<endl;
}
return 0;
}
for example, how can I write this function call in C?
void BuildDoublyEvenMagicSquare(vector<vector<int> > &mat, int Order);
and what vector<vector<int> > &mat means?
@Omnifarious
can i use something like this?
int **mat:
*mat = (int **)malloc(sizeof(int*)*Order);
for (int i=0;i<Order;i++)
mat[i] = (int *)malloc(sizeof(int)*Order);
| For the last part of the question, in C that function prototype would look like this if you follow the rest of my advice:
void BuildDoublyEvenMagicSquare(int *mat, int Order);
There are actually several ways you could do it. There are some things being done here that simply can't be done in C, so you'll have to sort of go for a slightly different approach. The biggest thing is the C++ vector's. A C++ vector is like a C array, but it does all the memory management for you. This means, for example, that it's fairly convenient to have an array of arrays where in C it would just add to your resource management headache.
The C++ declaration:
vector<int> varname(5);
is roughly equivalent to the C declaration:
int varname[5];
But in C++ you can do this:
int randominteger = 7;
vector<int> varname(randominteger);
and in C this is illegal unless you have a C99 compliant compiler (-std=c99 in gcc):
int randominteger = 7;
int varname[randominteger];
You can't have arrays with variable numbers of elements in C, so you have to resort to calloc or malloc and do your own memory management, like this:
/* Not that this is not necessary and shouldn't be done (as it's *
* prone to memory leaks) if you have a C99 compliant compiler. */
int randominteger = 7;
int *varname = calloc(randominteger, sizeof(int));
if (varname == NULL) {
/* Die horribly of running out of memory. */
}
In this case, I'm assuming that you're going to unfold your array of arrays into a single long C array of integers large enough to hold the answer so you can reduce the number of bits of memory you have to manage. To accomplish this, I would use a call like mat = calloc(order * order, sizeof(int)); in main, which also means you'll have to call free(mat) when you're finished with it at the end of main.
I'm also assuming that you're unfolding the array so that you no longer have an array of arrays. That means you'll have to be doing some math to turn a row,column index into a linear index into the array. Something like row * order + column.
You'll have to repeat the procedure I suggested for main in each of the functions that build a magic square because they each create temporary arrays to hold stuff in that go away at the end of the function.
|
2,163,090 | 2,163,132 | When I kill a pThread in C++, do destructors of objects on stacks get called? | I'm writing a multi-threaded C++ program. I plan on killing threads. However, I am also using a ref-counted GC. I'm wondering if stack allocated objects get destructed when a thread gets killed.
| The stack does not unwind when you 'kill' a thread.
Killing threads is not a robust way to operate - resources they have open, such as files, remain open until the process closes. Furthermore, if they hold open any locks at the time you close them, the lock likely remains locked. Remember, you are likely calling a lot of platform code you do not control and you can't always see these things.
The graceful robust way to close a thread is to interrupt it - typically it will poll to see if it's been told to close down periodically, or it's running a message loop and you send it a quit message.
|
2,163,365 | 2,163,386 | WinAPI for Game Controllers | I know that all windows platforms automatically detect when a game controller is connected. I also know there is a WinAPI for polling these controllers. I can't seem to find the functions I am looking for anywhere.
Any help is greatly appreciated!
Brendan
| You can use either DirectInput or XInput from the DirectX SDK.
|
2,163,632 | 2,163,657 | hooking on WM_SETTEXT message | I have setup a hook on WM_SETTEXT message using WH_CALLWNDPROC.
In hook procedure
CWPSTRUCT* info = (CWPSTRUCT*) lParam;
switch(info->message)
{
case WM_SETTEXT:
break;
}
Now in the above code how can I get the string that is passed along WM_SETTEXT message?
I am not able to get this information anywher..
| The lParam passed to WM_SETTEXT contains the string, so info->lParam should have the info you want.
|
2,163,853 | 2,163,875 | How can I display variable strings using C++ and PDCurses? | I'm extremely sorry to post such an embarrassingly newbish question, but I haven't mucked around much with C++ since my college days and I think at some point I drank all that I knew about pointers and C++ strings right out of my head. Basically, I'm creating a C++ console app (a roguelike, to be precise) with PDCurses to handle output. I want to display dynamic strings (something that I figure would be pretty useful in a dynamic game, heh) but mvaddstr() keeps throwing me errors. Here's an example of what I'm trying to do:
string vers = "v. ";
vers += maj_vers;// + 48;
vers += ".";
vers += min_vers;// + 48;
vers += ".";
vers += patch_vers;// + 48;
char *pvers = vers.c_str();
mvaddstr(5,17, pvers);
refresh();
Of course, this gives me an "Invalid conversion from const char*' tochar*'" error on the char *pvers definition. I know I'm doing something really brazenly, stupidly wrong here but I'm really rusty on this. Any help would be super helpful.
| Just declare pvers as:
const char *pvers = vers.c_str();
This const means you aren't going to modify the memory pointed to by pvers. It's really more of a hint so that the compiler can yell at you if you break this assumption. (Which is why you got the compiler warning.) You might start to see something funky if you use pvers after changing vers beyond this line, but for the snippet you posted I don't see that problem.
|
2,163,892 | 2,164,039 | API to use deault Web Cam? | I'm working on a Win32 application in C++ and would like to add the ability to output the default web cam onto the screen. I was wondering if there was a Win32 API for this, or a way to do this without coding the whole thing.
Thanks
| Yes, it is really simple with capCreateCaptureWindow. That googles really well, you'll have no trouble finding code samples.
|
2,164,001 | 2,164,122 | Installing C/C++ libraries on Windows | I'm studying (well, trying to) C right now, but I'm limited to working in Windows XP. I've managed to set up and learn how to use Emacs and can compile simple C programs with gcc (from Emacs no less!), but I'm getting to the point where I'd like to install something like SDL to play around with it.
The thing is that the installation instructions for SDL indicate that, on a Win32 environment using MingW, I would need to use MSYS to run ./configure and make/make install to install SDL, like one would do on Linux. I noticed that when I unzipped the SDL-dev package (forgot the exact name, sorry) there were folders there that corresponded to a folder in the MinGW directory (SDL/include -> MinGW/include).
Am I right in saying that all the ./configure and make commands do is move these files from one directory to another? Couldn't I just move those files by hand and spare myself the trouble of installing and configuring MSYS (which, to be honest, confuses me greatly)?
| The build process usually works like this: the configure script finds the appropriate settings for the compilation (like which features to enable, the paths to the required libraries, which compiler to use etc.) and creates a Makefile accordingly. make then compiles the source code to binaries. make install copies the created binaries, the headers, and the other files that belong to the library to the appropriate places.
You can't just copy the files from the source archive, because the source archive does not contain the binary files (or any other files that are created during the make step), so all you'd copy would be the headers, which aren't enough to use the library.
|
2,164,095 | 2,164,155 | Static variables in instance methods | Let's say I have this program:
class Foo {
public:
unsigned int bar () {
static unsigned int counter = 0;
return counter++;
}
};
int main ()
{
Foo a;
Foo b;
}
(Of course this example makes no sense since I'd obviously declare "counter" as a private attribute, but it's just to illustrate the problem).
I'd like to know how C++ behaves in this kind of situation: will the variable "counter" in the bar() method be the same for every instance?
| Yes, counter will be shared across all instances of objects of type Foo in your executable. As long as you're in a singlethreaded environment, it'll work as expected as a shared counter.
In a multithreaded environment, you'll have interesting race conditions to debug :).
|
2,164,276 | 2,204,671 | Compiling OpenCV for Visual C++ 9.0 | I looked at many places but could not find anything telling me how to buld the lib files. I know how to link them, but openCV install folder only contains .a files. I cant find an sln file or dsp. How can I make the lib files? Right now all the samples get linker problems because the lib files dont exist.
Thanks
| The Windows installer (.exe) for OpenCV 2.0 does not come with the binaries pre-built for vc++, nor does it have the .vcproj files for using vc++ to build them. You need to have cmake, which is available for free on the web. I used the GUI. Use that to build .vcproj files with which you can compile everything in VC++ 2008 or whatever. There are some gotchas. The question has been asked and answered.
|
2,164,360 | 2,164,375 | am i implementing this template class correctly? | Okay, I'm trying to implement a templated class of an array-based queue called Queue.
Here's how I did it. First, is this the right way to implement a templated class?
The problem is, when I try to compile, I get the error messages
undefined reference to
'Queue::Queue()'
undefined reference to
'Queue::~Queue()'
Any ideas what's wrong? Am I declaring it wrong or implementing it wrong?
queue.h
#ifndef __QUEUE_H__
#define __QUEUE_H__
template <class T>
class Queue
{
int first;
T* array;
public:
Queue();
~Queue;
void enqueue(T next);
T dequeue();
bool is_empty();
bool is_full();
};
#endif
queue.cpp
#include "queue.h"
template <class T> Queue<T>::Queue(){
...
}
template <class T> Queue<T>::~Queue(){
...
}
template <class T> void Queue<T>::enqueue(T next){
...
}
template <class T> T Queue<T>::dequeue(){
...
}
template <class T> bool Queue<T>::is_empty(){
...
}
template <class T> bool Queue<T>::is_full(){
...
}
main.cpp
#include "queue.h"
#include <iostream>
using namespace std;
int main(){
Queue<int> test;
return 0;
}
| Several issues:
The cause of your problem - C++ does not really support splitting templates into .h and .cpp files - you need to put everything in the header
The name __QUEUE_H__ is reserved for the C++ implementation, as are all names that contain double-underscores or begin with an underscore and an uppercase letter. You are not allowed to create such names in your own code.
You probably will find it more convenient to implement the queue in terms of a std::deque, rather than a C-style array
I assume you are doing this as a learning exercise, but if not you should know that the C++ Standard Library already contains a std::queue template class.
|
2,164,365 | 2,164,454 | Algorithm for searching for an image in another image. (Collage) | Is this even possible? I have one huge image, 80mb with a lot of tiny pictures. They are tilted and turned around as well. How can i search for an image with programming? I know how to use java and c++. How would you go about this?
| One algorithm I've used before is SIFT. If you're interested in implementing the algorithm for yourself, you can see course notes for CPSC 425 at UBC, which describes in gentle detail how to implement SIFT in MATLAB. If you just want code that does this, take a look at VLFeat, a C library that does SIFT and a number of other algorithms.
Quotation from Jerry Coffin:
Edit: Quite true -- it is patented, and I probably should have mentioned that to start with. In case anybody care's it's US patent # 6,711,293.
|
2,164,373 | 2,164,630 | A scripting language to simply compile | I'm looking for a simple script language which I can compile easily by just
putting the .h files under an include folder and the .c/.cpp files under a source directory. Something without any Makefile.
Must be written in C/C++ rather C++.
Okay so LUA doesn't work, I need something which I can just call a simple method and it will handle a script file. Without any load from file methods in it, or atleast something which doesn't use the stdio.h.
| Lua is a simple lightweight scripting language that can be easily embedded into your application. It is written in C (I don't really understand what you mean by "Must be written in C/C++ rather C++").
You can simply add all files from the src directory except for lua.c and luac.c into your project and it should work.
Note that if you're including from a C++ file, you have to wrap includes in extern "C" block. The following compiles and links for me.
extern "C" {
#include <lua.h>
#include <lauxlib.h>
}
int main()
{
lua_State* L = lua_open();
}
|
2,164,376 | 2,184,609 | Counter in AS3 "without dynamic text field" | What is the best way to program an LED number tick. I need to have a number display that goes up to 1,000,000.00. Dynamic text fields are not an option because of symbol instances. How would I make a counter?
ANIMATION
The numbers move in increments like an LED display. This
NUMBERS
The numbers multiple by ten each space over
decimal point numbers are not whole, so they go really fast
There's a 16,000 frame limit in flash
SYMBOLS
column of numbers that moves in increments, for each number place
WHAT WOULD IT REQUIRE?
numbers move at a rate in multiples of 10
decimal points times one hundred
FRAME BASED OR TIME BASED?
There's a 16,000 frame limit in Flash
Time based method would require a lot of code
the add and remove child issue
alt text http://www.ashcraftband.com/myspace/videodnd/number_example.jpg
TRANSITION EFFECT
A "tick"
move 10 pixels each time etc.
9 and 0 roll over smoothly
| In Flash, and to achieve the result in your picture there, I would create 2 MovieClips:
A black bar with a decimal point
The grey digits in a column, 0 -> 0, as suggested by your pic
Then, combine the black bar and 9 of the digit columns into a single MovieClip to represent your counter, along with a custom base class for it. This allows you fine-grained control over the entire counter.
Provide a CounterClip::Step() or ::Tick() method (or whatever you want to call it) that can move the individual columns. You can use the flash.transitions.Tween class to create smooth animations (I think thats what it's called... I'm a bit rusty.)
If you find you need more than the 9 columns, you can change your Counter MovieClip class to support dynamically adding more digits.
|
2,164,634 | 2,164,715 | Program Interaction and testing via bash script | I've just completed the coding section of simple homework assignment for my C++ class. The second part of the assignment requires us to verify our code's input validation. (The program takes several different values as inputs from a user and prints those values to a file)
I was hoping that I could use bash script for this. Is there any way to use bash script to run and interact with a program? How can I put the program's output into a variable (note that program has a series of input requests and outputs).
Thanks
| To build on @Travis' answer, create two files: one holds your inputs (input.txt) and one holds the expected output (expected_output.txt). Then do the following:
./myprogram <input.txt >output.txt
diff output.txt expected_output.txt
If the diff command has any output, there's a problem.
|
2,164,635 | 2,164,700 | Calculating a gradient fill's start and end colours given a base colour | I have a WTL C++ application and I want the user to be able to select different colours for some of the UI elements and apply a gradient fill using the GradientFill API call. However, instead of letting the user pick the start and end colours for the gradient, I'd like them to be able to select a 'base' colour and for my application to calculate suitable start/end colours automatically. I want to end up with a fill that is similar to the one Windows uses for various themed elements. The base colour could be the 'middle' colour of the gradient with my application somehow computing a slightly lighter colour for the gradient start and a slightly darker colour for the gradient end. Alternatively I could use the base as the start colour and compute the end or vice-versa.
I'm sure this would be relatively easy with some RGB macro magic but I really don't know where to start. Any ideas would be welcome.
| The RGB color space is not suitable for this. Use HSL or HSV: it is easy to auto-generate a good looking gradient by varying an individual component. Converting from HSL/V to an RGB triplet you can use in the API is simple.
|
2,164,720 | 2,165,685 | Collisions in a real world application | Here's my problem. I'm creating a game and I'm wondering about how to do the collisions. I have several case to analyze and to find the best solution for.
I'll say it beforehand, I'm not using any third party physics library, but I'm gonna do it in house. (as this is an educational project, I don't have schedules and I want to learn)
I have 2 types of mesh for which I have to make the collisions for :
1) Static Meshes (that move around the screen, but does not have ANY animation)
2) Skinned/Boned Meshes (animated)
Actually I have this solution (quite hacky :|)
First of all I have a test against some bounding volume that enclose the full mesh (capsule in my case), after :
1) For the static meshes I divide them manually in blocks (on the modeler) and for each of these blocks i use a sphere/AABB test. (works fine, but its a little messy to slice every mesh :P) (i tried an automatic system to divide the mesh through planes, but it gives bad results :()
2) For the animated mesh ATM i'm dividing the mesh at runtime into x blocks (where x is the number of bones). Each block contain the vertex for which that bone is the major influencer. (Sometimes works, sometimes gives really bad results. :|)
Please note that the divide of the mesh is done at loading time and not each time (otherwise it would run like a slideshow :D)
And here's the question :
What is the most sane idea to use for those 2 case?
Any material for me to study these methods? (with some sourcecode and explanations would be even better (language is not important, when i understand the algorithm, the implementation is easy))
Can you argument why that solution is better than others?
I heard a lot of talk about kd-tree, octree, etc..while I understand their structure I miss their utility in a collision detection scenario.
Thanks a lot for the answers!!!
EDIT : Trying to find a K-Dop example with some explanation on the net. Still haven't found anything. :( Any clues?
I'm interested on HOW the K-Dop can be efficiently tested with other type of bounding volumes etc...but the documentation on the net seems highly lacking. :(
| The most common approaches used in many current AAA games is "k-DOP" simplified collision for StaticMeshes, and a simplified physical body representation for the SkeletalMeshes.
If you google for "kDOP collision" or "discrete orientation polytopes" you should find enough references. This is basicly a bounding volume defined of several planes that are moved from outside towards the mesh, until a triangle collision occurs. The "k" in kDOP defines how many of these planes are used, and depending on your geometry and your "k" you can get really good approximations.
For SkeletalMeshes the most common technique is to define simple geometry that is attached to specific bones. This geometry might be a box or a sphere. This collision-model than can be used for quite accurate collision detection of animated meshes.
If you need per-triangle collision, the "Separating Axis Theorem" is the google-search term of your choice. This is usefull for specific cases, but 75% of your collision-detection needs should be covered with the above mentioned methods.
Keep in mind, that you most probably will need a higher level of early collision rejection than a bounding-volume. As soon as you have a lot of objects in the world, you will need to use a "spatial partitioning" to reject groups of objects from further testing as early as possible.
|
2,164,827 | 2,164,853 | Explicitly exporting shared library functions in Linux | Is there a Linux equivalent of __declspec(dllexport) notation for explicitly exporting a function from a shared library? For some reason with the toolchain I'm using, functions that aren't class members don't appear in the resulting shared library file.
| __attribute__((visibility("default")))
And there is no equivalent of __declspec(dllimport) to my knowledge.
#if defined(_MSC_VER)
// Microsoft
#define EXPORT __declspec(dllexport)
#define IMPORT __declspec(dllimport)
#elif defined(__GNUC__)
// GCC
#define EXPORT __attribute__((visibility("default")))
#define IMPORT
#else
// do nothing and hope for the best?
#define EXPORT
#define IMPORT
#pragma warning Unknown dynamic link import/export semantics.
#endif
Typical usage is to define a symbol like MY_LIB_PUBLIC conditionally define it as either EXPORT or IMPORT, based on if the library is currently being compiled or not:
#if MY_LIB_COMPILING
# define MY_LIB_PUBLIC EXPORT
#else
# define MY_LIB_PUBLIC IMPORT
#endif
To use this, you mark your functions and classes like this:
MY_LIB_PUBLIC void foo();
class MY_LIB_PUBLIC some_type
{
// ...
};
|
2,164,910 | 2,164,966 | is this a correct use of boost condition variables? | I wrote the following program for alternatively incrementing and doubling a counter(increment first) using boost condition variables. Can any one tell me if this is the correct use of boost condition variables. It is working correctly. I don't understand the use of lock in wait function call. What does condition.wait(lock) mean? For example what is the use of two scoped locks in increment and multiply in this program. How can I avoid them?
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/condition_variable.hpp>
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int counter=0;
boost::mutex m1,m2;
bool incremented=false,multiplied=false;
boost::condition_variable c1,c2;
void Increment()
{
{
boost::mutex::scoped_lock lk(m1);
counter++;
incremented = true;
c1.notify_one();
while(!multiplied)
c2.wait(lk);
multiplied=false;
}
}
void Multiply()
{
{
boost::mutex::scoped_lock lk(m2);
while(!incremented)
c1.wait(lk);
incremented = false;
counter = counter*2 ;
multiplied = true;
c2.notify_one();
}
}
void IncrementNtimes(int n){
for(int i=0;i<n;i++){
Increment();
}
}
void MultiplyNtimes(int n){
for(int i=0;i<n;i++){
Multiply();
}
}
int main(int argc, char* argv[])
{
srand ( time(NULL) );
boost::thread thrd1(boost::bind(&IncrementNtimes,20));
boost::thread thrd2(boost::bind(&MultiplyNtimes,20));
thrd1.join();
thrd2.join();
cout<<"Main counter is:"<<counter<<endl;
return 0;
}
| No, this is not correct. You're almost there, but the big problem is that the Multiply and Increment functions should be using the same mutex.
A mutex is an object that provides MUTual EXclusion. In other words, the point of a mutex is to prevent two threads from touching the same variable at the same time and causing unpredictable results. A mutex is kind of like a token that one thread at a time holds that gives it the "right" to access a certain variable (or set of variables). In this case, the variable you are trying to protect is counter. There must be one and only one mutex that controls the right to access counter. In your case, each thread will hold its own token that it thinks gives it the right to access counter, and so there will be unpredictable behavior.
You "hold" a mutex by locking it. That's the point of the locks, and that's why you cannot "avoid" them. The entire point of the scoped locks is that, assuming you have only one mutex m, when one of the threads holds the lock on m, the other thread is guaranteed to not also be holding a lock on m. If you've coded correctly, holding a lock on m should be a prerequisite for accessing counter, and so the value of counter should be predictable.
Now, regarding the wait(). A call to wait() means "I give up the lock on this mutex until someone else signals this condition, and then I want it back". In the mean time, the thread stops. So assuming you have only one mutex m and a condition c, and lk is a lock on m, the line c.wait(lk) means that the thread will give up the lock lk on mand then suspend execution until some other thread calls c.notify_one() (or c.notify_all()). When the waiting thread returns from the call to wait(), it will have automatically re-gained the lock lk on m and so is permitted to access counter again.
Finally, these boost locks are "scoped" locks. This means that they are released automatically on destruction (when they go out of scope). So in this case, each function holds its lock until it exits, except for times when it has given up its lock to wait and has suspended execution pending a signal.
|
2,164,932 | 2,164,946 | Adding layout to another layout in Qt [C++] | Could anyone tell me why I'm getting error and how to fix it?
QGridLayout* mainLayout = new QGridLayout;
QGridLayout *leftLayout = new QGridLayout;
QGridLayout *rightLayout = new QGridLayout;
mainLayout->addLayout(leftLayout);
mainLayout->addLayout(rightLayout);
setLayout(mainLayout);
error I'm getting:
'error: no matching function for call to 'QGridLayout::addLayout(QGridLayout*&)'
Thank you for any help.
| Qt4 Reference says:
void addLayout ( QLayout * layout, int
row, int column, Qt::Alignment
alignment = 0 )
So you have to do:
mainLayout->addLayout(leftLayout, 0, 0);
mainLayout->addLayout(rightLayout, 0, 1);
|
2,165,011 | 2,612,549 | Using OpenCV to detect a finger tip instead of a face | I'm using the facedetect example and going from there. Right now it only detects faces. Could someone point me in the direction to detect finger tips. Thanks
| Put a simple bright fluorescent sticker on the finger tip with a black dot in center or something like that. or even fashion a finger cap with a pattern printed on it which can be easily differentiated by the camera and your problem is very much solved.
|
2,165,030 | 2,165,051 | Use Boost to get arity and paramerter types of member function? (boost::function_traits) | It works just fine, for plain vanilla functions. The code below works just fine. It prints just what is should:
int __cdecl(int, char)
2
int,char
#include <boost/type_traits.hpp>
#include <boost/function.hpp>
#include <boost/typeof/std/utility.hpp>
#include <iostream>
using std::cout;
using std::endl;
int foo(int, char) {
return 0;
}
int main() {
typedef BOOST_TYPEOF(foo) foo_type;;
typedef boost::function_traits<foo_type> function_traits;
cout << typeid(foo_type).name() << endl;
cout << function_traits::arity << endl;
cout << typeid(function_traits::arg1_type).name() << ",";
cout << typeid(function_traits::arg2_type).name() << endl;
return 0;
}
So, the question is, how can one do this if foo is a member function of class bar?
struct bar {
int foo(int, char) { return 0; }
};
I have tried countless combinations of these constructs: BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() BOOST_TYPEOF_REGISTER_TYPE() boost::ref boost::remove_pointer boost::bind boost::mem_fn
etc., etc... No joy.
| Boost Function Types would probably be the natural solution:
#include <boost/function_types/function_type.hpp>
#include <boost/function_types/parameter_types.hpp>
#include <boost/function_types/function_arity.hpp>
#include <boost/typeof/std/utility.hpp>
#include <boost/typeof/typeof.hpp>
#include <iostream>
struct bar {
int foo(int, char) { return 0; }
};
int main() {
typedef BOOST_TYPEOF(&bar::foo) foo_type;
std::cout << typeid(foo_type).name() << std::endl;
std::cout << boost::function_types::function_arity<foo_type>::value << std::endl;
std::cout << typeid(boost::mpl::at_c<boost::function_types::parameter_types<foo_type>,1>::type).name() << ",";
std::cout << typeid(boost::mpl::at_c<boost::function_types::parameter_types<foo_type>,2>::type).name() << ",";
return 0;
}
|
2,165,078 | 2,165,109 | A reference can not be NULL or it can be NULL? | I have read from the Wikipedia that:
“References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.”
But I don’t believe because of following code, look at it, compiler gives no error:
class person
{
public:
virtual void setage()=0;
};
int main()
{
person *object=NULL;
person &object1=*object;
}
Please elaborate this point.
| Saying person &object1=*object is not the same thing as saying person &object1=NULL. Probably the compiler is just not smart enough to find out that you are dereferencing null pointer, but you'll get a runtime error anyway. So they are kind of true still ;)
|
2,165,079 | 2,165,255 | gcc with parameters "-S -save-temps" puts intermediate files in current directory | The parameters -S -save-temps work fine, as long as i don't use them on files with the same name.
Think of the following situation: I have a project with a main directory and a subdirectory with the name subDir and in both of the directories are files placed with the name file.c. If I now call gcc -S -save-temps file.cpp subDir/file.c only one intermediate file with the name file.i will be generated.
That is the expected behaviour, as the man file of gcc tells me, that the intermediate files will always be placed in the current path, when using -save-temps.
My problem is, that I'm working on projects I don't know in advance. It could very well be, that someone constructed the above mentioned example in his Makefiles. In that case I would be stuck, because I need both intermediate files.
A few words to the system I'm constructing (for better understanding): My tool uses make --just-print to collect the calls, a make file of a project invokes. I scan these calls for compiler calls and add the -save-temps and -S options. The purpose is to get every preprocessed file, that is used in the process of compiling the project.
Do you have any ideas, how I'm able to get every preprocessed file, even if the above mentioned example should appear?
| There's no problem with file.cpp / file.c in different directories. GCC will create a *.ii and a *.i depending on the files' extension.
If they both have c||cpp you can use -E and receive only one *.i where you can search for the pragma # 1 "<FILE_PATH>" and extract it via a script.
|
2,165,223 | 2,165,243 | C++ Controlling destructor order for global objects | I've got a class (A) that accesses (indirectly via a static method) a static variable (an STL container) in another class (B) in its constructor and destructor.
A objects may be global, global constants, static members of another class, stored in other classes (which may themselves have global or static instances) or basically anywhere else a c++ object can be.
If an A object is constructed before the static members in B or destructed after the static members in B, it will cause a crash at some point (usually an access violation).
Is there some way to guarantee that all instances of class A (except those that have leaked, since by definition there "lost" and so wont be destructed any way) are constructed after and destructed before B's static variable?
I've seen some solutions for making a specific variable be constructed/destructed before/after another, however not a general case of all instances of a given type so am not sure how to approach this.
| No. This is known as the static-initialization fiasco. The order that objects get constructed prior to entering main is unspecified. The only guarantee is that it happens.
What you can do is lazy-initialize. This means your objects won't be initialized until you use them. Such as:
struct A { /* some data */ };
struct B { B(void){ /* get A's data */ } };
A& get_A(void)
{
static A instance;
return instance;
}
B& get_B(void)
{
static B instance;
return instance;
}
You use get_A and get_B to get the global instances. The part where B uses A should use get_A, and your use of B should be with get_B. Note the get_B is optional in your case.
What happens when B is first created? (Either globally or in the function) The constructor will call get_A and that's where A will be created. This let's you control the order things get constructed.
Note I think I reversed your A and B.
|
2,165,230 | 2,166,341 | Should I use DirectInput or Windows message loop? | I'm working on a C++ DirectX 2D game and I need keyboard and mouse input.
Wikipedia says:
Microsoft recommends that new applications make use of the Windows message loop for keyboard and mouse input instead of DirectInput
So how should I use it?
I have a GameScreen class whice take care of the drawing and the updating(game logic), I call the Draw and the Update methods inside a windows message loop.
Thanks
| Since you pretty much have to run a message pump in order to have a window, you might as well use that pump to handle keyboard and mouse input as well. It's entirely up to your pump whether you hand keyboard events on to a child window, you can handle them in the pump if you prefer.
Your typical message pump looks like this:
while (GetMessage(&msg, NULL, 0, 0))
{
if (WM_QUIT == msg.message)
break;
TranslateMessage(&msg); // post a WM_CHAR message if this is a WM_KEYDOWN
DispatchMessage(&msg); // this sends messages to the msg.hwnd
}
For a game, your pump might look more like this
while (true)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE | PM_NOYIELD))
{
bool fHandled = false;
if (msg.message >= WM_MOUSEFIRST && msg.message <= WM_MOUSELAST)
fHandled = MyHandleMouseEvent(&msg);
else if (msg.message >= WM_KEYFIRST && msg.message <= WM_KEYLAST)
fHandled = MyHandleKeyEvent(&msg);
else if (WM_QUIT == msg.message)
break;
if ( ! fHandled)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
// if there are no more messages to handle right now, do some
// game slice processing.
//
}
}
Of course, your actual pump will likely be even more complex than that, possibly with a MsgWaitForMultipleObjects so that you can wake periodically even if there a no messages to process, but immediatelly when there are messages.
|
2,165,315 | 2,165,367 | Checking if a string object has only null characters | I want to check if a string object of 20 characters has only null characters in it (values of zero). My attempt:
string subString;
subString = fileBuffer.substr(origin, origin+20);
if(strCompare.compare("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0") == 0)
cout<<"string is empty"<<endl;
else
cout<<"string is not empty"<<endl;
I am certain that subString is assigned 20 characters of null, however, the program only outputs "string is not empty". I tried other methods too such as making the compare parameter to "" or NULL to no avail. Can someone point out to me of any obvious errors or of the correct way to do this? I would really appreciate it.
| The problem with this:
if(strCompare.compare("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")
is that the string constructed from the C-style string will be empty. You need to construct a string explicitly, providing the size. One way:
if( strCompare.compare(
std::string( "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20 ) == 0 )
or somewhat shorter:
if( strCompare.compare(
std::string( 20, 0 ) == 0 )
|
2,165,637 | 2,166,047 | Char array pointer vs string refrence in params | I often see the following structure, especially in constructors:
class::class(const string &filename)
{
}
class::class(const char * const filename)
{
}
By step-by-step debug, I found out the 2nd constructor is always called if I pass a hard-coded string.
Any idea:
1) Why the dual structure is used?
2) What is the speed difference?
Thanks.
| Two constructors are needed because you can pass a NULL to your MyClass::MyClass(const std::string &arg). Providing second constructor saves you from a silly crash.
For example, you write constructor for your class, and make it take a const std::string & so that you don't have to check any pointers to be valid if you'd be using const char*.
And everywhere in your code you're just using std::strings. At some point you (or another programmer) pass there a const char*. Here comes nice part of std::string - it has a constructor, which takes char*, and that's very good, apart from the fact, that std::string a_string(NULL) compiles without any problems, just doesn't work.
That's where a second constructor like you've shown comes handy:
MyClass::MyClass(const char* arg)
: m_string(arg ? arg : "")
{}
and it will make a valid std::string object if you pass it a NULL.
In this case I don't think you'd need to worry about any speed. You could try measuring, although I'm afraid you'd be surprised with how little difference (if any) there would be.
EDIT: Just tried std::string a_string(NULL);, compiles just fine, and here's what happens when it is run on my machine (OS X + gcc 4.2.1) (I do recall I tried it on Windows some time ago, result was very similar if not exactly same):
std::logic_error: basic_string::_S_construct NULL not valid
|
2,165,726 | 2,165,776 | How do I record timestamps in a Mac OS X C++ program? | I'm running a giant simulation / with a graphics engine.
There are lots of events that are flying by.
I would like to timestamp them (measured in milliseconds since the start of program execution).
What should I be using for this? [What library?]
| Since Mac OS X is Unix based, try gettimeofday(). It will return seconds and microseconds, up to the resolution of the system clock.
#include <sys/types.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
|
2,165,921 | 2,165,980 | Converting from a std::string to bool | What is the best way to convert a std::string to bool? I am calling a function that returns either "0" or "1", and I need a clean solution for turning this into a boolean value.
| It'll probably be overkill for you, but I'd use boost::lexical_cast
boost::lexical_cast<bool>("1") // returns true
boost::lexical_cast<bool>("0") // returns false
|
2,165,995 | 2,166,013 | How to include all boost header files? | In Java if you wanted all the classes in a namespace you could just do this:
import com.bobdylan.*;
Is there anyway I can get a result similar to:
import boost.*;
(except in C++)
| Not automatically. You can write a single header file that #includes all the other headers you are interested in, and then just #include that, but that's it - C++ has no "import" feature like java.
|
2,166,098 | 2,166,102 | Why does GetErrorMessage return "wrong password", when the user name is wrong? | GetErrorMessage (from CInternetException) gives me the following:
With the incorrect ftp server name:
"ERROR! The server name or address could not be resolved"
With the incorrect password:
ERROR! The password was not allowed
With the incorrect user name:
ERROR! The password was not allowed <-----? NO separate message for incorrect username? Is this intended?
try
{
pConnect = sess->GetFtpConnection(host, userName, password, port, FALSE );
}
catch (CInternetException* pEx) //incorrect user name displays incorrect password?
{
TCHAR sz[1024];
pEx->GetErrorMessage(sz, 1024);
printf("ERROR! %s\n", sz);
pEx->Delete();
}
| Yes that is intended. A typical FTP server will not distinguish between an invalid password and an invalid username. This is for security reasons, so e.g. attackers can't brute force their way to discover valid usernames.
|
2,166,099 | 2,166,109 | Calling a constructor to re-initialize object | is it possible to re-initialize an object of a class using its constructor?
| Sort of. Given a class A:
A a;
...
a = A();
the last statement is not initialisation, it is assignment, but it probably does what you want.
|
2,166,169 | 2,166,334 | how to assign a Base object to a Derived object | I have a question about C++, how to assign a Base object to a Derived object? or how to assign a pointer to a Base object to a pointer to a Derived object?
In the code below, the two lines are wrong. How to correct that?
#include <iostream>
using namespace std;
class A{
public:
int a;
};
class B:public A{
public:
int b;
};
int main(){
A a;
B b;
b = a; //what happend?
cout << b.b << endl;
B* b2;
b2 = &a; // what happened?
cout << b->b << endl;
}
| When an object is on the stack, you can only really assign objects of the same type to one another. They can be converted through overloaded cast operators or overloaded assignment operators, but you're specifying a conversion at that point. The compiler can't do such conversions itself.
A a;
B b;
b = a;
In this case, you're trying to assigning an A to a B, but A isn't a B, so it doesn't work.
A a;
B b;
a = b;
This does work, after a fashion, but it probably won't be what you expect. You just sliced your B. B is an A, so the assignment can take place, but because it's on the stack, it's just going to assign the parts of b which are part of A to a. So, what you get is an A. It's not a B in spite of the fact that you assigned from a B.
If you really want to be assigning objects of one type to another, they need to be pointers.
A* pa = NULL;
B* pb = new B;
pa = pb;
This works. pa now points to pb, so it's still a B. If you have virtual functions on A and B overrides them, then when you call them on pa, they'll call the B version (non-virtual ones will still call the A version).
A* pa = new A;
B* pb = pa;
This doesn't work. pa doesn't point B, so you can't assign it to pb which must point to a B. Just because a B is an A doesn't mean than an A is a B.
A a;
B* pb = &a;
This doesn't work for the same reason as the previous one. It just so happens that the A is on the stack this time instead of the heap.
A* pa;
B b;
pa = &b;
This does work. b is a B which is an A, so A can point to it. Virtual functions will call the B versions and non-virtual ones will call the A versions.
So, basically, A* can point to B's because B is an A. B* can't point to A because it isn't a B.
|
2,166,271 | 2,167,476 | How to resolve a naming conflict between two libraries in C++? | I am using two large libraries (GUI & network) and I can happily do
using namespace FirstLib;
using namespace SecondLib;
Except for 1 single class called Foobar where names clash.
I my code, I do not use FirstLib::Foobar. Is there a way to say "in my code, whenever you see Foobar, think SecondLib::Foobar ?
| It's strange nobody suggested to replace the full namespace use by the list of used class names. This solution is even in the C++faq (where I should have thought to look first).
If we cannot say
include all FirstLib, but remove SecondLib::Foobar
We can use using-declarations of the exact elements we need:
using FirstLib::Boids;
using FirstLib::Life;
// no using FirstLib::Foobar...
|
2,166,321 | 2,166,330 | Push_back causing an error when using vectors in C++ | I am having issues getting this piece of code to compile. I am compiling with Eclipse on OS X 10.6. The problem seems to occur only when using vectors. I cannot seem to use the push_back function at all. Every time I try, I get the error "expected constructor, destructor, or type conversion before '.' token". Here are a few snippets of my code:
#include <GLUT/glut.h>
#include <vector>
#include <stdlib.h>
#include <iostream>
#include <math.h>
using namespace std;
enum Colour {BLACK =0, RED=1, BLUE=2, GREEN=3, PURPLE=4, ORANGE=5, CYAN=6, BLANK=7};
class Point {
private:
GLfloat xval, yval;
public:
Point(float x =0.0, float y = 0.0){
xval=x;
yval=y;
}
GLfloat x() {return xval;}
GLfloat y() {return yval;}
};
class LinePoint {
private:
Point p;
Colour cNum;
public:
LinePoint(Point pnt = Point(0,0), Colour c = BLACK){
cNum = c;
p = pnt;
}
Point getPoint(){return p;}
Colour getColour(){return cNum;}
};
float turtleScale = 20;
Point turtlePos = Point(300./turtleScale,200./turtleScale);
LinePoint* lp = new LinePoint(turtlePos,BLACK);
vector<LinePoint*> lines;
lines.push_back(lp);
I'm not sure if this would have anything to do with how Eclipse is setup but it also seems that if I use the code located here, in place of my vector calls, it still compiles with the same error.
| Here:
float turtleScale = 20;
Point turtlePos = Point(300./turtleScale,200./turtleScale);
LinePoint* lp = new LinePoint(turtlePos,BLACK);
vector<LinePoint*> lines;
... you use initializations, but this:
lines.push_back(lp);
... is a statement! It must live in a function :)
int main()
{
lines.push_back(lp);
}
... will work.
|
2,166,425 | 2,166,534 | How to structure a C++ application to use a multicore processor | I am building an application that will do some object tracking from a video camera feed and use information from that to run a particle system in OpenGL. The code to process the video feed is somewhat slow, 200 - 300 milliseconds per frame right now. The system that this will be running on has a dual core processor. To maximize performance I want to offload the camera processing stuff to one processor and just communicate relevant data back to the main application as it is available, while leaving the main application kicking on the other processor.
What do I need to do to offload the camera work to the other processor and how do I handle communication with the main application?
Edit:
I am running Windows 7 64-bit.
| Basically, you need to multithread your application. Each thread of execution can only saturate one core. Separate threads tend to be run on separate cores. If you are insistent that each thread ALWAYS execute on a specific core, then each operating system has its own way of specifying this (affinity masks & such)... but I wouldn't recommend it.
OpenMP is great, but it's a tad fat in the ass, especially when joining back up from a parallelization. YMMV. It's easy to use, but not at all the best performing option. It also requires compiler support.
If you're on Mac OS X 10.6 (Snow Leopard), you can use Grand Central Dispatch. It's interesting to read about, even if you don't use it, as its design implements some best practices. It also isn't optimal, but it's better than OpenMP, even though it also requires compiler support.
If you can wrap your head around breaking up your application into "tasks" or "jobs," you can shove these jobs down as many pipes as you have cores. Think of batching your processing as atomic units of work. If you can segment it properly, you can run your camera processing on both cores, and your main thread at the same time.
If communication is minimized for each unit of work, then your need for mutexes and other locking primitives will be minimized. Course grained threading is much easier than fine grained. And, you can always use a library or framework to ease the burden. Consider Boost's Thread library if you take the manual approach. It provides portable wrappers and a nice abstraction.
|
2,166,473 | 2,166,684 | How to create a multicolumn Listbox? | I'm working on a program, which should list all files and it's size(for now...). I created a simple application, which should write the data to a listbox. I'm trying to write the data in two columns(the first should be the name, and next to it, in an other column, it's size), but i can't figure out, how should i do this.
Can someone help me?
Thanks in advance!
kampi
Update:
I try to use ListControl., but unfortunately i can't. I can succesfully compile my App, but i can only see, the empty rectangle. Does someone know what i am doing wrong?
BOOL CGetFileListDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
LVITEM lvItem;
LVCOLUMN lvColumn;
int nCol;
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_CENTER;
lvColumn.cx = 10;
lvColumn.pszText = _T("Filename");
ListView_InsertColumn( m_List, 0, &lvColumn );
ListView_SetItemText( m_List, 0, 0, _T("TEST") );
return TRUE; // return TRUE unless you set the focus to a control
}
| The list box control does support multiple columns, but it only supports a single series of entries; the multiple column support just makes the items continue onto the next columns so that vertical scrolling is not necessary.
As Kornel has suggested, a list view control may be more appropriate. After creating a list view control, use ListView_InsertColumn to create the columns. Then use ListView_SetItemText to insert items.
EDIT:
My apoligies; you should use ListView_InsertItem to insert an item (a row) and then use ListView_SetItemText to alter the subitems (columns). If the list view is still just a blank box without any headings, have you initialised common controls? This can be done using InitCommonControlsEx, specifying the ICC_LISTVIEW_CLASSES constant. This should be done before creating the control.
See Microsoft's documentation on list view controls.
|
2,166,475 | 2,166,489 | What would be a good replacement for C++ vector in C#? | I'm working on improving my skills in other languages, coming from using c++ as my primary programming language. My current project is hammering down C#.net, as I have heard it is a good in-between language for one who knows both c++ and VB.net.
Typically when working with an unknown number of elements in c++ I would declare my variable as a vector and just go from there. Vectors don't seem to exist in c#, and in my current program I have been using arraylists instead, but I'm starting to wonder if it's a good habit to use arraylists as I read somewhere that it was a carryover from .net 1.0
Long question short- what is the most commonly used listing type for c#?
| If you target pre .NET 2.0 versions, use ArrayList
If you target .NET 2.0+ then use generic type List<T>
You may need to find replacements for other C++ standard containers, so here is possible mapping of C++ to .NET 2.0+ similar types or equivalents:
std::vector - List<T>
std::list - LinkedList<T>
std::map - Dictionary<K, V>
std::set - HashSet<T>
std::multimap - Dictionary<K, List<V>>
|
2,166,483 | 2,166,491 | Which macro to wrap Mac OS X specific code in C/C++ | While reading various C and C++ sources, I have encountered two macros __APPLE__ and __OSX__. I found plenty of use of __OSX__ in various codes, especially those originating from *BSD systems.
However, sometimes I find that testing __OSX__ only is not sufficient and I have to complete tests with __APPLE__ macro.
The Porting Command Line Unix Tools to Mac OS X guides specifies __APPLE__ and additionally __APPLE_CC__ but does not mention __OSX__.
The Porting from GCC guide says:
Use #ifdef __GNUC__ to wrap any GCC-specific code.
Use #ifdef __APPLE_CC__ to wrap any Mac OS X-specific code.
Again, no mention about __OSX__ macro.
What macro is predefined on Mac OS X platform and XCode development environment that should be used to distinguish OSX-specific code in C/C++ programs?
Where is the __OSX__ macro defined? Is it *BSD specific macro?
| It all depends.
Each macro specifies something different in meaning.
See: https://developer.apple.com/library/mac/documentation/Porting/Conceptual/PortingUnix/compiling/compiling.html#//apple_ref/doc/uid/TP40002850-SW13
__APPLE__
This macro is defined in any Apple computer.
__APPLE_CC__
This macro is set to an integer that represents the version number of
the compiler. This lets you distinguish, for example, between compilers
based on the same version of GCC, but with different bug fixes or features.
Larger values denote later compilers.
__OSX__
Presumably the OS is a particular variant of OS X
So given the above definitions I would use __APPLE__ to distinguish apple specific code.
|
2,166,532 | 2,166,550 | Why does GetLastError() (NOT GetReturnMessage) return “wrong password”, when the user name is wrong? |
Possible Duplicate:
Why does GetErrorMessage return “wrong password”, when the user name is wrong?
Since GetErrorMessage gave the same string for invalid password and username, I decided to use GetLastError(), as it has a separate error for each.
However with the incorrect username it still gives me the code 12014? (password error) but there IS a separate error code: ERROR_INTERNET_INCORRECT_USER_NAME - 12013
Shouldn't this work or is this intended too?
Thanks.
try
{
pConnect = sess->GetFtpConnection(host, wronguserName, password, port, FALSE );
err= GetLastError(); <---RETURNS INVALID PASSWORD with the wrong username??
}
catch (CInternetException* pEx) //incorrect user name displays incorrect password?
{
TCHAR sz[1024];
pEx->GetErrorMessage(sz, 1024);
printf("ERROR! %s\n", sz);
pEx->Delete();
}
| The function can only tell you what the FTP server returns. The FTP server, being securely coded, says it's the wrong password. There's nothing the function can do to give you a different result from what the FTP server is telling it. :-P
For FTP servers that do distinguish between invalid usernames and invalid passwords (naughty, naughty), I'm sure the function will also just return you what the server returns, which in that case could be error 12013.
|
2,166,581 | 2,166,594 | C++ SetWindowsHookEx WH_KEYBOARD_LL Correct Setup | I'm creating a console application in which I'd like to record key presses (like the UP ARROW). I've created a Low Level Keyboard Hook that is supposed to capture all Key Presses in any thread and invoke my callback function, but it isn't working. The program stalls for a bit when I hit a key, but never invokes the callback. I've checked the documentation but haven't found anything. I don't know whether I'm using SetWindowsHookEx() incorrectly (to my knowledge it successfully creates the hook) or my callback function is incorrect! I'm not sure whats wrong! Thanks in advance for the help.
#include "Windows.h"
#include <iostream>
using namespace std;
HHOOK hookHandle;
LRESULT CALLBACK keyHandler(int nCode, WPARAM wParam, LPARAM lParam);
int _tmain(int argc, _TCHAR* argv[]) {
hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, keyHandler, NULL, 0);
if(hookHandle == NULL) {
cout << "ERROR CREATING HOOK: ";
cout << GetLastError() << endl;
getchar();
return 0;
}
MSG message;
while(GetMessage(&message, NULL, 0, 0) != 0) {
TranslateMessage( &message );
DispatchMessage( &message );
}
cout << "Press any key to quit...";
getchar();
UnhookWindowsHookEx(hookHandle);
return 0;
}
LRESULT CALLBACK keyHandler(int nCode, WPARAM wParam, LPARAM lParam) {
cout << "Hello!" << endl;
// Checks whether params contain action about keystroke
if(nCode == HC_ACTION) {
cout << ((KBDLLHOOKSTRUCT *) lParam)->vkCode << endl;
}
return CallNextHookEx(hookHandle, nCode,
wParam, lParam);
}
| You can't block on a syscall (the getchar), you have to be running a window loop and processing messages before your hook gets called.
|
2,166,587 | 2,166,626 | Linked lists implementation issue | I'm trying to make a Stack using an underlying linked list structure.
Maybe I'm wrong, but I'm having trouble with the remove() function.
int Stack::remove(){
node* victim = new node;
int popped;
popped = top->element;
victim = top;
top = victim->next;
delete victim;
return popped;
}
I'm getting glibc dectecting
double free or corruption (out);
Since I'm allocating new memory with victim, don't I have to delete victim, or is that something I don't have to worry about?
| A stack is much like a bunch of dishes that are being washed and set on top of one another. That is the first one in is the last one out (FILO data type). That is if your stack read in 2, 7, 8 then it would appear as :
8
7
2
That is first the 2 is placed in the stack, followed by the 7 and then by the 8. If you want to remove or pop the stack you need to move the head of the pointer. Your code looks a bit strange to me...
int Stack::remove()
{
int datum; //to store the popped value
node* temp=head; //assign pointer to head of list
datum = temp->data; //grab the data value stored at the head (or temp since they carry same reference)
head = temp->next; //move the head pointer (in our example now it points to 7)
delete temp;
return datum;
}
|
2,166,622 | 2,166,673 | Why does OpenGL have global functions? | Why isn't openGL object-orientied? Everybody teaches Object Orientated Programming + Design Patterns, but OpenGL has many global functions. Isn't this bad style?
| The whole point of a low-level API is to make it as minimal and portable as possible. Giving it an object-oriented architecture would not allow this:
Polymorphism adds unnecessary function call overhead.
It forces you to use some relatively difficult calling convention, which reduces portability.
You cannot wrap an object-oriented architecture to make it procedural, but you can do the reverse; so, it makes sense to make things as flexible as possible. It's trivial to write an object-oriented wrapper around OpenGL if you want.
Finally, you should really question what you've been taught about OOP. Despite what your college or university may tell you, OOP is not a panacea of program design. There are very good reasons why there is absolutely no object-orientation in the C++ STL (and most of Boost for that matter).
Object-orientation is useful in some cases, but you should learn when it is useful, and when it is not, and under no circumstances should you believe that anything that is not OOP is "bad style".
|
2,166,802 | 2,166,817 | C++ Binary Tree error: request for member (X) in (Y) which is of non-class type (Z) | Hey all, so I am trying to build a simple binary tree that has two keys and evaluates the sum for its sorting. Here is what it's looking like:
struct SumNode
{
int keyA;
int keyB;
SumNode *left;
SumNode *right;
};
class SumBTree
{
public:
SumBTree();
~SumBTree();
void insert(int, int);
SumNode *search(int, int);
SumNode *search(int);
void destroy_tree();
private:
SumNode *root;
void insert(int,int, SumNode*);
SumNode *search(int,int, SumNode*);
SumNode *search(int, SumNode*);
void destroy_tree(SumNode*);
};
SumBTree::SumBTree()
{
root = NULL;
}
SumBTree::~SumBTree(){};
void SumBTree::insert(int a, int b, SumNode *leaf)
{
int sum = a + b;
int leafsum = leaf->keyA + leaf->keyB;
if (sum < leafsum)
{
if (leaf->left != NULL)
{
insert(a,b, leaf->left);
}
else
{
leaf->left = new SumNode;
leaf->left->keyA = a;
leaf->left->keyB = b;
leaf->left->left = NULL;
leaf->left->right = NULL;
}
}
else
{
if (leaf -> right != NULL)
{
insert(a,b, leaf->right);
}
else
{
leaf->right = new SumNode;
leaf->right->keyA = a;
leaf->right->keyB = b;
leaf->right->left = NULL;
leaf->right->right = NULL;
}
}
}
SumNode *SumBTree::search(int a, int b, SumNode *leaf)
{
if (leaf != NULL)
{
if (a == leaf->keyA && b == leaf->keyB)
return leaf;
int sum = a + b;
int leafsum = leaf->keyA + leaf->keyB;
if (sum < leafsum)
return search(a, b, leaf->left);
return search(a, b, leaf->right);
}
return NULL;
}
SumNode *SumBTree::search(int sum, SumNode *leaf)
{
if (leaf != NULL)
{
int leafsum = leaf->keyA + leaf->keyB;
if (sum == leafsum)
return leaf;
if (sum < leafsum)
return search(sum, leaf->left);
return search(sum, leaf->right);
}
return NULL;
}
void SumBTree::destroy_tree(SumNode *leaf)
{
if(leaf != NULL)
{
destroy_tree(leaf->left);
destroy_tree(leaf->right);
delete leaf;
}
}
void SumBTree::insert(int a, int b)
{
if (root != NULL)
{
insert(a,b, root);
}
else
{
root = new SumNode;
root->keyA = a;
root->keyB = b;
root->left = NULL;
root->right = NULL;
}
}
SumNode *SumBTree::search(int a, int b)
{
return search(a, b, root);
}
SumNode *SumBTree::search(int sum)
{
return search(sum, root);
}
void SumBTree::destroy_tree()
{
destroy_tree(root);
}
I went to test it out, using this:
#include <iostream>
#include "SumBTree.h"
using namespace std;
int main()
{
cout << "Initializing Tree" << endl;
SumBTree sbt();
cout << "Inserting (2,3)" << endl;
sbt.insert(2,3);
cout << "Hello world!" << endl;
return 0;
}
But whenever I try to build it I get the following error:
||=== BTree, Debug ===|
C:\Users\Axel\Desktop\coding\C++ Projects\BTree\main.cpp||In function int main()':|
C:\Users\Axel\Desktop\coding\C++ Projects\BTree\main.cpp|12|error: request for memberinsert' in sbt', which is of non-class typeSumBTree ()()'|
||=== Build finished: 1 errors, 0 warnings ===|
I can't figure out what I'm doing wrong! Is it the overloaded functions? I don't get it.
Does anyone here know?
| you need to replace SumBTree sbt(); with SumBTree sbt;
Right now it thinks sbt isn't a class. If there are no parameters in a constructor don't use empty brackets.
|
2,167,059 | 2,167,068 | A dynamic 2 dimensional array in C++? | I am trying to build a 2 dimensional array in C++ while I don't know how many rows I will have. Here is some code:
In the header file:
class model
{
... ...
float vertices[][3];
... ...
}
And in the .cpp file:
istringstream iss(str);
for (int i = 0; i <=2; i++)
{
iss >> vertices[counter][i];
}
Is this a proper way to handle it? I got a segmentation fault, I just want to make sure it's not caused by the way I use arrays. Also is there a better way to handle this, thanks.
| You need to either use pointers, or use a dynamically resizable container such as std::vector when you don't know the size.
|
2,167,093 | 2,167,115 | Best way of replacing heavy exception use? | I have an old C++ project I made a while back. Well, it is a CPU emulator. Whenever a CPU fault happens(such as divide by zero, or debug breakpoint interrupt, etc) in my code it just does a throw and in my main loop I have something like this:
try{
*(uint32_t*)&op_cache=ReadDword(cCS,eip);
(this->*Opcodes[op_cache[0]])();
eip=(uint16_t)eip+1;
}
catch(CpuInt_excp err){
err.code&=0x00FF;
switch(err.code){
case 0:
case 1: //.....
Int16(err.code);
break;
default:
throw CpuPanic_excp("16bit Faults",(err.code|0xF000)|TRIPLE_FAULT_EXCP);
break;
}
}
And a simple opcode example(pulled out of thin air)
if(**regs16[AX]==0){
throw CpuInt_excp(0); //throw divide by zero error
}
What this code basically does is just reads an opcode and if an exception occurred, then call the appropriate interrupt(in the CPU, which just changes the EIP)
Well, this being in the main loop, the try{}catch{} overhead really adds up. This isn't a premature optimization, I profiled it and gcc's exception helper functions(without even doing any faults and thus no throws) and the helper functions took up over 10% of the total execution time of a long running emulated program.
So! What would be the best way of replacing exceptions in this case? I would prefer not to have to keep track of return values because I already have a ton of code written, and because keeping track of them is really difficult when functions get really deep.
| You haven't shown your loop, but I'm guessing in pseudocode it's:
while (some_condition) {
// Your try..catch block:
try {
// Do an op
}
catch (CpuInt_excp err) {
// Handle the exception
}
}
You could move the try..catch out a level:
done = false;
while (!done) {
try {
while (some_condition) {
// Do an op
}
done = true;
}
catch (CpuInt_excp err) {
// Handle the exception
}
}
There I've included two loops, because I assume that if an exception occurs you want to be able to carry on (hard to tell without knowing what you're doing in Int16, but I think you're allowing carrying on after non-panic exceptions). Naturally if you don't need to carry on, you only need one loop.
The outer loop just restarts things after the exception. It can check the same condition as the inner loop if that condition is not expensive to check (e.g., it's a program counter or something), or it can have a flag as in the above if the condition is expensive to check.
|
2,167,293 | 2,167,342 | C++ virtual function call versus boost::function call speedwise | I wanted to know how fast is a single-inheritance virtual function call when compared to one same boost::function call. Are they almost the same in performance or is boost::function slower?
I'm aware that performance may vary from case to case, but, as a general rule, which is faster, and to a how large degree is that so?
Thanks,
Guilherme
-- edit
KennyTM's test was sufficiently convincing for me. boost::function doesn't seem to be that much slower than a vcall for my own purposes. Thanks.
| As a very special case, consider calling an empty function 109 times.
Code A:
struct X {
virtual ~X() {}
virtual void do_x() {};
};
struct Y : public X {}; // for the paranoid.
int main () {
Y* x = new Y;
for (int i = 100000000; i >= 0; -- i)
x->do_x();
delete x;
return 0;
}
Code B: (with boost 1.41):
#include <boost/function.hpp>
struct X {
void do_x() {};
};
int main () {
X* x = new X;
boost::function<void (X*)> f;
f = &X::do_x;
for (int i = 100000000; i >= 0; -- i)
f(x);
delete x;
return 0;
}
Compile with g++ -O3, then time with time,
Code A takes 0.30 seconds.
Code B takes 0.54 seconds.
Inspecting the assembly code, it seems that the slowness may be due to exceptions and handling the possibility and that f can be NULL. But given the price of one boost::function call is only 2.4 nanoseconds (on my 2 GHz machine), the actual code in your do_x() could shadow this pretty much. I would say, it's not a reason to avoid boost::function.
|
2,167,335 | 2,167,355 | Pure Virtual Method Called | EDIT: SOLVED
I'm working on a multi-threaded project right now where I have a base worker class, with varying worker classes that inherit from it. At runtime, the worker classes become threads, which then perform work as needed.
Now, I have a Director I've written which is supposed to maintain an array of pointers to all of the workers, so that it can retrieve information from them, as well as modify variables within them later.
I did this by creating a pointer to a pointer of the base class:
baseWorkerClass** workerPtrArray;
Then in the constructor of the Director, I dynamically allocate an array of pointers to the base worker class:
workerPtrArray = new baseWorkerClass*[numWorkers];
In the constructor of each worker thread, the worker calls a function in the director which is meant to store the pointer of that worker in the array.
Here's how the director stores the pointers:
Director::manageWorker(baseWorkerClass* worker)
{
workerPtrArray[worker->getThreadID()] = worker;
}
Here is an example of a worker variant. Each worker inherits from the base worker class, and the base worker class contains pure virtual functions which should exist in all worker variants, as well as a few variables which are shared between all workers.
class workerVariant : protected baseWorkerClass
{
public:
workerVariant(int id)
: id(id)
{
Director::manageWorker(this);
}
~workerVariant()
{
}
int getThreadID()
{
return id;
}
int getSomeVariable()
{
return someVariable;
}
protected:
int id;
int someVariable
};
Then the baseWorkerClass looks something like this:
class baseWorkerClass
{
public:
baseWorkerClass()
{
}
~baseWorkerClass()
{
}
virtual int getThreadID() = 0;
virtual int getSomeVariable() = 0;
};
After each worker variant is done initializing, I should end up with an array of pointers to baseWorkerClass objects. This means I should be able to, for example, get the value of a given variable in a certain worker using its ID as the index to the array, like so:
workerPtrArray[5]->getSomeVariable(); // Get someVariable from worker thread 5
The problem is that this code causes a crash in a Windows executable, without any explanation of why, and in Linux, it says:
pure virtual method called
terminate called without an active exception
Aborted
I could've sworn I had this working at some point, so I'm confused as to what I've screwed up.
Actual unmodified code that has the problem:
Worker variant header: http://pastebin.com/f4bb055c8
Worker variant source file: http://pastebin.com/f25c9e9e3
Base worker class header: http://pastebin.com/f2effac5
Base worker class source file: http://pastebin.com/f3506095b
Director header: http://pastebin.com/f6ab1767a
Director source file: http://pastebin.com/f5f460aae
EDIT: Extra information, in the manageWorker function, I can call any of the pure virtual functions from the pointer "worker," and it works just fine. Outside of the manageWorker function, when I try to use the pointer array, it fails.
EDIT: Now that I think about it, the thread's entry point is operator(). The Director thread is created before the workers, which may mean that the overloaded parenthesis operator is calling pure virtual functions before they can be overridden by the child classes. I'm looking into this.
| The problem appears to be that Director::manageWorker is called in the constructor of workerVariant instances:
Director::manageWorker(baseWorkerClass* worker) {
workerPtrArray[worker->getThreadID()] = worker;
}
Presumably getThreadID() isn't a pure virtual function or you would have (hopefully!) gotten a compiler error about not overriding it in workerVariant. But getThreadID() might call other functions which you should override, but are being invoked in the abstract class. You should double check the definition of getThreadID() to make sure you're not doing anything untoward that would depend on the child class before it's properly initialized.
A better solution might be to separate this sort of multi-stage initialization into a separate method, or to design Director and baseWorkerClass such that they don't have this sort of initialization-time interdependency.
|
2,167,506 | 2,167,511 | Static member data of template class with two parameters | http://www.adp-gmbh.ch/cpp/templates/static_members.html makes it clear what I need to do - if the template has a single parameter.
What if it had two?
template <typename T, typename T2> class X {
public:
static int st_;
};
How would I template the static memebr data?
template <typename T, typename T2> int, int X<T, T2>::st_;
or
template <typename T, typename T2> int int X<T, T2>::st_;
or what?
I think that my problem is knowinng what to do with the two real types (both int here).
After templating, how do I declare my static member variable?
| template <typename T, typename T2>
int X<T, T2>::st_;
You don't need two int-s. The int is the just type of st_.
|
2,167,588 | 2,167,677 | boost::function and boost::bind are cool, but what is really cool about boost::lambda? | On Page 175 Paragraph 1 of Effective C++ Meyers has this to say about generalized functors and binding:
I find what tr1::function lets you do
so amazing, it makes me tingle all
over. If you're not tingling , it may
be because you're staring at the
definition of ... and wondering what's
going on with the ....
And I agree with him on bind and function. About lambda, Well I understand what lambda does and how it does it, but could someone post a book style mind-blowing snippet or a verbal outline of why lambda is supposed to (in Meyers' terminology) blow my socks off ? I ask because each area of C++ where the placeholder syntax is used seems like a hack to me (yes, I know enough about the functional method, so please no basics), I agree with the way it's used in bind and MPL; However, in the case of lambda I just want it justified so I can decide weather I should enter it into my repertoire.
-- edit --
This SO answer mentions the inlined creation of a functor using just placedholder syntax, he mentions advanced usage, and this is probably what I am after... in advanced usage is it still just inlined creation of functors ?
| Based on the comments left above, and the link in the question, the following is the answer I accept (community wiki) :
Boost.Lambda fills the purpose of inline functor creation (that's the term I like). This functionality can be filled by Function + Bind, but it is more verbose than it needs to be, and for simple functors this is unnecessary — e.g., the sort shown in the comments above.
There is obviously semantic overlap between the Function-Bind pair and Lambda — this is a historical artifact, and because Lambda has its raison d'être, it exists in Boost.
|
2,167,802 | 2,168,276 | Resolving typedefs in C and C++ | I'm trying to automatically resolve typedefs in arbitrary C++ or C projects.
Because some of the typedefs are defined in system header files (for example uint32), I'm currently trying to achieve this by running the gcc preprocessor on my code files and then scanning the preprocessed files for typedefs. I should then be able to replace the typedefs in the project's code files.
I'm wondering, if there is another, perhaps simpler way, I'm missing. Can you think of one?
The reason, why I want to do this: I'm extracting code metrics from the C/C++ projects with different tools. The metrics are method-based. After extracting the metrics, I have to merge the data, that is produced by the different tools. The problem is, that one of the tools resolves typedefs and others don't. If there are typedefs used for the parameter types of methods, I have metrics mapped to different method-names, which are actually referring to the same method in the source code.
Think of this method in the source code: int test(uint32 par1, int par2)
After running my tools I have metrics, mapped to a method named int test(uint32 par1, int par2) and some of my metrics are mapped to int test(unsigned int par1, int par2).
| If you do not care about figuring out where they are defined, you can use objdump to dump the C++ symbol table which resolves typedefs.
lorien$ objdump --demangle --syms foo
foo: file format mach-o-i386
SYMBOL TABLE:
00001a24 g 1e SECT 01 0000 .text dyld_stub_binding_helper
00001a38 g 1e SECT 01 0000 .text _dyld_func_lookup
...
00001c7c g 0f SECT 01 0080 .text foo::foo(char const*)
...
This snippet is from the following structure definition:
typedef char const* c_string;
struct foo {
typedef c_string ntcstring;
foo(ntcstring s): buf(s) {}
std::string buf;
};
This does require that you compile everything and it will only show symbols in the resulting executable so there are a few limitations. The other option is to have the linker dump a symbol map. For GNU tools add -Wl,-map and -Wl,name where name is the name of the file to generate (see note). This approach does not demangle the names, but with a little work you can reverse engineer the compiler's mangling conventions. The output from the previous snippet will include something like:
0x00001CBE 0x0000005E [ 2] __ZN3fooC2EPKc
0x00001D1C 0x0000001A [ 2] __ZN3fooC1EPKc
You can decode these using the C++ ABI specification. Once you get comfortable with how this works, the mangling table included with the ABI becomes priceless. The derivation in this case is:
<mangled-name> ::= '_Z' <encoding>
<encoding> ::= <name> <bare-function-type>
<name> ::= <nested-name>
<nested-name> ::= 'N' <source-name> <ctor-dtor-name> 'E'
<source-name> ::= <number> <identifier>
<ctor-dtor-name> ::= 'C2' # base object constructor
<bare-function-type> ::= <type>+
<type> ::= 'P' <type> # pointer to
<type> ::= <cv-qualifier> <type>
<cv-qualifier> ::= 'K' # constant
<type> ::= 'c' # character
Note: it looks like GNU changes the arguments to ld so you may want to check your local manual (man ld) to make sure that the map file generation commands are -mapfilename in your version. In recent versions, use -Wl,-M and redirect stdout to a file.
|
2,167,895 | 2,168,265 | Howto implement callback interface from unmanaged DLL to .net app? | in my next project I want to implement a GUI for already existing code in C++.
My plan is to wrap the C++ part in a DLL and to implement the GUI in C#. My problem is that I don't know how to implement a callback from the unmanaged DLL into the manged C# code. I've already done some development in C# but the interfacing between managed and unmanaged code is new to me. Can anybody give me some hints or reading tips or a simple example to start from? Unfortunatly I could not find anything helpful.
| You don't need to use Marshal.GetFunctionPointerForDelegate(), the P/Invoke marshaller does it automatically. You'll need to declare a delegate on the C# side whose signature is compatible with the function pointer declaration on the C++ side. For example:
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class UnManagedInterop {
private delegate int Callback(string text);
private Callback mInstance; // Ensure it doesn't get garbage collected
public UnManagedInterop() {
mInstance = new Callback(Handler);
SetCallback(mInstance);
}
public void Test() {
TestCallback();
}
private int Handler(string text) {
// Do something...
Console.WriteLine(text);
return 42;
}
[DllImport("cpptemp1.dll")]
private static extern void SetCallback(Callback fn);
[DllImport("cpptemp1.dll")]
private static extern void TestCallback();
}
And the corresponding C++ code used to create the unmanaged DLL:
#include "stdafx.h"
typedef int (__stdcall * Callback)(const char* text);
Callback Handler = 0;
extern "C" __declspec(dllexport)
void __stdcall SetCallback(Callback handler) {
Handler = handler;
}
extern "C" __declspec(dllexport)
void __stdcall TestCallback() {
int retval = Handler("hello world");
}
That's enough to get you started with it. There are a million details that can get you into trouble, you are bound to run into some of them. The much more productive way to get this kind of code going is writing a wrapper in the C++/CLI language. That also lets you wrap a C++ class, something you can't do with P/Invoke. A decent tutorial is available here.
|
2,167,922 | 2,167,940 | how to make "choose file" function on windows programming? | I need this us all known "choose file" feature in my program, so i can load files.
What is this thing called as and where is the code for it?
| What you are referring to are the "common dialogs", and you can get a file open dialog with GetOpenFileName
BOOL GetOpenFileName(
LPOPENFILENAME lpofn
);
A sample is available here
|
2,167,941 | 2,168,060 | Iterating over the types in a boost::variant | I'm using a boost variant to hold some generated types, right now my code generator creates a header with the types and a variant capable of holding them. At initialization time, I'd like to iterate over the allowable types in the variant, not the types the variant is holding at the moment.
Can I do this with a variant?
| boost::variant exposes its types via types, which is an MPL list. You can do runtime operations over MPL lists using mpl::for_each:
struct printer {
template<class T> void operator()(T t) {
std::cout << typeid(T).name() << std::endl;
}
};
// ...
typedef boost::variant<int, char> var;
boost::mpl::for_each<var::types>(printer());
|
2,168,054 | 2,168,059 | What does C(++) do with values that aren't stored in variables? | I'm a bit curious about how C and C++ handle data which isn't stored in variables, e.g:
int IE6_Bugs = 12345;
int Win_Bugs = 56789;
Yeah - everything clear. IE6_Bugs has 123456 stored at it's specific memory address.
Then what about..
if ( IE6_Bugs + Win_Bugs > 10000 )
{
// ...
So C grabs the values of the two variables and adds them in order to compare the result to the int on the right.
But:
Does IE6_Bugs+Win_Bugs ever reach RAM? Or does the processor directly compare the values via its own cache?
Or is, in the compiling process, the above if statement converted to something more "understandable" for the machine? (Maybe calculate IE6_Bugs+Win_Bugs first and store it in some variable,...)
| It'll be placed in a register in the CPU (assuming one is available). A register is a sort of super-fast super-small RAM that's built into the CPU itself and used to store results of intermediate operations.
If the value can be determined to always equal xxx then a smart compiler will substitute the value of xxx in its place.
Keep in mind that regardless of whether it is as an expression or a number, (x+y vs 10) it will still need to be placed in a register so that the CPU can access it and perform an operation based on its value.
For more info, read up on computer architecture.
|
2,168,055 | 2,168,196 | K-Dop collision between different K and Volumes | And now after some work, I finally understand how the KDop bounding volume are created and how the collisions are intersected and I maked a working implementation of them.
Now the problem is another. :D
How can I intersect (it has to be possible, or it would not make any sense) 2 K-Dop of different K values? (obviously we know beforehand which axis has been used to create those 2 K-Dop.)
Like how can i intersect a DOP6 (AABB) and a DOP14 (AABB + corners cut off)?
Or a DOP14 (AABB + corners cut off) and a DOP26 (AABB + Corners cut off + Edges cut off)?
The simple method (between KDOP with the same K) is
public Boolean Intersects(kDOP a, kDOP b)
{
// TODO : How to do if the K is not the same?
for (int i = 0; i < a.K / 2; i++)
if ((a.Min[i] > b.Max[i]) || (a.Max[i] < b.Min[i]))
return false;
return true;
}
Another question is. How to do intersection between KDOP and say a Sphere? KDOP and a Capsule? KDOP and a OOB? KDOP and a AABB? (this should be easier if we know how to do with different K (as AABB is a DOP6 basically))
I mean what's the common way to do intersection between these simple structures?
Thanks a lot for the answers!!!
EDIT : From some search on the net it seems that the separation axis is the way to go, but I can't find any detailed information on how to implement it on the K-DOP. :P
EDIT 2 : Someone has a working implementation of a separation axis theorem over KDOP? :|
| If the Ks are a different order, just run your i loop to the minimum of a.K/2 or b.K/2.
|
2,168,082 | 2,168,217 | How to rewrite array from row-order to column-order? | I have this double for-loop, where I have both row-order and column-order array indexing, which should be bad for performance.
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
/* Column-major order */
d = array_a[col*height +row];
if (d < 0) { d = 0; }
/* Row-major order */
/* Map from x=0,y=0 at buttom left corner to
0,0 at top left corner */
array_b[width*(height-1 -row) + col] = d;
}
}
Is there an approach/method on how to rewrite from one to the other?
When I try to rewrite the last to column-order, the data becomes skewed. Can't it be rewritten?
Sandra
| This is never going to be very fast as you'll probably have a number of cache misses, you'll either have to step to the one matrix with a large pitch or the other, there's no escaping that. The problem here is that a computer likes successive memory accesses to be close together, which in your algorithm is not the case the indexing of array_a skips by height elements at a time due to the col*height term. To fix that you could switch around the for loops, but then you'd have the same problem with the width*(height-1 -row) term in array_b.
You could rewrite one of the arrays to match the ordering of the other, but then you would have the exact same problem in the code which does the rewrite, so it depends on whether you need to do this kind of thing more than once on the same data, if you do, then it makes sense to first rewrite one of the matrices like Poita_ described, otherwise you'd best leave the algorithm as is.
|
2,168,201 | 2,168,222 | What is a copy constructor in C++? | On page 6 of Scott Meyers's Effective C++, the term 'copy constructor' is defined. I've been using Schiltdt's book as my reference and I can find no mention of copy constructors. I get the idea but is this a standard part of c++? Will such constructors get called when a pass a class by value?
| A copy constructor has the following form:
class example
{
example(const example&)
{
// this is the copy constructor
}
}
The following example shows where it is called.
void foo(example x);
int main(void)
{
example x1; //normal ctor
example x2 = x1; // copy ctor
example x3(x2); // copy ctor
foo(x1); // calls the copy ctor to copy the argument for foo
}
|
2,168,233 | 2,168,248 | c++ use of ptr as array base | On page 42 of Effective C++, a pointer is used as an array name ala
AirPlane *newBlock = ...
newBlock[i].next=0;
I've not been aware that this is legal. Is this part of the c++ standard? Is it common practice?
| From http://www.cplusplus.com/doc/tutorial/pointers/:
In the chapter about arrays we used
brackets ([]) several times in order
to specify the index of an element of
the array to which we wanted to refer.
Well, these bracket sign operators []
are also a dereference operator known
as offset operator. They dereference
the variable they follow just as *
does, but they also add the number
between brackets to the address being
dereferenced. For example:
a[5] = 0; // a [offset of 5] = 0
*(a+5) = 0; // pointed by (a+5) = 0
These two expressions are equivalent
and valid both if a is a pointer or if
a is an array.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.