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,619,659 | 2,619,783 | How do you make an in-place construction of a struct casted to array compile in Visual C++ 2008? | I'm working with quite a big codebase which compiles fine in linux but vc++ 2008 spits errors.
The problem code goes like this:
Declaration:
typedef float vec_t;
typedef vec_t vec2_t[2];
The codebase is littered with in-place construction like this one:
(vec2_t){0, divs}
Or more complex:
(vec2_t){ 1/(float)Vid_GetScreenW(), 1/(float)Vid_GetScreenH()}
As far as I know, this code constructs a struct, then converts it to an array and passes the address to the function. I personally never used in-place construction like this so I have no clue how to make this one work.
The compiler produces a bunch of syntax errors like these:
Error 2 error C2143: syntax error : missing ')' before '{'
Error 3 error C2059: syntax error : ')'
Error 4 error C2143: syntax error : missing ';' before '{'
I don't maintain the linux build, only the windows one. And I can't get it to compile. Is there some switch, some macro to make vc++ compile it?
Maybe there is a similar nifty way to construct those arrays and pass them to the functions in-place that compiles just fine in vc++?
| You're using a GCC extension that MSVC simply doesn't support, "compound literals", also called "constructor expressions" in older GCC docs.
If you want portable code, I think you'll need to change the code to declare the structs normally and initialize them with initializers that have constants expressions or using standard assignments (or use something like MinGW as your Windows compiler, if that'll do the trick).
|
2,619,812 | 2,619,816 | sqrt(int_value + 0.0) -- Does it have a purpose? | while doing some homework in my very strange C++ book, which I've been told before to throw away, had a very peculiar code segment. I know homework stuff always throws in extra "mystery" to try to confuse you like indenting 2 lines after a single-statement for-loop. But this one I'm confused on because it seems to serve some real-purpose.
basically it is like this:
int counter=10;
...
if(pow(floor(sqrt(counter+0.0)),2) == counter)
...
I'm interested in this part especially:
sqrt(counter+0.0)
Is there some purpose to the +0.0? Is this the poormans way of doing a static cast to a double? Does this avoid some compiler warning on some compiler I do not use? The entire program printed the exact same thing and compiled without warnings on g++ whenever I left out the +0.0 part. Maybe I'm not using a weird enough compiler?
Edit:
Also, does gcc just break standard and not make an error for Ambiguous reference since sqrt can take 3 different types of parameters?
[earlz@EarlzBeta-~/projects/homework1] $ cat calc.cpp
#include <cmath>
int main(){
int counter=0;
sqrt(counter);
}
[earlz@EarlzBeta-~/projects/homework1] $ g++ calc.cpp
/usr/lib/libstdc++.so.47.0: warning: strcpy() is almost always misused, please use strlcpy()
/usr/lib/libstdc++.so.47.0: warning: strcat() is almost always misused, please use strlcat()
[earlz@EarlzBeta-~/projects/homework1] $
Also, here is the relevant part of my system libraries cmath I'm not too keen on templates, so I'm not sure what it's doing
using ::sqrt;
inline float
sqrt(float __x)
{ return __builtin_sqrtf(__x); }
inline long double
sqrt(long double __x)
{ return __builtin_sqrtl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
sqrt(_Tp __x)
{ return __builtin_sqrt(__x);
|
Is this the poormans way of doing a static cast to a double?
Yes.
You can't call sqrt with an int as its parameter, because sqrt takes a float, double, or long double. You have to cast the int to one of those types, otherwise the call is ambiguous.
|
2,619,814 | 2,619,835 | Deleting a non-owned dynamic array through a pointer | I'm relatively novice when it comes to C++ as I was weened on Java for much of my undergraduate curriculum (tis a shame). Memory management has been a hassle, but I've purchased a number books on ansi C and C++. I've poked around the related questions, but couldn't find one that matched this particular criteria. Maybe it's so obvious nobody mentions it?
This question has been bugging me, but I feel as if there's a conceptual point I'm not utilizing.
Suppose:
char original[56];
cstr[0] = 'a';
cstr[1] = 'b';
cstr[2] = 'c';
cstr[3] = 'd';
cstr[4] = 'e';
cstr[5] = '\0';
char *shaved = shavecstr(cstr);
// various operations, calls //
delete[] shaved;
Where,
char* shavecstr(char* cstr)
{
size_t len = strlen(cstr);
char* ncstr = new char[len];
strcpy(ncstr,cstr);
return ncstr;
}
In that the whole point is to have 'original' be a buffer that fills with characters and routinely has its copy shaved and used elsewhere.
To clarify, original is filled via std::gets(char* buff), std::getline(char* buff, buff_sz), std::read(char* buff, buff_sz), or any in-place filling input reader. To 'shave' a string, it's basically truncated down eliminating the unused array space.
The error is a heap allocation error, and segs on the delete[].
To prevent leaks, I want to free up the memory held by 'shaved' to be used again after it passes through some arguments. There is probably a good reason for why this is restricted, but there should be some way to free the memory as by this configuration, there is no way to access the original owner (pointer) of the data.
| I assume you would replace original by cstr, otherwise the code won't compile as cstr is not declared.
The error here is that the size of the allocated array is too small. You want char* ncstr = new char[len+1]; to account for the terminating \0.
Also, if you delete shaved right after the function returns, there is no point in calling the function...
[*] To go a bit deeper, the memory used for cstr will be released when the containing function returns. Usually such static strings are placed in constants that live for the entire duration of the application. For example, you could have const char* cstr="abcde"; outside all your functions. Then you can pass this string around without having to dynamically allocate it.
|
2,619,830 | 2,619,896 | Why did this work with Visual C++, but not with gcc? | I've been working on a senior project for the last several months now, and a major sticking point in our team's development process has been dealing wtih rifts between Visual-C++ and gcc. (Yes, I know we all should have had the same development environment.) Things are about finished up at this point, but I ran into a moderate bug just today that had me wondering whether Visual-C++ is easier on newbies (like me) by design.
In one of my headers, there is a function that relies on strtok to chop up a string, do some comparisons and return a string with a similar format. It works a little something like the following:
int main()
{
string a, b, c;
//Do stuff with a and b.
c = get_string(a,b);
}
string get_string(string a, string b)
{
const char * a_ch, b_ch;
a_ch = strtok(a.c_str(),",");
b_ch = strtok(b.c_str(),",");
}
strtok is infamous for being great at tokenizing, but equally great at destroying the original string to be tokenized. Thus, when I compiled this with gcc and tried to do anything with a or b, I got unexpected behavior, since the separator used was completely removed in the string. Here's an example in case I'm unclear; if I set a = "Jim,Bob,Mary" and b="Grace,Soo,Hyun", they would be defined as a="JimBobMary" and b="GraceSooHyun" instead of staying the same like I wanted.
However, when I compiled this under Visual C++, I got back the original strings and the program executed fine.
I tried dynamically allocating memory to the strings and copying them the "standard" way, but the only way that worked was using malloc() and free(), which I hear is discouraged in C++. While I'm curious about that, the real question I have is this: Why did the program work when compiled in VC++, but not with gcc?
(This is one of many conflicts that I experienced while trying to make the code cross-platform.)
Thanks in advance!
-Carlos Nunez
| Tokens will be automatically replaced by a null-character by function strtok. That is not what you can do with constant data.
To make your code safe and cross-platform consider using boost::tokenizer.
|
2,619,848 | 2,619,957 | How to check if a position inside a std string exists ?? (c++) | i have a long string variable and i want to search in it for specific words and limit text according to thoses words.
Say i have the following text :
"This amazing new wearable audio solution features a working speaker embedded into the front of the shirt and can play music or sound effects appropriate for any situation. It's just like starring in your own movie"
and the words : "solution" , "movie".
I want to substract from the big string (like google in results page):
"...new wearable audio solution features a working speaker embedded..."
and
"...just like starring in your own movie"
for that i'm using the code :
for (std::vector<string>::iterator it = words.begin(); it != words.end(); ++it)
{
int loc1 = (int)desc.find( *it, 0 );
if( loc1 != string::npos )
{
while(desc.at(loc1-i) && i<=80)
{
i++;
from=loc1-i;
if(i==80) fromdots=true;
}
i=0;
while(desc.at(loc1+(int)(*it).size()+i) && i<=80)
{
i++;
to=loc1+(int)(*it).size()+i;
if(i==80) todots=true;
}
for(int i=from;i<=to;i++)
{
if(fromdots) mini+="...";
mini+=desc.at(i);
if(todots) mini+="...";
}
}
but desc.at(loc1-i) causes OutOfRange exception... I don't know how to check if that position exists without causing an exception !
Help please!
| This is an excellent exercise in taking advantage of what the STL has to offer. You simply open a reference and cherry-pick algorithms and classes for your solution!
#include <iostream> // algorithm,string,list,cctype,functional,boost/assign.hpp
using namespace std;
struct remove_from {
remove_from(string& text) : text(text) { }
void operator()(const string& str) {
typedef string::iterator striter;
striter e(search(text.begin(), text.end(), str.begin(), str.end()));
while( e != text.end() ) {
striter b = e;
advance(e, str.length());
e = find_if(e, text.end(), not1(ptr_fun<int,int>(isspace)));
text.erase(b, e);
e = search(text.begin(), text.end(), str.begin(), str.end());
}
}
private:
string& text;
};
int main(int argc, char* argv[])
{
list<string> toremove = boost::assign::list_of("solution")("movie");
string text("This amazing new wearable ...");
for_each(toremove.begin(), toremove.end(), remove_from(text));
cout << text << endl;
return 0;
}
|
2,619,853 | 2,625,331 | Emacs - override indentation | I have a multiply nested namespace:
namespace first {namespace second {namespace third {
// emacs indents three times
// I want to intend here
} } }
so emacs indents to the third position. However I just want a single indentation.
Is it possible to accomplish this effect simply?
| Use an an absolute indentation column inside namespace:
(defconst my-cc-style
'("gnu"
(c-offsets-alist . ((innamespace . [4])))))
(c-add-style "my-cc-style" my-cc-style)
Then use c-set-style to use your own style.
Note that this only works in c++-mode, c-mode doesn't know 'innamespace'.
|
2,619,866 | 2,619,889 | Overwriting a range of bits in an integer in a generic way | Given two integers X and Y, I want to overwrite bits at position P to P+N.
Example:
int x = 0xAAAA; // 0b1010101010101010
int y = 0x0C30; // 0b0000110000110000
int result = 0xAC3A; // 0b1010110000111010
Does this procedure have a name?
If I have masks, the operation is easy enough:
int mask_x = 0xF00F; // 0b1111000000001111
int mask_y = 0x0FF0; // 0b0000111111110000
int result = (x & mask_x) | (y & mask_y);
What I can't quite figure out is how to write it in a generic way, such as in the following generic C++ function:
template<typename IntType>
IntType OverwriteBits(IntType dst, IntType src, int pos, int len) {
// If:
// dst = 0xAAAA; // 0b1010101010101010
// src = 0x0C30; // 0b0000110000110000
// pos = 4 ^
// len = 8 ^-------
// Then:
// result = 0xAC3A; // 0b1010110000111010
}
The problem is that I cannot figure out how to make the masks properly when all the variables, including the width of the integer, is variable.
Does anyone know how to write the above function properly?
| A little bit shifting will give you the masks you need.
template<typename IntType>
IntType OverwriteBits(IntType dst, IntType src, int pos, int len) {
IntType mask = (((IntType)1 << len) - 1) << pos;
return (dst & ~mask) | (src & mask);
}
|
2,620,031 | 2,680,988 | WinMain not called before main (C/C++ Program Entry Point Issue) | I was under the impression that this code
#include <windows.h>
#include <stdio.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
printf("WinMain\n");
return 0;
}
int main()
{
printf("main\n");
return 0;
}
would output WinMain, but of course nothing ever works how you expects.
Anyways, could somebody please tell me how to get this program to run WinMain first (I do have a reason for using both). I'm running windows 7 with mingw if that helps anything.
| Just found this work around and kind of feel dumb.
#define main USER_Main
This then takes main out of line for being the programs entry point while still hiding the fact that anything was messed with from the user.
|
2,620,191 | 2,620,277 | What is better, a STL list or a STL Map for 20 entries, considering order of insertion is as important as the search speed | I have the following scenario.The implementation is required for a real time application.
1)I need to store at max 20 entries in a container(STL Map, STL List etc).
2)If a new entry comes and 20 entries are already present i have to overwrite the oldest entry with the new entry.
Considering point 2, i feel if the container is full (Max 20 entries) 'list' is the best bet as i can always remove the first entry in the list and add the new one at last (push_back). However, search won't be as efficient.
For only 20 entries, does it really make a big difference in terms of searching efficiency if i use a list in place of a map?
Also considering the cost of insertion in map i feel i should go for a list?
Could you please tell what is a better bet for me ?
| With only 20 elements, I would not worry much about which container you use. If you determine that the container chosen is in fact a detriment to the performance of your application, it should be relatively easy to swap out the container chosen and replace it with a more-efficient container later.
With that being said, for a large number of elements, the std::deque would probably give you the best all-around efficiency for what you are trying to accomplish. Unlike std::vector, std::deque allows for removal from the front without needing to move all of the other elements. Unlike std::list, std::deque allows for random access of its elements.
|
2,620,197 | 2,620,229 | Eclipse CDT: Import source / header files into my new project, without duplicating them | Im sure there is a very simple solution for this.
I have a bunch of .cpp / .h files from a project, say in directory ~/files
On the other hand, I want to create a c++ project using eclipse to work on those files, so I put my workspace on ~/wherever. Then I create a c++ project: ~/wherever/project, and include the source files (located in /~files).
The problem i'm having is that files are now duplicated in ~/wherever/project, and I would like to avoid that, specially so I know which copy of the file to commit.
Is this possible? Im sure it is, but cant get it.
Thanks in advance.
| You could try:
creating the project directly above the ~/files (which is not very clean, given the location of the sources in your home dir)
using a linked folder
importing existing sources in your project: details all the options (when your sources are also managed by a VCS like CVS, or when your sources are not managed)
|
2,620,205 | 2,620,249 | Need GDI programming Guideline | I want to change my window design rapidly. I have OnPaint function which I am calling when WM_PAINT message received. The design change only when the event occure. I want that design should automatically update doesn't depend on event kindly guide me how can I make it possible.
| All drawing code should be placed in WM_PAINT message handler or called from it. Your current code is OK. When window should be redrawn as result of some event, just call Invalidate() or UpdateWindow(), this is indirect call to WM_PAINT message handler.
|
2,620,218 | 2,622,526 | Fastest container or algorithm for unique reusable ids in C++ | I have a need for unique reusable ids. The user can choose his own ids or he can ask for a free one. The API is basically
class IdManager {
public:
int AllocateId(); // Allocates an id
void FreeId(int id); // Frees an id so it can be used again
bool MarkAsUsed(int id); // Let's the user register an id.
// returns false if the id was already used.
bool IsUsed(int id); // Returns true if id is used.
};
Assume ids happen to start at 1 and progress, 2, 3, etc. This is not a requirement, just to help illustrate.
IdManager mgr;
mgr.MarkAsUsed(3);
printf ("%d\n", mgr.AllocateId());
printf ("%d\n", mgr.AllocateId());
printf ("%d\n", mgr.AllocateId());
Would print
1
2
4
Because id 3 has already been declared used.
What's the best container / algorithm to both remember which ids are used AND find a free id?
If you want to know the a specific use case, OpenGL's glGenTextures, glBindTexture and glDeleteTextures are equivalent to AllocateId, MarkAsUsed and FreeId
| My idea is to use std::set and Boost.interval so IdManager will hold a set of non-overlapping intervals of free IDs.
AllocateId() is very simple and very quick and just returns the left boundary of the first free interval. Other two methods are slightly more difficult because it might be necessary to split an existing interval or to merge two adjacent intervals. However they are also quite fast.
So this is an illustration of the idea of using intervals:
IdManager mgr; // Now there is one interval of free IDs: [1..MAX_INT]
mgr.MarkAsUsed(3);// Now there are two interval of free IDs: [1..2], [4..MAX_INT]
mgr.AllocateId(); // two intervals: [2..2], [4..MAX_INT]
mgr.AllocateId(); // Now there is one interval: [4..MAX_INT]
mgr.AllocateId(); // Now there is one interval: [5..MAX_INT]
This is code itself:
#include <boost/numeric/interval.hpp>
#include <limits>
#include <set>
#include <iostream>
class id_interval
{
public:
id_interval(int ll, int uu) : value_(ll,uu) {}
bool operator < (const id_interval& ) const;
int left() const { return value_.lower(); }
int right() const { return value_.upper(); }
private:
boost::numeric::interval<int> value_;
};
class IdManager {
public:
IdManager();
int AllocateId(); // Allocates an id
void FreeId(int id); // Frees an id so it can be used again
bool MarkAsUsed(int id); // Let's the user register an id.
private:
typedef std::set<id_interval> id_intervals_t;
id_intervals_t free_;
};
IdManager::IdManager()
{
free_.insert(id_interval(1, std::numeric_limits<int>::max()));
}
int IdManager::AllocateId()
{
id_interval first = *(free_.begin());
int free_id = first.left();
free_.erase(free_.begin());
if (first.left() + 1 <= first.right()) {
free_.insert(id_interval(first.left() + 1 , first.right()));
}
return free_id;
}
bool IdManager::MarkAsUsed(int id)
{
id_intervals_t::iterator it = free_.find(id_interval(id,id));
if (it == free_.end()) {
return false;
} else {
id_interval free_interval = *(it);
free_.erase (it);
if (free_interval.left() < id) {
free_.insert(id_interval(free_interval.left(), id-1));
}
if (id +1 <= free_interval.right() ) {
free_.insert(id_interval(id+1, free_interval.right()));
}
return true;
}
}
void IdManager::FreeId(int id)
{
id_intervals_t::iterator it = free_.find(id_interval(id,id));
if (it != free_.end() && it->left() <= id && it->right() > id) {
return ;
}
it = free_.upper_bound(id_interval(id,id));
if (it == free_.end()) {
return ;
} else {
id_interval free_interval = *(it);
if (id + 1 != free_interval.left()) {
free_.insert(id_interval(id, id));
} else {
if (it != free_.begin()) {
id_intervals_t::iterator it_2 = it;
--it_2;
if (it_2->right() + 1 == id ) {
id_interval free_interval_2 = *(it_2);
free_.erase(it);
free_.erase(it_2);
free_.insert(
id_interval(free_interval_2.left(),
free_interval.right()));
} else {
free_.erase(it);
free_.insert(id_interval(id, free_interval.right()));
}
} else {
free_.erase(it);
free_.insert(id_interval(id, free_interval.right()));
}
}
}
}
bool id_interval::operator < (const id_interval& s) const
{
return
(value_.lower() < s.value_.lower()) &&
(value_.upper() < s.value_.lower());
}
int main()
{
IdManager mgr;
mgr.MarkAsUsed(3);
printf ("%d\n", mgr.AllocateId());
printf ("%d\n", mgr.AllocateId());
printf ("%d\n", mgr.AllocateId());
return 0;
}
|
2,620,314 | 2,620,376 | C++ type-checking at compile-time | all. I'm pretty new to C++, and I'm writing a small library (mostly for my own projects) in C++. In the process of designing a type hierarchy, I've run into the problem of defining the assignment operator.
I've taken the basic approach that was eventually reached in this article, which is that for every class MyClass in a hierarchy derived from a class Base you define two assignment operators like so:
class MyClass: public Base {
public:
MyClass& operator =(MyClass const& rhs);
virtual MyClass& operator =(Base const& rhs);
};
// automatically gets defined, so we make it call the virtual function below
MyClass& MyClass::operator =(MyClass const& rhs);
{
return (*this = static_cast<Base const&>(rhs));
}
MyClass& MyClass::operator =(Base const& rhs);
{
assert(typeid(rhs) == typeid(*this)); // assigning to different types is a logical error
MyClass const& casted_rhs = dynamic_cast<MyClass const&>(rhs);
try {
// allocate new variables
Base::operator =(rhs);
} catch(...) {
// delete the allocated variables
throw;
}
// assign to member variables
}
The part I'm concerned with is the assertion for type equality. Since I'm writing a library, where assertions will presumably be compiled out of the final result, this has led me to go with a scheme that looks more like this:
class MyClass: public Base {
public:
operator =(MyClass const& rhs); // etc
virtual inline MyClass& operator =(Base const& rhs)
{
assert(typeid(rhs) == typeid(*this));
return this->set(static_cast<Base const&>(rhs));
}
private:
MyClass& set(Base const& rhs); // same basic thing
};
But I've been wondering if I could check the types at compile-time. I looked into Boost.TypeTraits, and I came close by doing BOOST_MPL_ASSERT((boost::is_same<BOOST_TYPEOF(*this), BOOST_TYPEOF(rhs)>));, but since rhs is declared as a reference to the parent class and not the derived class, it choked.
Now that I think about it, my reasoning seems silly -- I was hoping that since the function was inline, it would be able to check the actual parameters themselves, but of course the preprocessor always gets run before the compiler. But I was wondering if anyone knew of any other way I could enforce this kind of check at compile-time.
| You can't perform this assert at compile time for the simple reason that the run-time types won't be known until, well, run time.
assert(typeid(rhs) == typeid(*this));
return this->set(static_cast<Base const&>(rhs));
In the non-inline version you had dynamic_cast. I would retain this so that you get a well-defined error and not undefined behaviour if your assertion is violated.
If you do this the assertion is either overly restrictive or pointless. The dynamic_cast will throw a bad_cast exception in both debug and release builds. This is what you want.
Personally, I would question the whole polymorphic assignment issue. I would follow Scott Meyers' Effective C++ advise and make all your non-leaf nodes in the inheritance hierarchy abstract. You can then make the base class assignment operators protected and non-virtual.
This enables you to use their implementation in derived classes assignment operator but prevents clients from slicing objects. If a client class has only a base class reference or pointer it is questionable whether the should be attempting to assign to the class anyway. If the do, they should be responsible for the casting and type safety guarantees.
|
2,620,324 | 2,620,361 | Allow member to be const while still supporting operator= on the class | I have several members in my class which are const and can therefore only be initialised via the initialiser list like so:
class MyItemT
{
public:
MyItemT(const MyPacketT& aMyPacket, const MyInfoT& aMyInfo)
: mMyPacket(aMyPacket),
mMyInfo(aMyInfo)
{
}
private:
const MyPacketT mMyPacket;
const MyInfoT mMyInfo;
};
My class can be used in some of our internally defined container classes (e.g. vectors), and these containers require that operator= is defined in the class.
Of course, my operator= needs to do something like this:
MyItemT&
MyItemT::operator=(const MyItemT& other)
{
mMyPacket = other.mPacket;
mMyInfo = other.mMyInfo;
return *this;
}
which of course doesn't work because mMyPacket and mMyInfo are const members.
Other than making these members non-const (which I don't want to do), any ideas about how I could fix this?
| You're kind of violating the definition of const if you have an assignment operator that can change them after construction has finished. If you really need to, I think Potatoswatter's placement new method is probably best, but if you have an assignment operator your variables aren't really const, since someone could just make a new instance and use it to change their values
|
2,620,357 | 2,620,426 | Can a stack have an exception safe method for returning and removing the top element with move semantics? | In an answer to a question about std::stack::pop() I claimed that the reason pop does not return the value is for exception safety reason (what happens if the copy constructor throws).
@Konrad commented that now with move semantics this is no longer relevant. Is this true?
AFAIK, move constructors can throw, but perhaps with noexcept it can still be achieved.
For bonus points what thread safety guarantees can this operation supply?
| Of course, not every type is move-enabled and C++0x even allows throwing move constructors. As long as constructing the object from an rvalue may throw it cannot be exception-safe. However, move semantics allows you to have many types that are nothrow-constructible given an rvalue source.
Conditional support for this could be done with SFINAE. But even without such a conditional member function nothing stops you from writing:
auto stack = ...;
auto elem = std::move_if_noexcept(stack.back());
stack.pop_back();
which is makes the strong exception guarantee even in case your move constructor doesn't give the strong guarantee.
|
2,620,377 | 2,620,398 | Lua - Reflection - Get list of functions/fields on an object? | I'm new to Lua and dealing with Lua as a scripting language in an alpha release of a program. The developer is unresponsive and I need to get a list of functions provided by some C++ objects which are accessible from the Lua code.
Is there any easy way to see what fields and functions these objects expose?
| In Lua, to view the members of a object, you can use:
for key,value in pairs(o) do
print("found member " .. key);
end
Unfortunately I don't know if this will work for objects imported from C++.
|
2,620,409 | 2,620,573 | Getting HWND of current Process | I have a process in c++ in which I am using window API. I want to get the HWND of own process. Kindly guide me how can I make it possible.
| You are (incorrectly) assuming that a process has only a single HWND. This is not generally true, and therefore Windows can't offer an API to get it. A program could create two windows, and have two HWNDs as a result. OTOH, if your program creates only a single window, it can store that HWND in a global variable.
|
2,620,845 | 2,620,914 | Sudden windows shut down during programming with Borland C++ followed by a blue screen! | This problem has happened to me twice.Both times during programming with Borland C++.when i wanted to run the simple code bellow:(completely what I wrote)
int n, total=0, counter=1,average;
while ( n )
{
cin >> n;
total = total + n;
average = total / counter;
counter++;
cout <<average<<endl;
}
| BSOD is almost always a hardware or driver issue. It could be that a particular sequence of program operations is exercising something that is failing.
Best thing to do is look at the memory dump in MS' analyzer to see if that points to a specific software item.
|
2,620,862 | 46,128,321 | Using custom std::set comparator | I am trying to change the default order of the items in a set of integers to be lexicographic instead of numeric, and I can't get the following to compile with g++:
file.cpp:
bool lex_compare(const int64_t &a, const int64_t &b)
{
stringstream s1,s2;
s1 << a;
s2 << b;
return s1.str() < s2.str();
}
void foo()
{
set<int64_t, lex_compare> s;
s.insert(1);
...
}
I get the following error:
error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Compare, class _Alloc> class std::set’
error: expected a type, got ‘lex_compare’
what am I doing wrong?
| 1. Modern C++20 solution
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s;
We use lambda function as comparator. As usual, comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
Online demo
2. Modern C++11 solution
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s(cmp);
Before C++20 we need to pass lambda as argument to set constructor
Online demo
3. Similar to first solution, but with function instead of lambda
Make comparator as usual boolean function
bool cmp(int a, int b) {
return ...;
}
Then use it, either this way:
std::set<int, decltype(cmp)*> s(cmp);
Online demo
or this way:
std::set<int, decltype(&cmp)> s(&cmp);
Online demo
4. Old solution using struct with () operator
struct cmp {
bool operator() (int a, int b) const {
return ...
}
};
// ...
// later
std::set<int, cmp> s;
Online demo
5. Alternative solution: create struct from boolean function
Take boolean function
bool cmp(int a, int b) {
return ...;
}
And make struct from it using std::integral_constant
#include <type_traits>
using Cmp = std::integral_constant<decltype(&cmp), &cmp>;
Finally, use the struct as comparator
std::set<X, Cmp> set;
Online demo
|
2,621,066 | 2,621,236 | Calling unmanaged dll from C#. Take 2 | I have written a c# program that calls a c++ dll that echoes the commandline args to a file
When the c++ is called using the rundll32 command it displays the commandline args no problem, however when it is called from within the c# it doesnt.
I asked this question to try and solve my problem, but I have modified it my test environment and I think it is worth asking a new question.
Here is the c++ dll
#include "stdafx.h"
#include "stdlib.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
extern "C" __declspec(dllexport) int WINAPI CMAKEX(
HWND hwnd,
HINSTANCE hinst,
LPCSTR lpszCommandLine,
DWORD dwReserved)
{
ofstream SaveFile("output.txt");
SaveFile << lpszCommandLine;
SaveFile.close();
return 0;
}
Here is the c# app
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Net;
namespace nac
{
class Program
{
[DllImport("cmakca.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool CMAKEX(IntPtr hwnd, IntPtr hinst, string lpszCmdLine, int nCmdShow);
static void Main(string[] args)
{
string cmdLine = @"/source_filename proxy-1.txt /backup_filename proxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /profile ""C:\Documents and Settings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp""";
const int SW_SHOWNORMAL = 1;
CMAKEX(IntPtr.Zero, IntPtr.Zero, cmdLine, SW_SHOWNORMAL).ToString();
}
}
}
The output from the rundll32 command is
rundll32 cmakex.dll,CMAKEX /source_filename proxy-1.txt /backup_filename proxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /profile ""C:\Documents and Settings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp"
/source_filename proxy-1.txt /backup_filename proxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /profile ""C:\Documents and Settings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp"
however the output when the c# app runs is
/
| LPCSTR is not unicode, is it? Just use ANSI and you should be fine: CharSet = CharSet.Ansi
|
2,621,136 | 2,621,233 | Compiling and using NTL c++ library for Windows | I have compiled the NTL inifite precision integer arithmetic library for c++, using Microsoft Visual Studio 2008. I did as explained, on this site, using the Visual Studio interface, rather than from the command prompt. Actually I would rather do it from the command prompt, but I was not sure how to.
Anyhow, I got the library compiled, and I now want to compile a program using the library, from the command prompt. The program I am trying to compile, has been tested on a linux system, where I compile it with the following
c++ -I/appl/htopopt/Linux_x86_64/NTL-5.4.2/include mpqs.cpp main.cpp -o main -L/appl/htopopt/Linux_x86_64/NTL-5.4.2/lib -lntl -L/appl/htopopt/Linux_x86_64/gmp-4.2.1/lib -lgmp -lm
Nevermind the gmp stuff, I dont have that installed on Windows. It is purely an optional thing that will make the NTL run faster. Anyhow, this works fine on linux. Now on Windows I write the following
cl /EHsc /I D:\Downloads\WinNTL-5_5_2\include mpqs.cpp main.cpp /link /LIBPATH:"D:\Documents\Visual Studio 2008\Projects\ntl\Debug"
But this results in the following errors:
mpqs.cpp
mpqs.cpp(38) : error C2039: 'find_smooth_vals' : is not a member of 'QS'
d:\desktop\qs\mpqs.h(12) : see declaration of 'QS'
mpqs.cpp(41) : error C2065: 'M' : undeclared identifier
mpqs.cpp(41) : error C2065: 'n' : undeclared identifier
mpqs.cpp(42) : error C2065: 'sieve_table' : undeclared identifier
mpqs.cpp(42) : error C2228: left of '.size' must have class/struct/union
type is ''unknown-type''
mpqs.cpp(43) : error C2065: 'sieve_table' : undeclared identifier
mpqs.cpp(44) : error C2065: 'qx_table' : undeclared identifier
mpqs.cpp(44) : error C3861: 'test_smoothness': identifier not found
mpqs.cpp(45) : error C2065: 'smooth_indices' : undeclared identifier
mpqs.cpp(45) : error C2228: left of '.push_back' must have class/struct/union
type is ''unknown-type''
main.cpp
Generating Code...
It is as if, my mpqs.h file is not included into the compilation process? Also I dont understand why it complains about .push_back() for a vector type?
Help is much appreciated!
| mpqs.h is definitely being included as the output asks you to refer to it.
Seeing as MPQS.h does not appear to be included in the NTL library ... did you write it? If so can you post the code up?
Also, shouldn't you included the library file somewhere on your build?
Edit: There is no function find_smooth_values so why should you expect MSVC to find it? I'm not sure why that compiles under GCC but its obviously missing. I'm guessing that the other errors are caused because of this one. The errors are telling you things. You should listen to them.
push_back is failing because it doesn't know what the type you are trying to push_back into is. This again is probably caused by the fact that find_smooth_values doesn't exist. Try adding the function prototype into the QS class. This may well fix all your problems.
As for the library it won't get to using the library until the compilation succeeds. So don't worry about that just now. Get in there and fix the errors that MSVC is reporting!
|
2,621,436 | 2,627,183 | Accidental Complexity in OpenSSL HMAC functions | SSL Documentation Analaysis
This question is pertaining the usage of the HMAC routines in OpenSSL.
Since Openssl documentation is a tad on the weak side in certain areas, profiling has revealed that using the:
unsigned char *HMAC(const EVP_MD *evp_md, const void *key,
int key_len, const unsigned char *d, int n,
unsigned char *md, unsigned int *md_len);
From here, shows 40% of my library runtime is devoted to creating and taking down HMAC_CTX's behind the scenes.
There are also two additional function to create and destroy a HMAC_CTX explicetly:
HMAC_CTX_init() initialises a HMAC_CTX
before first use. It must be called.
HMAC_CTX_cleanup() erases the key and
other data from the HMAC_CTX and
releases any associated resources. It
must be called when an HMAC_CTX is no
longer required.
These two function calls are prefixed with:
The following functions may be used if
the message is not completely stored
in memory
My data fits entirely in memory, so I choose the HMAC function -- the one whose signature is shown above.
The context, as described by the man page, is made use of by using the following two functions:
HMAC_Update() can be called repeatedly
with chunks of the message to be
authenticated (len bytes at data).
HMAC_Final() places the message
authentication code in md, which must
have space for the hash function
output.
The Scope of the Application
My application generates a authentic (HMAC, which is also used a nonce), CBC-BF encrypted protocol buffer string. The code will be interfaced with various web-servers and frameworks Windows / Linux as OS, nginx, Apache and IIS as webservers and Python / .NET and C++ web-server filters.
The description above should clarify that the library needs to be thread safe, and potentially have resumeable processing state -- i.e., lightweight threads sharing a OS thread (which might leave thread local memory out of the picture).
The Question
How do I get rid of the 40% overhead on each invocation in a (1) thread-safe / (2) resume-able state way ? (2) is optional since I have all of the source-data present in one go, and can make sure a digest is created in place without relinquishing control of the thread mid-digest-creation. So,
(1) can probably be done using thread local memory -- but how do I resuse the CTX's ? does the HMAC_final() call make the CTX reusable ?.
(2) optional: in this case I would have to create a pool of CTX's.
(3) how does the HMAC function do this ? does it create a CTX in the scope of the function call and destroy it ?
Psuedocode and commentary will be useful.
| The documentation for the HMAC_Init_ex() function in OpenSSL 0.9.8g says:
HMAC_Init_ex() initializes or reuses a
HMAC_CTX structure to use the function
evp_md and key key. Either can be
NULL, in which case the existing one
will be reused.
(Emphasis mine). So this means that you can initialise a HMAC_CTX with HMAC_CTX_Init() once, then keep it around to create multiple HMACs with, as long as you don't call HMAC_CTX_cleanup() on it and you start off each HMAC with HMAC_Init_ex().
So yes, you should be able to do what you want with a HMAC_CTX in thread-local memory.
|
2,621,460 | 2,621,476 | operators computing direction | I encountered something that I can't understand.
I have this code:
cout << "f1 * f1 + f2 * f1 - f1 / f2 is: "<< f1 * f1 + f2 * f1 - f1 / f2 << endl;
All the "f"s are objects, and all the operators are overloaded.
The weird this is that the first computation is of the / operator,
then the second * and then the first *; after that, the operator + and at last, operator -.
So basically, the / and * worked from right to left,
and the + and - operators worked from left to right.
I made another test...
I checked this code:
cout << "f1 * f1 / f2 is: " << f1 * f1 / f2 << endl;
Now, the first operator was * and only then operator /.
So now, it worked from left to right.
Can someone help me understand why is there difference in the directions?
10X!
| This is yet again a question of the order of evaluation of function parameters - C++ does not specify such an order. Your code is equivalent to:
(f1 * f1) + (f2 * f1) - (f1 / f2)
The three multiply and divide operations can be evaluated in any order. This is perhaps cleraer for named functions:
add(f1*f2,f2*f1)).minus(f1/f2);
The bottom line is that associativity and precedence have nothing to say about the order of evaluation of function parameters and/or sub-expressions. Given the simple expression:
a + b
the C++ (and C) compiler is free to evaluate a first, then b, or b first then a, whether or not the '+' is overloaded.
|
2,621,548 | 2,621,596 | Program ends abruptly even in debugger - how did that happen? | I am trying to debug a program that unexpectedly shuts down. When I say "shuts down, I mean one moment I am seeing all the windows being displayed, each of which is showing all the right data,then suddenly all the windows disappear. The is no messagebox reporting anything wrong. So I tried running the program in the debugger hoping that it would somehow trap whatever was causing the program to abort, but even within the debugger the program simply ends abruptly. The last line in the debugger is:
The program '[5500] test.exe: Native' has exited with code 0 (0x0).
My program, which is extremely large and extremely old, has a lot of self diagnostics. My suspicion is that perhaps a self test has failed and maybe I just called "exit()", forgetting to pop up a dialog explaining why.
My question now is, how can I find out from which point in the code, my program quit?
| Marcelo's answer is great. If for some reason you can't break on exit, install a function (takes no arguments, returns void) with atexit and break inside that.
|
2,621,650 | 2,621,656 | Return reference from class to this | I have the following member of class foo.
foo &foo::bar()
{
return this;
}
But I am getting compiler errors. What stupid thing am I doing wrong?
Compiler error (gcc): error: invalid initialization of non-const reference of type 'foo&' from a temporary of type 'foo* const'
| this is a pointer. So it should be return *this;
|
2,621,845 | 2,626,947 | Void pointers in C++ | I have written this qsort:
void qsort(void *a[],int low,int high, int (*compare)(void*,void*));
When I call this on
char *strarr[5];
It says invalid conversion from char** to void**. Why this is wrong?
This is the code:
#include<cstdlib>
#include<cstdio>
#include<iostream>
using namespace std;
inline void strswap(void *a,void *b) {
char *t=*(char**)a;
*(char**)a=*(char**)b;
*(char**)b=t;
}
int strcompare(void *a, void *b) {
return strcmp(*(char**)a,*(char**)b);
}
void qsort1(void *a[],int low,int high, int (*compare)(void*,void*), void (*swap)(void*,void*)) {
if(low>=high)
return;
int q=low-1;
for(int i=low;i<=high-1;i++)
if((*compare)(&a[i],&a[high]) < 0)
swap(&a[i],&a[++q]);
swap(&a[high],&a[++q]);
qsort1(a,low,q-1,compare,swap);
qsort1(a,q+1,high,compare,swap);
}
int main() {
const int n=3;
//int a[n]={4,6,8,12,10,9,8,0,24,3};
char *strarr[5]={"abcd","zvb","cax"};
qsort1(strarr,0,n-1,strcompare,strswap);
for(int i=0;i<n;i++)
cout << strarr[i] << " ";
cout << endl;
return 0;
}
| An implicit conversion from any pointer type to void * is allowed, because void * is a defined to be a pointer type that has a sufficient range that it can represent any value that any other pointer type can. (Technically, only other object pointer types, which excludes pointers to functions).
This does not mean that void * has the same size or representation as any other pointer type, though: Converting a pointer from another pointer type to a void * does not necessarily leave the underlying representation unchanged. Converting from double * to void * is just like converting from double to int - it has to happen in full view of the compiler, you can't hide that conversion behind the compiler's back.
So this implies that while void * is a generic pointer, void ** is not a generic pointer-to-pointer. It's a pointer to void * - a void ** pointer should only ever point to real void * objects (whereas void * itself can point to anything).
This is why there's no implicit conversions between type ** and void ** - it's for the same reason that there's no implicit conversions between double * and int *.
Now, there is one special case: for historical reasons, char * is guaranteed to have the same size, representation and alignment requirements as void *. This means that conversions between char ** (in particular) and void ** are actually OK, as an exception to the general rule. So in your particular case, your code is correct if you add a cast to void ** when you pass strarr to qsort1().
However, your qsort1() is only defined to correctly work on arrays of void * or char * (including unsigned char * etc.). You can't use it to sort an array of double * pointers, for example (although it would actually work on most common environments today).
|
2,621,905 | 2,621,915 | sort array of size n | if an array of size n has only 3 values 0 ,1 and 2 (repeated any number of times) what is the best way to sort them. best indicates complexity. consider space and time complexity both
| Count the occurences of each number and afterward fill the array with the correct counts, this is O(n)
|
2,622,200 | 2,622,803 | Exceptions silently caught by Windows, how to handle manually? | We're having problems with Windows silently eating exceptions and allowing the application to continue running, when the exception is thrown inside the message pump. For example, we created a test MFC MDI application, and overrode OnDraw:
void CTestView::OnDraw(CDC* /*pDC*/)
{
*(int*)0 = 0; // Crash
CTestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: add draw code for native data here
}
You would expect a nasty error message when running the application, but you actually get nothing at all. The program appears to be running perfectly well, but if you check the output window you will see:
First-chance exception at
0x13929384 in Test.exe:
0xC0000005: Access violation writing
location 0x00000000.
First-chance exception at 0x77c6ee42
in Test.exe: 0xC0150010: The
activation context being deactivated
is not active for the current thread
of execution.
I know why I'm receiving the application context exception, but why is it being handled silently? It means our applications could be suffering serious problems when in use, but we'll never know about it, because our users will never report any problems.
| After browsing similar questions I stumbled across this answer:
OpenGL suppresses exceptions in MFC dialog-based application
"Ok, I found out some more information
about this. In my case it's windows 7
that installs
KiUserCallbackExceptionHandler as
exception handler, before calling my
WndProc and giving me execution
control. This is done by
ntdll!KiUserCallbackDispatcher. I
suspect that this is a security
measure taken by Microsoft to prevent
hacking into SEH.
The solution is to wrap your wndproc
(or hookproc) with a try/except
frame."
I've filed a bug report with Microsoft, you can see their response here:
http://connect.microsoft.com/VisualStudio/feedback/details/550944/hardware-exceptions-on-x64-machines-are-silently-caught-in-wndproc-messages
From Microsoft:
Thanks for the report. I've found out that this is a Windows issue,
and there is a hot fix available. Please see
http://support.microsoft.com/kb/976038 for a fix that you can install
if you wish.
|
2,622,246 | 2,622,697 | Access to Oracle Database with sqlapi C++ | I need to write some data in several database.
I choose sqlapi.com
I have made it for mysql and mssql.
Now I have Problem with Oracle database.
I have installed server and client on Ubuntu.
In browser it works, but sqlapi says:
libnnz10.so: cannot open shared object
file: No such file or directory
DBMS API Library 'libclntsh.so'
loading fails
This library is a part of DBMS client
installation, not SQLAPI++
Make sure DBMS client is installed and
this required library is available for
dynamic loading
Linux/Unix:
1) The directories in the user's
LD_LIBRARY_PATH environment variable
2) The list of libraries cached in
/etc/ld.so.cache
3) /usr/lib, followed by /lib
There are both of these files depp inside /usr/lib.
I have tried a lot of ways to say eclipse path to this folder, but nothing works.
Thanks for help.
| I think that you need to set the variable LD_LIBRARY_PATH to the file path of the shared lib.
e.g.
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/oracle/instantclient/lib
set the variable in .profile or .bash_profile. This depends on the shell you are using.
Update
Due to some new security requirements in ubuntu (see https://bugs.launchpad.net/ubuntu/+bug/366728 for details) you cannot use LD_LIBRARY_PATH for non-interactive shells. Use the following procedure (adjust the oracle path to your needs):
echo "/opt/oracle/product/whatever/lib" | sudo tee /etc/ld.so.conf.d/oracle.conf
sudo ldconfig -v
|
2,622,441 | 2,622,459 | C++ integer floor function | I want to implement greatest integer function. [The "greatest integer function" is a quite standard name for what is also known as the floor function.]
int x = 5/3;
My question is with greater numbers could there be a loss of precision as 5/3 would produce a double?
EDIT: Greatest integer function is integer less than or equal to X.
Example:
4.5 = 4
4 = 4
3.2 = 3
3 = 3
What I want to know is 5/3 going to produce a double? Because if so I will have loss of precision when converting to int.
Hope this makes sense.
| You will lose the fractional portion of the quotient. So yes, with greater numbers you will have more relative precision, such as compared with 5000/3000.
However, 5 / 3 will return an integer, not a double. To force it to divide as double, typecast the dividend as static_cast<double>(5) / 3.
|
2,622,755 | 2,622,828 | Refresh text shown in a GTK+ widget? | Being resonably new to using GTK+, im not fully aware of all its functionality.
Basically, I have a GtkTreeView widget that has 4 Columns. I need to update the text displayed in the 4 columns every couple of seconds, but im not aware how to do this in GTK+.
I'm aware that I could flush the data using gtk_tree_store_clear, but I'm not sure how to repopulate the columns and have the top level window refresh to show this new data?
| You need to get a GtkTreeIter to the proper row, then use the appropriate (model-specific) setter to change the data.
For instance gtk_list_store_set() for the GtkListStore model.
There is no need to clear the entire model if you just want to change some of the data, that is very wasteful and slow.
If you really need to change all the data, then sure, clear it.
You don't have to worry about getting the display to refresh; the view listens to events from the model, and automatically knows to refresh when the model changes.
UPDATE:
When changing the data (as described in commment), you don't need to "flush" the old data. The model owns the data, and knows how to keep track of the memory used. You just use the above-mentioned gtk_list_store_set() call as necessary to put the new desired data in the model. You can do this as often as necessary, and an update frequency of once every few seconds should be no problem at all.
Of course, in such a case, to keep your application (which I assume is single-threaded, for simplicity) responsive, you must have a way to asynchronously trigger an update, perhaps using a timer. Have a look at glib's g_timeout_add() function to learn how to add a simple global timer.
|
2,623,165 | 2,623,552 | CreateFileMapping MapViewOfFile | With win32api, I want that the following program creates two process and creates a filemap. (using c++)
i don't know what i should write at Handle CreateFileMapping(....
I've tried it with:
PROCCESS_INFORMATION hfile.
Furthermore the first parameter should be INVALID_HANDLE_VALUE, but then i don't know what to write into MapViewOfFile as first parameter.
the code from the first program: (i didn't programmed the 2.&3. because even the first doesn't work)
//Initial process creates proccess 2 and 3
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
void main()
{
bool ret;
bool retwait;
bool bhandleclose;
STARTUPINFO startupinfo;
GetStartupInfo (&startupinfo);
PROCESS_INFORMATION pro2info;
PROCESS_INFORMATION pro3info;
//create proccess 2
wchar_t wcsCommandLine[] = L"D:\\betriebssystemePRA2pro2.exe";
ret = CreateProcess(NULL, wcsCommandLine, NULL, NULL, false, CREATE_NEW_CONSOLE, NULL,
NULL, &startupinfo, &pro2info);
if (ret==false){
cout<<"Prozess konnte nicht erzeugt werden. Fehler:"<<GetLastError();
ExitProcess(0);
}
//***************
//create process3
wchar_t wcs2CommandLine[] = L"D:\\betriebssystemePRA2pro3.exe";
ret = CreateProcess(NULL, wcs2CommandLine, NULL, NULL, false, CREATE_NEW_CONSOLE, NULL,
NULL, &startupinfo, &pro3info);
if (ret==false){
cout<<"Prozess konnte nicht erzeugt werden. Fehler:"<<GetLastError();
ExitProcess(0);
}
//***************
//create mapping object
// program2:
PROCESS_INFORMATION hfile;
CreateFileMapping( //erzeugt filemapping obj returned ein handle
INVALID_HANDLE_VALUE, //mit dem handle-->kein seperates file nötig
NULL,
PAGE_READWRITE, //rechte (lesen&schreiben)
0,
5,
L"myfile"); //systemweit bekannter name
LPVOID mappointer = MapViewOfFile( //virtuelle speicherraum, return :zeiger, der auf den bereich zeigt
INVALID_HANDLE_VALUE, //handle des filemappingobj.
FILE_MAP_ALL_ACCESS,
0,
0,
100);
//wait
cout<<"beliebige Taste druecken"<<endl;
cin.get();
//close
bool unmap;
unmap = UnmapViewOfFile (mappointer);
if (unmap==true)
cout<<"Unmap erfolgreich"<<endl;
else
cout<<"Unmap nicht erfolgreich"<<endl;
bhandleclose=CloseHandle (INVALID_HANDLE_VALUE);
cout<<bhandleclose<<endl;
bhandleclose=CloseHandle (pro2info.hProcess);
bhandleclose=CloseHandle (pro3info.hProcess);
ExitProcess(0);
}
| MapViewOfFile takes the handle returned by CreateFileMapping:
HANDLE hFileMapping = CreateFileMapping(...);
LPVOID lpBaseAddress = MapViewOfFile(hFileMapping, ...);
|
2,623,277 | 2,664,601 | What can I access in Androids Native libraries? And How? | I am completely new to the NDK.
I have done a couple of the tutorials including the hello from jni one
and another one that calculates the sum of two numbers.
They involved using cygwin and the ndk to create the library so file
and I have a bit of a grasp on how to insert my own libraries into the
libraries layer of Android.
I have now been asked to access the native libraries on Android and
see what I can use them for.
My question is can I do this?
The STABLE-APIS.txt document is a bit vague and mentions the following
as Stable C++ API's in Android 1.5
cstddef
new
utility
stl_pair.h
Does that mean I can access them?
If so then how do I go about it? I dont think that following the
tutorials I have already done would be any help?
Any pointers on how to do this or links to tutorials etc.. would be
greatly appreciated
| As others pointed out on the android-ndk group, you probably should just use the SDK. The NDK doesn't give you access to any features beyond those available with the SDK and it reduces the portability of your application. You should only consider it if you have legacy code written C or C++ (that doesn't use exceptions or RTTI). While some operations are much faster in native code, passing data between managed and native code is expensive and thus using the NDK only speeds up certain types of applications.
|
2,623,396 | 2,626,913 | Boost Thread Specific Storage Question (boost/thread/tss.hpp) | The boost threading library has an abstraction for thread specific (local) storage. I have skimmed over the source code and it seems that the TSS functionality can be used in an application with any existing thread regardless of weather it was created from boost::thread --i.e., this implies that certain callbacks are registered with the kernel to hook in a callback function that may call the destructor of any TSS objects when the thread or process is going out of scope. I have found these callbacks.
I need to cache HMAC_CTX's from OpenSSL inside the worker threads of various web-servers (see this, detailed, question for what I am trying to do), and as such I do not controll the life-time of the thread -- the web-server does. Therefore I will use the TSS functionality on threads not created by boost::thread.
I just wanted to validate my assumptions before I started implementing the caching logic, are there any flaws in my logic ?
| You're right. You can use it for threads not created by boost::thread.
If you look in test_tss.cpp you can see they test exactly that, and it should work with both POSIX and Windows threads.
|
2,623,566 | 2,623,693 | How much effort do you have to put in to get gains from using SSE? | Case One
Say you have a little class:
class Point3D
{
private:
float x,y,z;
public:
operator+=()
...etc
};
Point3D &Point3D::operator+=(Point3D &other)
{
this->x += other.x;
this->y += other.y;
this->z += other.z;
}
A naive use of SSE would simply replace these function bodies with using a few intrinsics. But would we expect this to make much difference? MMX used to involve costly state cahnges IIRC, does SSE or are they just like other instructions? And even if there's no direct "use SSE" overhead, would moving the values into SSE registers and back out again really make it any faster?
Case Two
Instead, you're working with a less OO-based code base. Rather than an array/vector of Point3D objects, you simply have a big array of floats:
float coordinateData[NUM_POINTS*3];
void add(int i,int j) //yes it's unsafe, no overlap check... example only
{
for (int x=0;x<3;++x)
{
coordinateData[i*3+x] += coordinateData[j*3+x];
}
}
What about use of SSE here? Any better?
In conclusion
Is trying to optimise single vector operations using SSE actually worthwhile, or is it really only valuable when doing bulk operations?
| In general you will need to take additional steps to get the best out of SSE (or any other SIMD architecture):
data needs to be 16 byte aligned (ideally)
data needs to be contiguous
you need enough data to make the SIMD operation worthwhile
you need to coalesce as many operations as you can to mitigate the costs of loads/stores
you need to be aware of the cache/memory hierarchy and its performance impact (e.g. use strip-mining/tiling)
|
2,623,843 | 2,656,556 | Make process crash on large memory allocation | I'm trying to find a significant memory leak (15MB at a time, but doing allocations like this on multiple places). I checked the most obvious places, and then used AQTime, but I still can't pinpoint it. Now I see 2 options left:
1) Use SetProcessWorkingSetSize: I've tried this but my process happily keeps on running when using up more then 150MB:
DWORD MemorySize = 150*1024*1024;
SetProcessWorkingSetSize( GetCurrentProcess(), MemorySize/2, MemorySize*2 );
2) Put a breakpoint when allocating more then 1MB at a time. How should I do this, overload operator new with an 'if>1MB' inside ?
| Sorry all, none of the proposed solutions worked. It finally got fixed using AQTime and a lot of debugoutput. The leak got cleaned on shutdown, so it was looking for a needle in a haystack.
Still I'm interested in how to efficiently find this though. I tried to put a conditional breakpoint on the new operator, but the debugger took ages to evaluate "bytes > 1024 * 1024" for every single allocation.
|
2,623,881 | 2,624,020 | Special Characters on Console | I've finished my poker game but now I want to make it look a bit better with displaying Spades, Hearts, Diamonds and Clubs. I tried this answer: C++: Printing ASCII Heart and Diamonds With Platform Independent
Maybe stupid but I try:
cout << 'U+2662' << endl;
I don't know how to write it.
| To output a UTF-8 character, you need to encode it as hex bytes. I'll steal this link to fileinfo.com from an answer to the question you linked - if you jump to the UTF-8 representation, it says 0xE2 0x99 0xA5 and you can convert that to "\xE2\x99\xA5" as a string.
However I can't guarantee that your console will display UTF-8 so this answer might not help.
|
2,623,927 | 2,624,613 | ERROR_MORE_DATA ---- Reading from Registry | I am trying to create an offline registry in memory using the offreg.dll provided in the windows ddk 7 package.
You can find out more information on the offreg.dll here: MSDN
Currently, while attempting to read a value from an open registry hive / key I receive the following error: 234 or ERROR_MORE_DATA
Here is the .h code that contains ORGetValue:
DWORD
ORAPI
ORGetValue (
__in ORHKEY Handle,
__in_opt PCWSTR lpSubKey,
__in_opt PCWSTR lpValue,
__out_opt PDWORD pdwType,
__out_bcount_opt(*pcbData) PVOID pvData,
__inout_opt PDWORD pcbData
);
Here is the code that I am using to pull the data
[DllImport("offreg.dll", CharSet = CharSet.Auto, EntryPoint = "ORGetValue", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
public static extern uint ORGetValue(IntPtr Handle, string lpSubKey, string lpValue, out uint pdwType, out string pvData, out uint pcbData);
IntPtr myHive;
IntPtr myKey;
string myValue;
uint pdwtype;
uint pcbdata;
uint ret3 = ORGetValue(myKey, "", "DefaultUserName", out pdwtype, out myValue, out pcbdata);
The goal is to be able to read myValue as a string.
I am not sure if I need to use marshaling... or a second call with an adjusted buffer.. Or really how to adjust the buffer in C#. Any help or pointers would be greatly appreciated.
Thank you.
| The attribute on the pcbData argument is wrong, it is ref, not out. You need to initialize it to the Capacity of the StringBuilder you pass for the pvData argument. Right now the API function probably sees a 0 so will return the error code.
It ought to look something like this:
[DllImport("offreg.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern uint ORGetValue(IntPtr Handle, string lpSubKey, string lpValue, out int pdwType, StringBuilder pvData, ref int pcbData);
int pdwtype;
var buffer = new StringBuilder(256);
int pcbdata = buffer.Capacity;
uint ret3 = ORGetValue(myKey, "", "DefaultUserName", out pdwtype, buffer, ref pcbdata);
string myValue = buffer.ToString();
|
2,624,022 | 2,624,036 | What is the different purpose of .H header file and a IDL file? | I am studying COM so there're some basic questions puzzling me...
I know that IDL file is used to describe the method definitions (or the so called 'contract' between software modules), and the .H header files contains something like a method prototype, which looks similar to what the IDL is meant for. So, why are these two things coexist? Isn't one enough?
Many thanks.
| Interface description language (IDL) is a small language in itself which provides a programming language independent way to describe an interface. Tools generate .h files from your .idl.
If you only had a .h file it would be impossible to tie into it with another programming language. .h files are very specific to C and C++ code only.
Some other differences are that in .h files you can sometimes have implementation as well as declaration, as well as class member variables. Whereas in IDL you are strictly defining an interface.
|
2,624,232 | 2,624,242 | How to change a particular element of a C++ STL vector | vector<int> l;
for(int i=1;i<=10;i++){
l.push_back(i);
}
Now, for example, how do I change the 5th element of the vector to -1?
I tried l.assign(4, -1);
It is not behaving as expected. None of the other vector methods seem to fit.
I have used vector as I need random access functionality in my code (using l.at(i)).
| at and operator[] both return a reference to the indexed element, so you can simply use:
l.at(4) = -1;
or
l[4] = -1;
|
2,624,238 | 2,624,474 | c++ undefined references with static library | I'm trying to make a static library from a class but when trying to use it, I always get errors with undefined references on anything. The way I proceeded was creating the object file like
g++ -c myClass.cpp -o myClass.o
and then packing it with
ar rcs myClass.lib myClass.o
There is something I'm obviously missing generally with this. I bet it's something with symbols.
Thanks for any advice, I know it's most probably something I could find out if reading some tutorial so sorry if bothering with stupid stuff again :)
edit:
myClass.h:
class myClass{
public:
myClass();
void function();
};
myClass.cpp:
#include "myClass.h"
myClass::myClass(){}
void myClass::function(){}
program using the class:
#include "myClass.h"
int main(){
myClass mc;
mc.function();
return 0;
}
finally I compile it like this:
g++ -o main.exe -L. -l myClass main.cpp
the error is just classic:
C:\Users\RULERO~1\AppData\Local\Temp/ccwM3vLy.o:main.cpp:(.text+0x31): undefined
reference to `myClass::myClass()'
C:\Users\RULERO~1\AppData\Local\Temp/ccwM3vLy.o:main.cpp:(.text+0x3c): undefined
reference to `myClass::function()'
collect2: ld returned 1 exit status
| This is probably a link order problem. When the GNU linker sees a library, it discards all symbols that it doesn't need. In this case, your library appears before your .cpp file, so the library is being discarded before the .cpp file is compiled. Do this:
g++ -o main.exe main.cpp -L. -lmylib
or
g++ -o main.exe main.cpp myClass.lib
The Microsoft linker doesn't consider the ordering of the libraries on the command line.
|
2,624,257 | 2,624,279 | Percentage calculation around 0.5 (0.4 = -20% and 0.6 = +20%) | I'm in a strange situation where I have a value of 0.5 and I want to convert the values from 0.5 to 1 to be a percentage and from 0.5 to 0 to be a negative percentage.
As it says in the title 0.4 should be -20%, 0.3 should be -40% and 0.1 should be -80%.
I'm sure this is a simple problem, but my mind is just refusing to figure it out :)
Can anyone help? :)
| What we want to do is to scale the range (0; 1) to (-100; 100):
percentage = (value - 0.5) * 200;
The subtraction transforms the value so that it's in the range (-0.5; 0.5), and the multiplication scales it to the range of (-100; 100).
|
2,624,387 | 2,624,411 | Fastest possible algorithm to sum numbers up to N | I want a really fast algorithm or code in C to do the following task: sum all numbers from 1 to N for any given integer N, without assuming N is positive. I made a loop summing from 1 to N, but it is too slow.
| If N is positive: int sum = N*(N+1)/2;
If N is negative: int tempN = -N; int sum = 1 + tempN*(tempN+1)/2 * (-1);.
|
2,624,442 | 2,624,466 | Coordinating typedefs and structs in std::multiset (C++) | I'm not a professional programmer, so please don't hesitate to state the obvious.
My goal is to use a std::multiset container (typedef EventMultiSet) called currentEvents to organize a list of structs, of type Event, and to have members of class Host occasionally add new Event structs to currentEvents. The structs are supposed to be sorted by one of their members, time. I am not sure how much of what I am trying to do is legal; the g++ compiler reports (in "Host.h") "error: 'EventMultiSet' has not been declared." Here's what I'm doing:
// Event.h
struct Event {
public:
bool operator < ( const Event & rhs ) const {
return ( time < rhs.time );
}
double time;
int eventID;
int hostID;
};
// Host.h
...
void calcLifeHist( double, EventMultiSet * ); // produces compiler error
...
void addEvent( double, int, int, EventMultiSet * ); // produces compiler error
// Host.cpp
#include "Event.h"
...
// main.cpp
#include "Event.h"
...
typedef std::multiset< Event, std::less< Event > > EventMultiSet;
EventMultiSet currentEvents;
EventMultiSet * cePtr = ¤tEvents;
...
Major questions
Where should I include the EventMultiSet typedef?
Are my EventMultiSet pointers obviously problematic?
Is the compare function within my Event struct (in theory) okay?
Thank you very much in advance.
|
The compiler errors are simply because your typedef is in the wrong place - only main.cpp knows about it. It looks like you probably want it in Event.h, which both of the others include.
I'm not sure exactly what you're asking - but possibly you want to pass by reference not by pointer?
I don't see anything wrong with it - though you might want to provide the other comparisons (>, <=, ...) too.
|
2,624,556 | 2,624,660 | Why does the compiler allow a function to return a value that is stored as a reference | Can anybody explain why this code does not generate a compiler error?
class Foo
{
public:
int _x;
};
Foo getFoo()
{
Foo myfoo;
myfoo._x = 10;
return myfoo;
}
int _tmain()
{
// shouldn't this line of code be a compiler error?
Foo& badfoo = getFoo();
return 0;
}
| You are probably using VC++ which allows this as an extension.
main.cpp:18: warning C4239: nonstandard extension used :
'initializing' : conversion from 'Foo' to 'Foo &'
|
2,624,628 | 2,624,947 | In a class with no virtual methods or superclass, is it safe to assume (address of first member variable) == this? | I made a private API that assumes that the address of the first member-object in the class will be the same as the class's this-pointer... that way the member-object can trivially derive a pointer to the object that it is a member of, without having to store a pointer explicitly.
Given that I am willing to make sure that the container class won't inherit from any superclass, won't have any virtual methods, and that the member-object that does this trick will be the first member object declared, will that assumption hold valid for any C++ compiler, or do I need to use the offsetof() operator (or similar) to guarantee correctness?
To put it another way, the code below does what I expect under g++, but will it work everywhere?
class MyContainer
{
public:
MyContainer() {}
~MyContainer() {} // non-virtual dtor
private:
class MyContained
{
public:
MyContained() {}
~MyContained() {}
// Given that the only place Contained objects are declared is m_contained
// (below), will this work as expected on any C++ compiler?
MyContainer * GetPointerToMyContainer()
{
return reinterpret_cast<MyContainer *>(this);
}
};
MyContained m_contained; // MUST BE FIRST MEMBER ITEM DECLARED IN MyContainer
int m_foo; // other member items may be declared after m_contained
float m_bar;
};
| It seems the current standard guarantees this only for POD types.
9.2.17
A pointer to a POD-struct object,
suitably converted, points to its
initial member (or if that member is a
bit-field, then to the unit in which
it resides) and vice versa. [Note:
There might therefore be unnamed
padding within a POD-struct object,
but not at its beginning, as necessary
to achieve appropriate alignment. ]
However, the C++0x standard seems to extend this guarantee to "standard-layout struct object"
A standard-layout class is a class
that:
— has no non-static data members of
type non-standard-layout class (or
array of such types) or reference,
— has no virtual functions (10.3) and
no virtual base classes (10.1),
— has the same access control (Clause
11) for all non-static data members,
— has no non-standard-layout base
classes,
— either has no non-static data
members in the most-derived class and
at most one base class with non-static
data members, or has no base classes
with non-static data members, and
— has no base classes of the same type
as the first non-static data member.
A standard-layout struct is a
standard-layout class defined with the
class-key struct or the class-key
class.
It is probably likely that the assumption holds in practice (and the former didn't just have these distinctions, though this could have been the intention)?
|
2,624,667 | 2,624,672 | What's a very easy C++ profiler (VC++)? | I've used a few profilers in the past and never found them particularly easy. Maybe I picked bad ones, maybe I didn't really know what I was expecting!
But I'd like to know if there are any 'standard' profilers which simply drop in and work? I don't believe I need massively fine-detailed reports, just to pick up major black-spots. Ease of use is more important to me at this point.
It's VC++ 2008 we're using (I run standard edition personally). I don't suppose there are any tools in the IDE for this, I can't see any from looking at the main menus?
| VS built in:
If you have team edition you can use the Visual Studio profiler.
Other options:
Otherwise check this thread.
Creating your own easily:
I personally use an internally built one based on the Win32 API QueryPerformanceCounter.
You can make something nice and easy to use within a hundred lines of code or less.
The process is simple: create a macro at the top of each function that you want to profile called PROFILE_FUNC() and that will add to internally managed stats. Then have another macro called PROFILE_DUMP() which will dump the outputs to a text document.
PROFILE_FUNC() creates an object that will use RAII to log the amount of time until the object is destroyed. Both the constructor of this RAII object and the destructor will call QueryPerformanceCounter. You could also leave these lines in your code and control the behavior via a #define PROFILING_ON
|
2,624,693 | 2,624,739 | Why is this undefined behavior when I always get the same result? | I recently came across a question about sequence points in C++ at this site, about
what this code will output:
int c=0;
cout << c++ << c;
It was answered that the output is undefined and << is not a sequence point, but still I want to know why is it undefined when, even if I compile it 25 times, it still always prints 01?
| "Undefined" means that the standard doesn't specify what has to happen in that situation, so anything your compiler does is, by definition, right. If it always prints 01, that's fine. If it prints a different number every time you run, that would be fine too. If it causes monkeys to fly out of your nose (as illustrated here), that would be fine as well.
You might not think so, but the compiler writers are off the hook if it happens.
[Edit: It has been pointed out in the comments that the cannonical reference is "nasal demons", not "nasal monkeys". My apologies for any unintended confusion. Any intended confusion I'm proud of and do not apologize for. :-) ]
|
2,624,880 | 2,632,886 | Static Class Variables in Dynamic Library and Main Program | I am working on a project that has a class 'A' that contains a static stl container class. This class is included in both my main program and a .so file. The class uses the default(implicit, not declared) constructor/destructor. The main program loads the .so file using dlopen() and in its destructor, calls dlclose(). The program crashes after main exits when glibc calls the destructor for the static class member variable. The problem appears to be that when dlclose() is called, the destructor for the static variable is called, then when main exits() glibc also calls the destructor, resulting in a double free.
I have 2 questions, namely:
1) In this particular case, why are there not two copies of the static variable(yes i know that sounds somewhat ridiculous, but since both the main program and .so file have a separately compiled 'A', shouldn't they each have one?)
2) Is there any way to resolve this issue without re-writing class 'A' to not contain static member variables?
| This question has been resolved in another question I posted. Basically there were indeed two copies of the static variable -- one in the main program and one in the shared library, but the runtime linker was resolving both copies to the main programs copy. See this question for more information:
Main Program and Shared Library initializes same static variable in __static_initialization_and_destruction_0
|
2,625,304 | 2,626,249 | C++ using cdb_read returns extra characters on some reads | I am using the following function to loop through a couple of open CDB hash tables. Sometimes the value for a given key is returned along with an additional character (specifically a CTRL-P (a DLE character/0x16/0o020)).
I have checked the cdb key/value pairs with a couple of different utilities and none of them show any additional characters appended to the values.
I get the character if I use cdb_read() or cdb_getdata() (the commented out code below).
If I had to guess I would say I am doing something wrong with the buffer I create to get the result from the cdb functions.
Any advice or assistance is greatly appreciated.
char* HashReducer::getValueFromDb(const string &id, vector <struct cdb *> &myHashFiles)
{
unsigned char hex_value[BUFSIZ];
size_t hex_len;
//construct a real hex (not ascii-hex) value to use for database lookups
atoh(id,hex_value,&hex_len);
char *value = NULL;
vector <struct cdb *>::iterator my_iter = myHashFiles.begin();
vector <struct cdb *>::iterator my_end = myHashFiles.end();
try
{
//while there are more databases to search and we have not found a match
for(; my_iter != my_end && !value ; my_iter++)
{
//cerr << "\n looking for this MD5:" << id << " hex(" << hex_value << ") \n";
if (cdb_find(*my_iter, hex_value, hex_len)){
//cerr << "\n\nI found the key " << id << " and it is " << cdb_datalen(*my_iter) << " long\n\n";
value = (char *)malloc(cdb_datalen(*my_iter));
cdb_read(*my_iter,value,cdb_datalen(*my_iter),cdb_datapos(*my_iter));
//value = (char *)cdb_getdata(*my_iter);
//cerr << "\n\nThe value is:" << value << " len is:" << strlen(value)<< "\n\n";
};
}
}
catch (...){}
return value;
}
| First, I am not familiar with CDB and I don't believe you include enough details about your software environment here.
But assuming it is like other database libraries I've used...
The values probably don't have to be NUL-terminated. That means that casting to char* and printing it will not work. You should add a 0 byte yourself.
So malloc cdb_datalen + 1 and set the last character to 0. Then print it.
Better yet, use calloc and it will allocate memory already set to zero.
|
2,625,378 | 2,625,428 | gcc compilation without using system defined header locations | I am attempting to compile a c++ class using gcc. Due to the nature of the build, I need to invoke gcc from a non-standard location and include non-system defined headers, only to add a set from a different location. However, when I do this, I run into an issue where I cannot find some base symbols (suprise suprise). So i am basically running this command to compile my code:
-->(PARENT_DIR)/usr/bin/gcc # invoke compiler
-B$(PARENT_DIR)/usr/lib64/gcc/suselinux-x8664
-B$(PARENT_DIR)/usr/lib64
#C/C++ flags
-fPIC -fvisibility=default -g -c -Wall -m64 -nostdinc
# source files
-I$(SRC_DIR_ONE)/
-I$(SRC_DIR_TWO)
-I../include
# 'Mock' include the system header files
-I$(PARENT_DIR)/usr/include/c++/$(GCC_VERSION)
-I$(PARENT_DIR)/usr/include/c++/$(GCC_VERSION)/backward
-I$(PARENT_DIR)/usr/include/c++/$(GCC_VERSION)/x86_64-suse-linux
-I$(PARENT_DIR)/usr/lib64/x86_64-suse-linux/$(GCC_VERSION)/include
-I$(PARENT_DIR)/usr/lib64/gcc/x86_64-suse-linux/$(GCC_VERSION)/include
-I$(PARENT_DIR)/usr/lib64/gcc/x86_64-suse-linux/$(GCC_VERSION)/include-fixed
-I$(PARENT_DIR)/usr/src/linux/include
-I$(PARENT_DIR)/usr/x86_64-suse-linux/include
-I$(PARENT_DIR)/usr/include/suselinux-x8664
-I$(PARENT_DIR)/usr/suselinux-x8664/include
-I$(PARENT_DIR)/usr/include
-I$(PARENT_DIR)/usr/include/linux
file.cpp
I am getting several errors which indicate that the base headers are not being included: such as:
$(PARENT_DIR)/usr/include/c++/$(GCC_VERSION)/cstddef ::prtdiff_t has not been declared
$(PARENT_DIR)/usr/include/c++/$(GCC_VERSION)/cstddef ::size_t has not bee declared.
Is there something that I am doing wrong when I include the header file directories? Or am I looking in the wrong place?
| Perhaps the --sysroot arg would help, see gcc docs.
|
2,625,411 | 2,626,894 | How to build a sentence parser using only the c++ standared library? | I am designing a text based game similar to Zork, and I would like it to able to parse a sentance and draw out keywords such TAKE, DROP ect. The thing is, I would like to do this all through the standard c++ library... I have heard of external libraries (such as flex/bison) that effectively accomplish this; however I don't want to mess with those just yet.
What I am thinking of implementing is a token based system that has a list of words that the parser can recognize even if they are in a sentence such as "take sword and kill monster" and know that according to the parsers grammar rules, TAKE, SWORD, KILL and MONSTER are all recognized as tokens and would produce the output "Monster killed" or something to that effect. I have heard there is a function in the c++ standard library called strtok that does this, however I have also heard it's "unsafe". So if anyone here could lend a helping hand, I would greatly appreciate it.
| For a naive implementation using std::string, the std::set container and this tokenization function (Alavoor Vasudevan) you can do this :
#include <iostream>
#include <set>
#include <string>
int main()
{
/*You match the substring find in the while loop (tokenization) to
the ones contained in the dic(tionnary) set. If there's a match,
the substring is printed to the console.
*/
std::set<std::string> dic;
dic.insert("sword");
dic.insert("kill");
dic.insert("monster");
std::string str = "take sword and kill monster";
std::string delimiters = " ";
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
if(dic.find(str.substr(lastPos, pos - lastPos)) != dic.end())
std::cout << str.substr(lastPos, pos - lastPos)
<< " is part of the dic.\n";
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
return 0;
}
This will output :
sword is part of the dic.
kill is part of the dic.
monster is part of the dic.
Remarks :
The tokenization delimiter (white space) is very (too) simple for natural languages.
You could use some utilities in boost (split,tokenizer).
If your dictionnary (word list) was really big using the hash version of set could be useful (unordered_set).
With boost tokenizer, it could look like this (this may not be very efficient):
boost::tokenizer<> tok(str);
BOOST_FOREACH(const std::string& word,tok)
{
if(dic.find(word) != dic.end())
std::cout << word << " is part of the dic.\n";
}
|
2,625,418 | 2,626,362 | What is the reciprocal of CComboBox.GetItemData? | Instead of associating objects with Combo Box items, I associate long ids representing choices. They come from a database, so it seems natural to do so anyway. Now, I persist the id and not the index of the user's selection, so that the choice is remembered across sessions. If id no longer exists in database - no big deal. The choice will be messed up once. If db does not change, however, then it would be a great success ;)
Here is how I get the id :
chosenSomethingIndex = cmbSomething.GetCurSel();
lastSomethingId = cmbSomething.GetItemData(chosenSomethingIndex);
How do I reverse this? When I load the stored value for user's last choice, I need to convert that id into an index. I can do:
cmbSomething.SetCurSel(chosenSomethingIndex);
However, how can I attempt (it might not exist) to get an index once I have an id?
I am looking for a reciprocal function to GetItemData
I am using VS2008, probably latest version of MFC, whatever that is.
Thank you.
EDIT:
Ah, crap. Looks like I need to do this:
for (int i = 0; i < nCount; i++)
{
if (nId == GetItemData(i))
{
SetCurSel(i);
hr = S_OK;
break;
}
}
| You have a function that maps item index to database ID. There is no built-in inverse for that function because the general case doesn't have an inverse. A single data value might map to many different items in the list control; the OS doesn't know your data values are unique.
Your technique of searching the control items one by one is the only way to do it, unless you have additional information stored elsewhere. As you populate your combo box, you could build a reverse index in a std::map. When you add item i with database ID id, add an entry to your other data structure, too:
SetItemData(i, id);
reverse_index[id] = i;
Then, instead of searching one item at a time, you can just look in the index, replacing your loop with this:
std::map<DWORD_PTR, int>::iterator it = reverse_index.find(nId);
if (it != reverse_index.end()) {
assert(GetItemData(*it) == nId);
SetCurSel(*it);
hr = S_OK;
}
|
2,625,869 | 2,625,881 | Why is a pointer to pointer needed to allocate memory in this function? | I have a segmentation fault in the code below, but after I changed it to pointer to pointer, it is fine. What is the reason?
void memory(int * p, int size) {
try {
p = (int *) malloc(size*sizeof(int));
} catch(exception& e) {
cout << e.what() << endl;
}
}
It does not work in the main function as below:
int *p = 0;
memory(p, 10);
for(int i = 0; i < 10; i++)
p[i] = i;
However, it works like thi .
void memory(int ** p, int size) { `//pointer to pointer`
try {
*p = (int *) malloc(size*sizeof(int));
} catch(exception& e) {
cout<<e.what()<<endl;
}
}
int main()
{
int *p = 0;
memory(&p, 10); // Get the address of the pointer
for(int i = 0; i < 10; i++)
p[i] = i;
for(int i = 0; i < 10; i++)
cout << *(p+i) << " ";
return 0;
}
| Because you're wanting to get a pointer value back from the operations done in the function. malloc allocates memory and gives you an address for that memory.
In your first example, you store that address in the local argument variable p, but since it's just the argument, that doesn't make it back to the main program, because C/C++ are pass-by-value by default - even for pointers.
Main Function malloc
p p allocated
+---+ +---+
| 0 | | 0 | A
+---+ +---+
becomes...
p p allocated
+---+ +---+
| 0 | | ------------> A
+---+ +---+
and thus when main reads p, it gets 0, not A.
In your working code, you follow the pointer passed to an address, and that address gives you the location of the pointer variable in the main program. You update the pointer value at that address, which the main program can then look up the value of to use as its memory location - thus passing the address returned by malloc back to the main program for use.
Main Function malloc
p p allocated
+---+ +---+
| 0 |<------- | A
| | | |
+---+ +---+
becomes...
p p allocated
+---+ +---+
| |<------- |
| ----------------------> A
+---+ +---+
and thus when main reads p, it gets A.
|
2,626,027 | 2,626,119 | What color to use in owner-draw Windows List Control background? | I have an owner-drawn list control in my Windows program. I use CListCtrl::GetBkColor to get the background color, and for a selected item I use GetSysColor(COLOR_HIGHLIGHT). This matches what Windows uses for non owner drawn list controls, except for the case where the control doesn't have focus - then the background is replaced with gray.
Does Windows use one of the GetSysColor constants for the selected but unfocused background? If so, which one?
| COLOR_INACTIVECAPTION (3), I think.
Update: Nope, it looks like it's just COLOR_BTNFACE (15).
|
2,626,150 | 2,626,174 | set static member pointer variables | I'm trying to set a static pointer variable in a class but I'm getting these errors for each variable I try to set.
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2040: 'xscroll' : 'int' differs in levels of indirection from 'float *'
error C2440: 'initializing' : cannot convert from 'float **' to 'int'
Here is the code
Enemy.h
#include <windows.h>
#include "Player.h"
class Enemy
{
public:
Enemy(float xPos, float yPos);
Enemy(void);
~Enemy(void);
//update the position of the user controlled object.
void updatePosition(float timeFactor);
//loads all the enemy textures
void static loadTextures();
//creates a set number of enemies
void static createEnemies(int numEnemies, Enemy * enemyArray);
GLuint static enemyTex;
static float * xscroll;
static float * yscroll;
static Player * player;
private:
bool checkCollison(float x, float y, int radius);
float XPos;
float YPos;
};
trying to set variables
Enemy::xscroll = &xscroll;
Enemy::yscroll = &yscroll;
Enemy::player = &player;
| I think you're mixing up initialization with assignment. All class static variables have to be defined once, from global scope (i.e. the definition is outside any class or function, can be in a namespace however) and can be initialized at that time. This definition looks just like the definition of any global variable, type identifier = initializer; except that the identifier includes the scope operator ::.
|
2,626,230 | 2,632,271 | Running multiprocess applications from MATLAB | I've written a multitprocess application in VC++ and tried to execute it with command line arguments with the system command from MATLAB. It runs, but only on one core --- any suggestions?
Update:In fact, it doesn't even see the second core. I used OpenMP and used omp_get_max_threads() and omp_get_thread_num() to check and omp_get_max_threads() seems to be 1 when I execute the application from MATLAB but it's 2 (as is expected) if I run it from the command window.
Question:My task manager reports that CPU usage is close to 100% --- could this mean that the aforementioned API is malfunctioning it's still running as a multiprocess application?
Confirmation:
I used Process Explorer to check if there were any differences in the number of threads.
When I call the application from the command window, 1 thread goes to cmd.exe and 2 go to my application.
When I call it from MATLAB, 26 threads are for MATLAB.exe, 1 for cmd.exe and 1 for my application.
Any ideas?
| The question is how Matlab is affecting your app's behavior, since it's a separate process. I suspect Matlab is modifying environment variables in a manner that affects OMP, maybe because it uses OMP internally, and the process you are spawning from Matlab is inheriting this modified environment.
Do a "set > plain.txt" from the command window where you're launching you app plain, and "system('set > from_matlab.txt')" from within Matlab, and diff the outputs. This will show you the differences in environment variables that Matlab is introducing. When I do this, this appears in the environment inherited from Matlab, but not in the plain command window's environment.
OMP_NUM_THREADS=1
That looks like an OpenMP setting related to the function calls in your question. I'll bet your spawned app is seeing that and respecting it.
I don't know why Matlab is setting it. But as a workaround, when you launch the app from Matlab, instead of calling it directly, call a wrapper .bat file that clears the OMP_NUM_THREADS environment variable, or sets it to a higher number.
|
2,626,653 | 2,626,749 | Is there a safe / standard way to manage unstructured memory in C++? | I'm building a toy VM that requires a block of memory for storing and accessing data elements of different types and of different sizes. I've done this by writing a wrapper class around a uint8_t* data block of the needed size. That class has some template methods to write / read typed data elements to / from arbitrary locations in the memory block, both of which check to make certain the bounds aren't violated. These methods use memmove in what I hope is a more or less safe manner. That said, while I am willing to press on in this direction, I've got to believe that other with more expertise have been here before and might be willing to share their wisdom. In particular:
1) Is there a class in one of the C++ standards (past, present, future) that has been defined to perform a function similar to what I have outlined above?
2) If not, is there a (preferably free as in beer) library out there that does?
3) Short of that, besides bounds checking and the inevitable issue of writing one type to a memory location and reading a different from that location, are there other issues I should be aware of?
EDIT
Here's a simplification (i.e. destructor and some other related methods ommitted) of what I'm trying to do; but it captures the essense of it:
#include <stdint.h>
#include <assert.h>
#include <string.h>
#include <iostream>
class block
{
private:
uint8_t *data;
size_t size;
protected:
block(const void* src, size_t size)
: data(new uint8_t[size]), size(size) { ::memmove(data, src, size); }
void set(const void* src, size_t dst_adr, size_t len)
{
assert( (size > dst_adr) && (size > len) && ( (size - len) > dst_adr) );
::memmove(data+dst_adr, src, len);
}
void* get(size_t src_adr) const
{
assert( size > src_adr );
return data+src_adr;
}
public:
block(size_t size) : data(new uint8_t[size]), size(size) {}
size_t get_size() const { return this->size; }
virtual void copy(const block& src, size_t src_adr, size_t dst_adr, size_t len)
{
// Bounds check
assert( (size > dst_adr) && (size >= len) && ( (size - len) >= dst_adr) );
assert( (src.size > src_adr) && (src.size >= len) && ( (src.size - len) >= src_adr) );
::memmove(data+dst_adr, src.data+src_adr, len);
}
};
template <typename T>
class typed_block : public block
{
public:
typed_block(const T& val) : block(&val, sizeof(T)) {}
// Could use reinterpret_cast here instead, per Ben Voigt below
operator T () const { return *((T*) this->get(0)); }
typed_block<T>& operator=(const T& val)
{
this->set(*val, 0, get_size());
return *this;
}
};
int main(int argc, char** argv)
{
block db(512);
typed_block<long> x(1 << 30);
typed_block<short> y(0);
db.copy(x, 0, 15, x.get_size());
y.copy(db, 17, 0, y.get_size());
std::cout << "x = " << x << "\ty = " << y << std::endl;
return 0;
}
So, I guess what I'm really getting at, are there class libraries available (either in or out of any C++ standards) that provide essentially this functionality. I guess what makes me uncomfortable with this is passing "void *" parameters (even as protected members) in the block class, and I'm looking for a safer way to do this in general.
Thanks.-&&
| Hmm, since you are in C++, it sounds like you are looking for STL allocator and/or placement new.
|
2,626,748 | 2,638,838 | WinForm-style Invoke() in unmanaged C++ | I've been playing with a DataBus-type design for a hobby project, and I ran into an issue. Back-end components need to notify the UI that something has happened. My implementation of the bus delivers the messages synchronously with respect to the sender. In other words, when you call Send(), the method blocks until all the handlers have called. (This allows callers to use stack memory management for event objects.)
However, consider the case where an event handler updates the GUI in response to an event. If the handler is called, and the message sender lives on another thread, then the handler cannot update the GUI due to Win32's GUI elements having thread affinity. More dynamic platforms such as .NET allow you to handle this by calling a special Invoke() method to move the method call (and the arguments) to the UI thread. I'm guessing they use the .NET parking window or the like for these sorts of things.
A morbid curiosity was born: can we do this in C++, even if we limit the scope of the problem? Can we make it nicer than existing solutions? I know Qt does something similar with the moveToThread() function.
By nicer, I'll mention that I'm specifically trying to avoid code of the following form:
if(! this->IsUIThread())
{
Invoke(MainWindowPresenter::OnTracksAdded, e);
return;
}
being at the top of every UI method. This dance was common in WinForms when dealing with this issue. I think this sort of concern should be isolated from the domain-specific code and a wrapper object made to deal with it.
My implementation consists of:
DeferredFunction - functor that stores the target method in a FastDelegate, and deep copies the single event argument. This is the object that is sent across thread boundaries.
UIEventHandler - responsible for dispatching a single event from the bus. When the Execute() method is called, it checks the thread ID. If it does not match the UI thread ID (set at construction time), a DeferredFunction is allocated on the heap with the instance, method, and event argument. A pointer to it is sent to the UI thread via PostThreadMessage().
Finally, a hook function for the thread's message pump is used to call the DeferredFunction and de-allocate it. Alternatively, I can use a message loop filter, since my UI framework (WTL) supports them.
Ultimately, is this a good idea? The whole message hooking thing makes me leery. The intent is certainly noble, but are there are any pitfalls I should know about? Or is there an easier way to do this?
| I have been out of the Win32 game for a long time now, but the way we used to achieve this was by using PostMessage to post a windows message back to the UI thread and then handle the call from there, passing the additional info you need in wParam/lParam.
In fact I wouldn't be surprised if that is how .NET handles this in Control.Invoke.
Update: I was currios so I checked with reflector and this is what I found.
Control.Invoke calls MarshaledInvoke which does a bunch of checkes etc. but the interesting calls are to RegisterWindowMessage and PostMessage. So things have not changed that much :)
|
2,626,808 | 2,626,822 | Referencing a union inside a structure using union tag gives incorrect address | I had a need to declare a union inside a structure as defined below:
struct MyStruct
{
int m_DataType;
DWORD m_DataLen;
union theData
{
char m_Buff [_MAX_PATH];
struct MyData m_myData;
} m_Data;
};
Initially, I tried accessing the union data as follows (before I added the m_Data declaration):
MyStruct m_myStruct;
char* pBuff = m_myStruct.theData::m_Buff;
This compiles but returns to pBuff a pointer to the beginning of the MyStruct structure which caused me to overwrite the m_DataType & m_DataLength members when I thought I was writing to the m_Buff buffer.
I am using Visual Studio 2008. Can anyone explain this unexpected behavior? Thanks.
| You should be writing:
char *pBuff = m_myStruct.m_Data.m_Buff;
I wish I knew how it was compiling as written.
|
2,626,885 | 2,626,901 | understanding a Build c++ | I think I know what a build is. But I am not sure. My definition of a build is another word for saying compiled application. Can someone please tell me what exactly a build is. And why do people ask for 3 types of builds. Such as Debug Build, Profile Build and a Release Build. What are the differences.
[edit]
the types of builds
| Have a look at Visual Studio Debug and Release Modes
Release Mode
When an assembly is built in release mode, the compiler performs all available optimisations to ensure that the outputted executables and libraries execute as efficiently as possible. This mode should be used for completed and tested software that is to be released to end-users. The drawback of release mode is that whilst the generated code is usually faster and smaller, it is not accessible to debugging tools.
Debug Mode
Debug mode is used whilst developing software. When an assembly is compiled in debug mode, additional symbolic information is embedded and the code is not optimised. This means that the output of the compiler is generally larger, slower and less efficient. However, a debugger can be attached to the running program to allow the code to be stepped through whilst monitoring the values of internal variables.
|
2,626,903 | 2,626,921 | Creating a good directory structure | This might be a silly question but I am still learning. I have read several books on creating application and creating a good directory structure. When people talk about creating a directory structure, do they mean the folders you make within the solution explorer (folders you actually find inside of a .sln file) or do they mean setting up and creating folders that reside in the same folder as your .sln file or your compiled application (.exe). I figured the solution explorer folders are different from a typical windows folder cause the folders I create inside my .sln file are no where to be found on my windows system.
| Visual Studio has a strange way of dealing with "folders" in solutions. A "Solution Folder" is not actually a physical folder, but more of a virtual folder managed by Visual Studio. Your files may end up in the root directoy, but VS will treat them as if they are in a "folder." This is configured and managed in the VS .sln or project file.
I'm not a fan of how this works in Visual Studio, I don't get why they don't just put files in physical folders. It's up to you whether you want to fight VS and try to keep your files in physical folders, or if you want to just let VS manage it, but ultimately, it really doesn't matter.
|
2,627,013 | 2,627,211 | how to call a dll file in c. I want to transmit a xml file to it | I found many ways, but they are too easy, they always get a return-value from the dll file.
dll file: a file with the sufix ".dll"
| It's just like any other WINAPI
// assuming you are using windows
LPCTSTR lpszXml = _T("<xml> </xml>");
TCHAR szResult[1000] = _T("");
HMODULE hModule = LoadLibrary(_T("mylibrary.dll"));
int (*DoWorkFunc)(LPCTSTR lpszXmlData, LPTSTR lpszResult, int cchMaxSize);
*(FARPROC*)&DoWorkFunc = GetProcAddress(hModule, _T("DoWork"));
int nLength = DoWorkFunc(lpszXml, szResult, 1000);
_tprintf(_T("input [%s] output [%s] length of the result [%d]\n")
, lpszXml, szResult, nLength);
FreeLibrary(hModule);
// warning: no error handling is performed
Edit:
Since I speak multiple-languages, I can roughly guess what the OP asked. It is probably along this line:
I found many ways [in the internet] to load a DLL file and call a function inside it. But those that I found involve simple functions like int add(int a, int b). They only get a return value from the function. What I want to do is to pass a big chunk of data and get another big chunk of data from the function. How can I pass a big chunk of data and get a big chunk of data as the return value?
|
2,627,114 | 3,193,724 | C++ modularization framework (like OSGi) ? | I found one SOF http://www.codeproject.com/KB/library/SOF_.aspx ,
Are there anyother stable frameworks for modularization in C++ ?
| The OSGi4Cpp tries to implement the OSGi specification in C++.
|
2,627,134 | 2,627,156 | Passing enums to functions in C++ | I have a header file with all the enums listed (#ifndef #define #endif construct has been used to avoid multiple inclusion of the file) that I use in multiple cpp files in my application.One of the enums in the files is
enum StatusSubsystem {ENABLED,INCORRECT_FRAME,INVALID_DATA,DISABLED};
There are functions in the application delcared as
ShowStatus(const StatusSubsystem&);
Earlier in the application when I made calls to the above function like
ShowStatus(INCORRECT_FRAME);
my application used to compile perfectly. But after some code was added The compilation halts giving the following error:
File.cpp:71: error: invalid conversion from `int' to `StatusSubsystem'
File.cpp:71: error: initializing argument 1 of `void Class::ShowStatus(const StatusSubsystem&)
I checked the code for any conflicting enums in the new code and it looked fine.
My Question is what is wrong with the function call that compiler shows as erroneous?
For your reference the function definition is:
void Class::ShowStatus(const StatusSubsystem& eStatus)
{
QPalette palette;
mStatus=eStatus;//store current Communication status of system
if(eStatus==DISABLED)
{
//select red color for label, if it is to be shown disabled
palette.setColor(QPalette::Window,QColor(Qt::red));
mLabel->setText("SYSTEM");
}
else if(eStatus==ENABLED)
{
//select green color for label,if it is to be shown enabled
palette.setColor(QPalette::Window,QColor(Qt::green));
mLabel->setText("SYSTEM");
}
else if(eStatus==INCORRECT_FRAME)
{
//select yellow color for label,to show that it is sending incorrect frames
palette.setColor(QPalette::Window,QColor(Qt::yellow));
mLabel->setText("SYSTEM(I)");
}
//Set the color on the Label
mLabel->setPalette(palette);
}
A strange side effect of this situation is it compiles when I cast all the calls to ShowStatus() as
ShowStatus((StatusSubsystem)INCORRECT_FRAME);
Though this removes any compilation error, but a strange thing happens. Though I make call to INCORRECT_FRAME above but in function definition it matches with ENABLED. How on earth is that possible? Its like while passing INCORRECT_FRAME by reference, it magically converts to ENABLED, which should be impossible. This is driving me nuts.
Can you find any flaw in what I am doing? or is it something else?
The application is made using C++,Qt-4.2.1 on RHEL4.
Thanks.
| You should take the enum by value, rather than by const reference. It's small enough to fit into an int, so there is no performance penalty or anything like it.
But, from what you're describing, it sounds like somebody has #defined INCORRECT_FRAME to 0 elsewhere. You should put something like the following in the line above it:
#ifdef INCORRECT_FRAME
#error Whoops, INCORRECT_FRAME already defined!
#endif
BTW, the #ifndef thingy (for your header files) is called an include guard. :-)
|
2,627,166 | 2,627,179 | What is the difference between a const reference and normal parameter? | void DoWork(int n);
void DoWork(const int &n);
What's the difference?
| The difference is more prominent when you are passing a big struct/class:
struct MyData {
int a,b,c,d,e,f,g,h;
long array[1234];
};
void DoWork(MyData md);
void DoWork(const MyData& md);
When you use use 'normal' parameter, you pass the parameter by value and hence creating a copy of the parameter you pass. If you are using const reference, you pass it by reference and the original data is not copied.
In both cases, the original data cannot be modified from inside the function.
EDIT:
In certain cases, the original data might be able to get modified as pointed out by Charles Bailey in his answer.
|
2,627,192 | 2,627,207 | C++ vector<T>::iterator operator + | Im holding an iterator that points to an element of a vector, and I would like to compare it to the next element of the vector.
Here is what I have
Class Point{
public:
float x,y;
}
//Somewhere in my code I do this
vector<Point> points = line.getPoints();
foo (points.begin(),points.end());
where foo is:
void foo (Vector<Point>::iterator begin,Vector<Point>::iterator end)
{
std::Vector<Point>::iterator current = begin;
for(;current!=end-1;++current)
{
std::Vector<Point>::iterator next = current + 1;
//Compare between current and next.
}
}
I thought that this would work, but current + 1 is not giving me the next element of the vector.
I though operator+ was the way to go, but doesnt seem so. Is there a workaround on this?
THanks
| current + 1 is valid for random access iterators (which include vector iterators), and it is the iterator after current (i.e., what you think it does). Check (or post!) your comparison code, you're probably doing something wrong in there.
|
2,627,223 | 2,627,252 | C++ Template Class Constructor with Variable Arguments | Is it possible to create a template function that takes a variable number of arguments, for example, in this Vector< T, C > class constructor:
template < typename T, uint C >
Vector< T, C >::Vector( T, ... )
{
va_list arg_list;
va_start( arg_list, C );
for( uint i = 0; i < C; i++ ) {
m_data[ i ] = va_arg( arg_list, T );
}
va_end( arg_list );
}
This almost works, but if someone calls Vector< double, 3 >( 1, 1, 1 ), only the first argument has the correct value. I suspect that the first parameter is correct because it is cast to a double during the function call, and that the others are interpreted as ints and then the bits are stuffed into a double. Calling Vector< double, 3 >( 1.0, 1.0, 1.0 ) gives the desired results. Is there a preferred way to do something like this?
| This code looks dangerous and I think your analysis on why it isn't working is spot on, there's no way for the compiler to know that when calling:
Vector< double, 3 >( 1, 1, 1 )
the ones should be passed as doubles.
I would change the constructor to something like:
Vector< T, C >::Vector(const T(&data)[C])
instead, and have the user pass the arguments as an array. Another sort of ugly solution would be something like this:
template < typename T, uint C >
Vector< T, C >::Vector(const Vector<T, C - 1>& elements, T extra) {
}
and call it like this (with some typedefs):
Vector3(Vector2(Vector1(1), 1), 1);
|
2,627,351 | 2,627,484 | Can I use dll in Turbo C++ program and do we have any dll for lzw compression and decompression | I was trying to create a lzw compression program. But i need to finish it by today itself so i want to use some dll for taking my input as txt file and output to as a text file. I want to do this in TURBO C++ code which are doing my remaining functionalities.
Can anyone suggest me some method.
| Libzip isn't LZW (it uses an algorithm that's generally better), but it is probably the best standard answer. I don't know if there's a downloadable DLL for it in a standard location, so you might have to compile it from source.
Alternatively, a bit of Google-searching (on "lzw compression dll") found this C++ source code for doing LZW compression, which you may be able to use: http://zabkat.com/blog/24Jan10-lzw-compression-code.htm
|
2,627,416 | 2,627,430 | Are Multiple singleton instances possible in a shared DLL? | I am going to develop a DLL for an MFC Application, and suppose I have a singleton class in this DLL with some synchronization mechanism. And this DLL is used by other processes, namely EXEs. The question is: is this singleton created only once for all sharing processes or every process has its own singleton?
And How can I solve this multiple singleton problem?
| I suppose you are talking about Windows. In that case every process has its own singleton. You could place it in shared memory and use named synchronization primitives to share singleton between processes.
|
2,627,540 | 2,627,562 | Why is the destructor of the class called twice? | Apologies if the question sounds silly, I was following experts in SO and trying some examples myself, and this is one of them. I did try the search option but didn't find an answer for this kind.
class A
{
public:
A(){cout<<"A Contruction"<<endl;}
~A(){cout<<"A destruction"<<endl;}
};
int main()
{
vector<A> t;
t.push_back(A()); // After this line, when the scope of the object is lost.
}
Why is the destructor of the class called twice ?
| To add the element a copy constructor is invoked on a temporary object. After the push_back() the temporary object is destroyed - that't the first destructor call. Then vector instance goes out of scope and destroys all the elements stored - that's the second destructor call.
|
2,627,900 | 2,627,969 | What can explain std::cout not to display anything? | For whatever reason, std::cout does not display anything with my application. The description of my development environment follows.
I am working on a Qt application using Qt Creator. Since Qt Creator can't be launched from my station (XP64), i am currently developping it with Visual Studio 2008 and the Qt plugin (by importing the .pro project file). Everything seems fine and the application works.
In some cases (depending on command line arguments), i don't want to launch the HIM, just to display a few sentences in the CLI (command line required arguments, for instance).
I don't get any error, but nothing is displayed.
The corresponding code, which i am sure is run is the (classical) following :
std::cout << "is this going to be displayed ?" << std::endl;
Do you have any idea why nothing is displayed ?
| Ok, answer found. Simple answer, of course, as always when encountering such problems. Michael Aaron was on the right tracks.
Simply changing SubSystem to Console in project configuration (/Configuration properties/Linker/System) makes the whole thing work. The GUI still works, but with a background console. I can deal with that.
|
2,628,018 | 2,628,044 | Using an array in embedded x86 assembly? | I have a method (C++) that returns a character and takes an array of characters as its parameters.
I'm messing with assembly for the first time and just trying to return the first character of the array in the dl register. Here's what I have so far:
char returnFirstChar(char arrayOfLetters[])
{
char max;
__asm
{
push eax
push ebx
push ecx
push edx
mov dl, 0
mov eax, arrayOfLetters[0]
xor edx, edx
mov dl, al
mov max, dl
pop edx
pop ecx
pop ebx
pop eax
}
return max;
}
For some reason this method returns a ♀
Any idea whats going on? Thanks
| The line of assembly:
mov eax, arrayOfLetters[0]
is moving a pointer to the array of characters into eax (note, that's not what arrayOfLetters[0] would do in C, but assembly isn't C).
You'll need to add the following right after it to make your little bit of assembly work:
mov al, [eax]
|
2,628,135 | 2,628,160 | Polymorphic functions with parameters from a class hierarchy | Let's say I have the following class hierarchy in C++:
class Base;
class Derived1 : public Base;
class Derived2 : public Base;
class ParamType;
class DerivedParamType1 : public ParamType;
class DerivedParamType2 : public ParamType;
And I want a polymorphic function, func(ParamType), defined in Base to take a parameter of type DerivedParamType1 for Derived1 and a parameter of type DerivedParamType2 for Derived2.
How would this be done without pointers, if possible?
| You cannot have Base::func take different parameters depending on what class inherits it. You will need to change something.
You could make them both take a ParamType and handle an unexpected parameter with whatever mechanism you like (e.g. throw an exception or return an error code instead of void):
struct ParamType;
struct Base {
void func(ParamType&);
}
struct Derived1 : Base {};
//...
Or template on the type of parameter they should take:
struct ParamType;
struct DerivedParamType1 : ParamType {};
struct DerivedParamType2 : ParamType {};
template<class ParamT>
struct Base {
void func(ParamT&);
};
struct Derived1 : Base<DerivedParamType1> {};
struct Derived2 : Base<DerivedParamType2> {};
With the second solution, Derived1 and Derived2 won't share a common base and cannot be used polymorphically.
|
2,628,143 | 2,631,448 | facebook api over rest getting Incorrect signature <error_code> 104 | im trying to send rest api Users.getLoggedInUser
i have all the secret session and all the Authenticationi made
according to this site :
http://wiki.developers.facebook.com/index.php/Authorization_and_Authentication_for_Desktop_Applications
here is my code (cpp QT but it can be any thing else ) :
QString toAPISignature =
"api_key="
+ API_KEY
+ "call_id=" + strCallid
+ "format=XML"
+ "method=Users.getLoggedInUser"
+ "session_key="+ fbSessionKey
+ "v=1.0"+m_fbSecretKey;
QByteArray hashedApiData= QCryptographicHash::hash(toAPISignature.toAscii(),
QCryptographicHash::Md5);
QString APIMD5Signature(hashedApiData);
.....
.....
.....
// now set the api request
QUrl api_url;
api_url.setUrl(FB_REST_URL);
api_url.addQueryItem("api_key",API_KEY);
api_url.addQueryItem("session_key",fbSessionKey);
api_url.addQueryItem("call_id",strCallid);
api_url.addQueryItem("sig",APIMD5Signature);
api_url.addQueryItem("format","XML");
api_url.addQueryItem("method","Users.getLoggedInUser");
api_url.addQueryItem("v","1.0");
then i init the request object :
QNetworkRequest request;
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
request.setRawHeader("User-Agent", "Facebook API Client 0.1");
request.setUrl(url);
do the get request :
QEventLoop loop;
QNetworkReply *reply = networkManager->get(request);
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QByteArray data=reply->readAll();
and this is the xml im getting back:
look ..why the sig looks like this ?
does the hash MD5 suppose to look like set of numbers ?
<arg>
<key>sig</key>
<value>N{?¬???¬@?±B???????¶</value>
</arg>
<?xml version="1.0" encoding="UTF-8"?>
<error_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd">
<error_code>104</error_code>
<error_msg>Incorrect signature</error_msg>
<request_args list="true">
<arg>
<key>api_key</key>
<value>bc5xxxxxxxxx57811</value>
</arg>
<arg>
<key>session_key</key>
<value>a99fdxxxxxxx5c2-100xxxxx455</value>
</arg>
<arg>
<key>call_id</key>
<value>1</value>
</arg>
<arg>
<key>sig</key>
<value>N{?¬???¬@?±B???????¶</value>
</arg>
<arg>
<key>format</key>
<value>XML</value>
</arg>
<arg>
<key>method</key>
<value>Users.getLoggedInUser</value>
</arg>
<arg>
<key>v</key>
<value>1.0</value>
</arg>
</request_args>
</error_response>
| The big problem is that you need to convert the hashedApiData QByteArray to Hex:
QString APIMD5Signature(hashedApiData.toHex());
That may do it for you, but you can still cause problems converting back and forth to strings, which you really don't need to do.
Here's how I handle creating the sig and doing the post to facebook. The m_argMap contains the pairs for the POST (e.g. <"format","XML">) except for the secret which isn't needed for the POST but is needed for the sig. (I'm using a QVariant there due to some pre-processing that happens involving that QMap before it gets here).
QByteArray sigByteArray;
QByteArray postArgs;
// QMap is automatically sorted by keys
QMapIterator<QString, QVariant> i(m_argMap);
while (i.hasNext()) {
i.next();
sigByteArray.append(i.key() + "=" + i.value().toString() );
postArgs.append(i.key() + "=" + i.value().toString() + "&");
}
sigByteArray.append(m_userInfo->getSecret());
QByteArray sig = QCryptographicHash::hash(sigByteArray,QCryptographicHash::Md5 );
postArgs.append("sig=");
postArgs.append(sig.toHex());
QByteArray exclude("&=");
QByteArray include;
postArgs = postArgs.toPercentEncoding(exclude,include,'%');
// qDebug() << postArgs;
QUrl url("http://api.facebook.com/restserver.php");
QNetworkRequest nr;
nr.setUrl(url);
nr.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
m_reply = m_manager->post(nr,postArgs);
|
2,628,164 | 2,628,228 | Do console apps run faster than GUI apps? | I am relatively new to world of programming. I have a few performance questions:
Do console apps run faster than apps with a graphical user interface?
Are languages like C and Pascal faster than object oriented languages like C++ and Delphi? I know language speed depends more on compiler than on language itself, but do compilers for procedural languages produce faster code than OO ones (including C++ compilers that can produce C code)?
|
do console apps run faster than windows based app
Short answer: No
Long answer:
In a console based application, there is no GUI thread that needs to repaint the windows and accept user input, so in that sense, a console application may be slightly faster (since it has one fewer thread stealing away CPU cycles). However, since modern operating systems run multiple processes concurrently, anyway, a console application would still be contending for the CPU with other processes in the system, so no.
are languages like c and pascal faster than object oriented languages like c++ and delphi?
Short answer: No
Long answer:
Equivalent programs in C and C++ perform roughly the same. Although programming languages certainly can play a role in performance, generally the main thing you need to worry about is the algorithm (what you are expressing with your application's logic) and not the language the algorithm is coded up in.
|
2,628,180 | 2,628,250 | Dynamically allocated structure and casting | Let's say I have a first structure like this:
typedef struct {
int ivalue;
char cvalue;
}
Foo;
And a second one:
typedef struct {
int ivalue;
char cvalue;
unsigned char some_data_block[0xFF];
}
Bar;
Now let's say I do the following:
Foo *pfoo;
Bar *pbar;
pbar = new Bar;
pfoo = (Foo *)pbar;
delete pfoo;
Now, when I call the delete operator, how much memory does it free?
sizeof(int) + sizeof(char)
Or
sizeof(int) + sizeof(char) + sizeof(char) * 0xFF
?
And if it's the first case due to the casting, is there any way to prevent this memory leak from happening?
Note: please don't answer "use C++ polymorphism" or similar, I am using this method for a reason.
| The whole idea of such code is just undefined behavior. Don't do it. What happens if someone overloads operator new and operator delete for one struct and not for the other?
The only legal way to do what you want is to inherit both structs from the comon base with a virtual destructors - then you will have proper defined behavior and no problems with deallocation.
However if operator new and operator delete are not overloaded and both structs have trivial destructors it might just work allright on your implementation - the compiler will call ::operator delete() that has one parameter - the address of the block and it will free exactly the right amount of memory. However don't count on it - your code actually has undefined behavior.
|
2,628,345 | 2,628,443 | Will a call to std::vector::clear() set std::vector::capacity() to zero? | If I use .reserve(items) on a vector, the vector will allocate enough memory for my guess of the number of items that I'll need.
If I later on use .clear(), will that just clear the vector or save my earlier defined reserve?
thanks.
| It is specified that std::vector<T>::clear() affects the size. It might not affect the capacity. For resetting the capacity, use the swap trick:
std::vector<int> v1;
// somehow increase capacity
std::vector<int>().swap(v1);
Note: Since this old answer is still getting upvotes (thus people read it), I feel the need to add that C++11 has added std::vector<...>::shrink_to_fit(), which requests the vector to remove unused capacity.
|
2,628,459 | 2,628,484 | something about C++ unnamed namespace | #include <iostream>
namespace
{
int a=1;
}
int a=2,b=3;
int main(void)
{
std::cout<<::a<<::b;
return 0;
}
I complie it with my g++,but the output is 23,
who can explain it?
is that a way to get access to the <unnamed> namespace ::a?
| :: in ::a refers to the global namespace. Anonymous namespace should be accessed via just a (or to be more specific, you shouldn't do like this at all)
|
2,628,677 | 2,628,706 | What does: throw 0 do/mean? Is it "bad"? | Context
I came across some code, like this:
if( Some_Condition ) throw 0;
I googled a bit, and found a few other code snippets using that odd looking throw 0 form.
I presume one would catch this as:
catch(const int& e)
{ }
Or is this a NULL ptr? to be caught as void* ?
Question
What does this throw 0 do? Is it special in some way?
My normal preference would be to throw something that is (or derived from) std::exception. So to me this looks "bad".
Is it "bad" ?
| Generally throw can throw any type, any you need to catch it with this type or its base type.
So technically it is legal code but...
it is bad code: You should always derive your exceptions from std::exception or at least from some class that provides some useful information about error rather then plain number. But deriving from std::exception is the correct way because it allows to use topmost catch(std::exception const &e) and get at least some information about the error.
|
2,628,712 | 2,636,635 | Counting texels using a fragment shader | I have two textures generated using a fragment shader. I want to be able to count the number of texels in each texture that are above some colour intensity.
How can this be done?
My initial thought is to count these texels using the fragment shader before generating the texture. However, this would require some sort of global counter. I can't use occlusion queries because the textures are created from other textures. I'm using OpenGL 2.1.
| Thanks for the ideas,
I found a simple way I think is the most efficient. I initially thought occlusion queries could only be used with geometry but they can also be used with textures.
Turn on occlusion queries
Render the image using a fragment shader and discard texels below required
color intensity
Retrieve number of texels passing drawing test from query
|
2,628,714 | 2,628,794 | get const or non-const reference type from trait | I am writing a functor F which takes function of type void (*func)(T) and func's argument arg.
template<typename T>
void F(void (*func)(T), WhatTypeHere? arg)
{
func(arg);
}
Then functor F calls func with arg. I would like F not to copy arg, just to pass it as reference. But then I cannot simply write "void F(void (*func)(T), T&)" because T could be a reference. So I am trying to write a trait, which allows to get proper reference type of T:
T -> T&
T& -> T&
const T -> const T&
const T& -> const T&
I come up with something like this:
template<typename T>
struct type_op
{
typedef T& valid_ref_type;
};
template<typename T>
struct type_op<T&>
{
typedef typename type_op<T>::valid_ref_type valid_ref_type;
};
template<typename T>
struct type_op<const T>
{
typedef const T& valid_ref_type;
};
template<typename T>
struct type_op<const T&>
{
typedef const T& valid_ref_type;
};
template<typename T>
void F(void (*func)(T), typename type_op<T>::valid_ref_type arg)
{
func(arg);
}
Which doesn't work for example for
void a(int x) { std::cout << x << std::endl; }
F(&a, 7);
Giving error:
invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’ in passing argument 2 of ‘void F(void (*)(T), typename type_op::valid_ref_type) [with T = int]’
How to get this trait to work?
| template<class T>
struct forwarding { typedef T const& type; };
template<class T>
struct forwarding<T&> { typedef T& type; };
template<typename T>
void F(void (*func)(T), typename forwarding<T>::type arg) {
func(arg);
}
void a(int x) { std::cout << x << std::endl; }
int main() {
F(&a, 7);
}
Your mapping was close, you actually want T mapped to T const& too:
T -> T const&
T& -> T&
T const& -> T const&
Note that functions having a parameter type of T const have a signature of T! The const is an implementation detail:
void f(int const);
typedef void F(int); // typedef of function type
F* p = &f; // no error! f's signature doesn't include const
|
2,629,346 | 2,629,369 | C++ template and pointers | I have a problem with a template and pointers ( I think ). Below is the part of my code:
/* ItemCollection.h */
#ifndef ITEMCOLLECTION_H
#define ITEMCOLLECTION_H
#include <cstddef>
using namespace std;
template <class T> class ItemCollection
{
public:
// constructor
//destructor
void insertItem( const T );
private:
struct Item
{
T price;
Item* left;
Item* right;
};
Item* root;
Item* insert( T, Item* );
};
#endif
And the file with function defintion:
/* ItemCollectionTemp.h-member functions defintion */
#include <iostream>
#include <cstddef>
#include "ItemCollection.h"
template <class T>
Item* ItemCollection <T>::insert( T p, Item* ptr)
{
// function body
}
Here are the errors which are generated by this line of code:
Item* ItemCollection <T>::insert( T p, Item* ptr)
Errors:
error C2143: syntax error : missing ';' before '*'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2065: 'Type' : undeclared identifier
error C2065: 'Type' : undeclared identifier
error C2146: syntax error : missing ')' before identifier 'p'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2470: 'ItemCollection::insert' : looks like a function definition, but there is no parameter list; skipping apparent body
error C2072: 'ItemCollection::insert': initialization of a function
error C2059: syntax error : ')'
Any help is much appreciated.
| template <class T>
typename ItemCollection <T>::Item* ItemCollection<T>::insert( T p, Item* ptr)
{
// function body
}
|
2,629,674 | 2,629,735 | Are there any pitfalls when calling functions from a C library in a C++ program? | I'm using a library which has both a C interface and a C++ interface in my C++ program. The C++ one is a bit immature and I must stick with the C one. I was wondering, in more general terms, is there anything specific to keep in mind when mixing C-style binary object files with a C++ project?
| For C functions to be called from C++, they have to be declared as extern "C". Usually something like this is used in headers:
#if defined(__cplusplus)
extern "C" {
#endif
void f();
void g();
#if defined(__cplusplus)
}
#endif
|
2,630,024 | 2,630,397 | why BOOST_FOREACH cannot handle const boost::ptr_map? | void main()
{
typedef boost::ptr_map<int, char> MyMap;
//typedef std::map<int, char *> MyMap; // in contrast with std type it works
MyMap mymap;
mymap[1] = new char('a');
mymap[2] = new char('b');
mymap[3] = new char('c');
BOOST_FOREACH(MyMap::value_type value, mymap)
{
std::cout << value.first << " " << value.second << std::endl;
}
MyMap const & const_mymap = mymap;
BOOST_FOREACH(const MyMap::value_type value, const_mymap)
{
std::cout << value.first << " " << value.second << std::endl;
}
}
The following error message comes from GCC at the second BOOST_FOREACH
error: conversion from 'boost::ptr_container_detail::ref_pair<int, const char* const>' to non-scalar type 'boost::ptr_container_detail::ref_pair<int, char* const>' requested
I reckon that this is the weakness of the pointer container's ref_pair...
| Based on this answer, it looks like you're right. But there's a workaround. Change your second loop to this:
BOOST_FOREACH(MyMap::const_iterator::value_type value, const_mymap)
{
std::cout << value.first << " " << value.second << std::endl;
}
|
2,630,054 | 2,630,091 | Does C++ limit recursion depth? | In Python there is a maximum recursion depth. Seems it is because Python is interpreted rather than compiled. Does C++ have the same concept? Or it is connected only with RAM limit?
| The limit in C++ is due to the maximum size of the stack. That's typically less than the size of RAM by quite a few orders of magnitude, but is still pretty large. (Luckily, large things like string contents are typically held not on the stack itself.)
The stack limit is typically tunable at the OS level. (See the docs for the ulimit shell built-in if you're on Unix.) The default on this machine (OSX) is 8 MB.
[EDIT] Of course, the size of the stack doesn't entirely help by itself when it comes to working out how deep you can recurse. To know that, you have to compute the size of the activation record (or records) of the recursive function (also called a stack frame). The easiest way to do that (that I know of) is to use a disassembler (a feature of most debuggers) and to read out the size of the stack pointer adjustments at the start and end of every function. Which is messy. (You can work it out other ways – for example, computing the difference between pointers to variables in two calls – but they're even nastier, especially for portable code. Reading the values out of the disassembly is easier IMO.)
|
2,630,163 | 2,630,232 | How to restrict the range of elements of C++ STL vector? | vector<int> l;
for(int i=0;i<10;i++){
l.push_back(i);
}
I want the vector to only be able to store numbers from a specified range (or set).
How can that be done, in general?
In particular, I want to restrict the vector to beonly be able to store single digits.
So, if I do a l[9]++ (in this case l[9] is 9), it should give me an error or warn me. (because 10 is not a single digit number). Similarly, l[0]-- should warn me.
Is there a way to do this using C++ STL vector?
| An alternative solution would be to create your own datatype that provides this restrictions. As i read your question I think the restrictions do not really belong to the container itself but to the datatype you want to store. An example (start of) such an implementation can be as follows, possibly such a datatype is already provided in an existing library.
class Digit
{
private:
unsigned int d;
public:
Digit() : d(0) {}
Digit(unsigned int d)
{
if(d > 10) throw std::overflow_error();
else this->d=d;
}
Digit& operator++() { if(d<9) d++; return *this; }
...
};
|
2,630,258 | 2,630,733 | texture on cube-side with opengl | hello i want to use a texture on a cube (created by glutsolidcube()), how can i define where the texture is pictured at?
(for example on the "frontside" of a cube)
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filterMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filterMode);
glColor4f(0.8,0.7,0.11,1.0);
glPushMatrix();
glScalef(4, 1.2, 1.5);
glTranslatef( 0, 0.025, 0);
glutSolidCube(0.1);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
thanks
| Not possible, since glutSolidCube() only generates vertexes and normals, not texture coordinates.
However, there are workarounds.
|
2,630,406 | 2,630,684 | Will unused destructor be optimized out? | Assuming MyClass uses the default destructor (or no destructor), and this code:
MyClass *buffer = new MyClass[i];
// Construct N objects using placement new
for(size_t i = 0; i < N; i++){
buffer[i].~MyClass();
}
delete[] buffer;
Is there any optimizer that would be able to remove this loop?
Also, is there any way for my code to detect if MyClass is using an empty/default constructor?
EDIT: Sorry about my horrible code. I think this is correct now..
| There are a few things wrong with this code.
Firstly, you don't need to be calling the destructor. MyClass buffer* = new MyClass[i]; delete[] buffer; does that just fine. (Note, not the array syntax.)
That said, you comment leads me to believe you meant something else, like:
// vector, because raw memory allocation is bad
std::vector<char> memory(sizeof(MyClass) * count);
std::vector<MyClass*> objs; objs.reserve(count);
for (size_t i = 0; i < count; ++i)
objs.push_back(new (memory[sizeof(MyClass) * i]) MyClass()); // place it
Then later:
for (size_t i = 0; i < count; ++i)
objs[i].~MyClass(); // destruct (note syntax)
Of course there's no need to delete anything, since we used a vector. This is the correct syntax for calling a destructor.
Will it be optimized? It depends of the compiler can determine if the destructor does nothing. If the destructor is compiler-generated, I'm sure it'll remove the worthless loop. If the destructor is user-defined but in the header, it'll also be able to see it does nothing and remove the loop.
However, if it's in some other object file, I don't think it will, even if it's empty. That depends on your compilers ability to optimize during the linking phase. The best way to know is to look at the generated assembly.
|
2,630,529 | 2,630,830 | JNI how to access Java Object (Integer) | I have a JNI method to access java method which returns an Integer object. I do not want to return the primitive int type because this code will be modified to handle Generic objects. The following is what I have. I am not able to get the value of the Integer that I pass. The output at C++ side is something like
value = 0x4016f3d0
How can I get the actual value of Integer object that I pass at C++ end?
Please help.
Thanks,
-H
GenericPeer.cpp
JNIEXPORT void JNICALL Java_GenericPeer_print (JNIEnv *jenv, jclass jcls, jobject data){
jclass peerCls = jenv->GetObjectClass(data);
jmethodID mGetValue = jenv->GetMethodID(peerCls, "getValue","()Ljava/lang/Integer;");
if(mGetValue == NULL){
return (-1);
}
jobject value = jenv->CallObjectMethod(data, mGetValue);
cout<<"value = "<<value<<endl;
}
GenericPeer.java
public class GenericPeer {
public static native void print(Data d);
static {
System.load("/home/usr/workspace/GenericJni/src/libGenericJni.so");
}
}
Data.java
public class Data {
private Integer value;
pubilc Data(Integer v){
this.value = v;
}
public Integer getValue() { return value; }
public void setValue(Integer value) {
this.value = value;
}
}
Test.java (Main class)
public class Test {
public static void main(String[] args){
Integer i = new Integer(1);
Data d = new Data(i);
GenericPeer.print(d);
}
}
| You have to invoke the intValue method on the Integer instance to get its primitive value. Use FindClass instead of GetObjectClass (as in your code) to get a reference to the class java.lang.Integer and then GetMethodID and CallObjectMethod to actually invoke the intValue method.
|
2,630,695 | 2,630,918 | Dynamic linking in Visual Studio | I have to link dynamically with OpenSSL libeay32.dll.
I'm writing native c++ console application using Visual C++ Express 2008.
I'm including a header evp.h from OpenSSL distribution. Building and...:
error LNK2001: unresolved external symbol _EVP_aes_256_cbc
error LNK2001: unresolved external symbol _EVP_DecryptInit
error LNK2001: unresolved external symbol _EVP_CIPHER_CTX_init
How to make calls to libeay32.dll methods? I don't know where to specify it's filename
| In the project properties, configuration properties, linker, input - add the library name under "additional dependencies".
[Note, this will actually STATICALLY link with the library. If you truly want to load the library dynamically you will need to call LoadLibrary() on the DLL and then get function pointers for the functions you need using GetProcAddress().
See for example
http://msdn.microsoft.com/en-us/library/ms886736.aspx
and
http://msdn.microsoft.com/en-us/library/ms885634.aspx
|
2,630,806 | 2,630,873 | Maddening Linked List problem | This has been plaguing me for weeks. It's something really simple, I know it. Every time I print a singly linked list, it prints an address at the end of the list.
#include <iostream>
using namespace std;
struct node
{
int info;
node *link;
};
node *before(node *head);
node *after(node *head);
void middle(node *head, node *ptr);
void reversep(node *head, node *ptr);
node *head, *ptr, *newnode;
int main()
{
head = NULL;
ptr = NULL;
newnode = new node;
head = newnode;
for(int c1=1;c1<11;c1++)
{
newnode->info = c1;
ptr = newnode;
newnode = new node;
ptr->link = newnode;
ptr = ptr->link;
}
ptr->link=NULL;
head = before(head);
head = after(head);
middle(head, ptr);
//reversep(head, ptr);
ptr = head;
cout<<ptr->info<<endl;
while(ptr->link!=NULL)
{
ptr=ptr->link;
cout<<ptr->info<<endl;
}
system("Pause");
return 0;
}
node *before(node *head)
{
node *befnode;
befnode = new node;
cout<<"What should go before the list?"<<endl;
cin>>befnode->info;
befnode->link = head;
head = befnode;
return head;
}
node *after(node *head)
{
node *afnode, *ptr2;
afnode = new node;
ptr2 = head;
cout<<"What should go after the list?"<<endl;
cin>>afnode->info;
ptr2 = afnode;
afnode->link=NULL;
ptr2 = head;
return ptr2;
}
void middle(node *head, node *ptr)
{
int c1 = 0, c2 = 0;
node *temp, *midnode;
ptr = head;
while(ptr->link->link!=NULL)
{
ptr=ptr->link;
c1++;
}
c1/=2;
c1-=1;
ptr = head;
while(c2<c1)
{
ptr=ptr->link;
c2++;
}
midnode = new node;
cout<<"What should go in the middle of the list?"<<endl;
cin>>midnode->info;
cout<<endl;
temp=ptr->link;
ptr->link=midnode;
midnode->link=temp;
}
void reversep(node *head, node *ptr)
{
node *last, *ptr2;
ptr=head;
ptr2=head;
while(ptr->link!=NULL)
ptr = ptr->link;
last = ptr;
cout<<last->info;
while(ptr!=head)
{
while(ptr2->link!=ptr)
ptr2=ptr2->link;
ptr = ptr2;
cout<<ptr->info;
}
}
I'll admit that this is class work, but even the professor can't figure it out, and says that its probably something insignificant that we're overlooking, but I can't put my mind to rest until I find out what it is.
| There are two problems here:
In your initial loop which creates the list, you don't set the info of the last node. This is what causes the random-looking value to be displayed at the end. This is the relevant code:
for(int c1=1;c1<11;c1++)
{
newnode->info = c1;
ptr = newnode;
newnode = new node;
ptr->link = newnode;
ptr = ptr->link;
}
ptr->link=NULL;
As you can see, the last node to be created will never have its info set.
In the after function, you don't actually connect the new node. You need to find the last node in the list, and set its link to the new node.
|
2,631,006 | 2,631,508 | How do I render 3d model into directshow virtual camera output | I want to provide a virtual webcam via DirectShow that will use the video feed from an existing camera running some tracking software against it to find the users face and then overlay a 3d model oriented just that it appears to move the users face. I am using a third party api to do the face tracking and thats working great. I get position and rotation data from that api.
My question is whats the best way to render the 3d model and get into the video feed and out to direct show?
I am using c++ on windows xp.
| you can overlay your graphics by using a VMR filter -- a video renderer with multiple input pins. The VMR-9 filter is based on Direct3D, so you can use Direct3D rendering for your model and feed the output to a secondary pin on the VMR, to be overlaid or alpha-blended with the camera output which is fed to the primary pin of the VMR.
|
2,631,128 | 2,631,143 | C++ inherited class has member of same name | In C++ you can put a member in a base class and a member with the same name in the inherited class.
How can I access a specific one in the inherited class?
| In that case you should fully qualify a member name.
class A
{
public:
int x;
};
class B : public A
{
public:
int x;
B()
{
x = 0;
A::x = 1;
}
};
|
2,631,452 | 3,244,399 | 64bit exceptions in WndProc silently fail | The following code will give a hard fail when run under Windows 7 32bit:
void CTestView::OnDraw(CDC* /*pDC*/)
{
*(int*)0 = 0; // Crash
CTestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: add draw code for native data here
}
However, if I try this on Windows 7 64bit, I just get this in the output window:
First-chance exception at 0x13929384
in Test.exe: 0xC0000005: Access
violation writing location 0x00000000.
First-chance exception at 0x77c6ee42
in Test.exe: 0xC0150010: The
activation context being deactivated
is not active for the current thread
of execution.
What is the reason for this? I know it's a hardware exception (http://msdn.microsoft.com/en-us/library/aa363082.aspx), but why the difference when ran under 32bit and 64bit? And what can I do to correctly handle these kind of errors? Because they should really be trapped and fixed, as opposed to what currently happens which is Windows just carries on pumping messages to the application and let's it run (so the user and the developers are completely unaware any problems have actually occurred).
Update:
Our regular crash reporting software uses SetUnhandledExceptionFilter but that doesn't get called on x64 for hardware exceptions inside a WndProc. Does anyone have any information on this, or a workaround?
Update2:
I've reported the issue at Microsoft Connect:
https://connect.microsoft.com/VisualStudio/feedback/details/550944/hardware-exceptions-on-x64-machines-are-silently-caught-in-wndproc-messages
| OK, I've received a reply from Microsoft:
Hello,
Thanks for the report. I've found out
that this is a Windows issue, and
there is a hot fix available. Please
see
http://support.microsoft.com/kb/976038
for a fix that you can install if you
wish.
@Skute: note that the Program
Compatibility Assistant will ask once
if the program should be allowed to
continue to execute, and after that it
will always be allowed, so that may be
the cause of the confusing behavior
you are seeing.
Pat Brenner Visual C++ Libraries
Development
So the workaround is either make sure the hotfix is installed, or wrap each WndProc in your application with a __try / __except block.
|
2,631,489 | 2,640,156 | Qt moc failure without an error message | So I'm pretty new to Qt, and I've just inherited a project from someone else who is also new to Qt. He isn't around this week btw. We are using Visual Studio 2008, and have the latest version of Qt installed(4.6.2).
The project builds on my coworker's machine fine, and I can get the project from svn and build it directly. But under any other circumstances it refuses to build on my machine, and it doesn't give me much of an explanation why. Even if I just do a 'build clean' and then a 'build' it doesn't work. Any slight modification will make it fail.
When I try to build the entire project I get the error message:
1>Moc'ing MatrixTypeInterface.h...
1>moc: Cannot create
.\GeneratedFiles\Debug\moc_MatrixTypeInterface.cpp;.\GeneratedFiles\Debug\moc_matrixtypeinterface.cpp
1>Project : error PRJ0019: A tool
returned an error code from "Moc'ing
MatrixTypeInterface.h..."
The moc tool doesn't give any sort of error message as to why it isn't working, and I wasted most of yesterday trying to figure out why. I got the command that VS was using to call moc, and I entered in the command line myself. It didn't write anything to the screen.
Any ideas?
| I finally found the answer. my coworker was back in the office today, and I used the build log off his machine to get his full moc command(about 4 lines long). Our moc commands were basically the same except at the very end. His command ended in:
-o ".\GeneratedFiles\$(ConfigurationName)\moc_$(InputName).cpp"
My command ended with:
-o ".\GeneratedFiles\$(ConfigurationName)\moc_$(InputName).cpp;.\GeneratedFiles\Debug\moc_matrixtypeinterface.cpp"
I checked the custom build step for that file, and removed the excess bit. After that the file compiled fine. I don't know how or why qt decided to add in this extra tidbit, but it did.
Thanks for your help guys. A couple of you suspected that it was a filesystem issue, and indeed a semicolon is not allowed in a windows filename. But I feel the root cause was Qt creating the wrong build string.
I'm accepting my own answer in the hope that it will help someone else.
|
2,631,585 | 2,631,677 | C++: How to require that one template type is derived from the other | In a comparison operator:
template<class R1, class R2>
bool operator==(Manager<R1> m1, Manager<R2> m2) {
return m1.internal_field == m2.internal_field;
}
Is there any way I could enforce that R1 and R2 must have a supertype or subtype relation? That is, I'd like to allow either R1 to be derived from R2, or R2 to be derived from R1, but disallow the comparison if R1 and R2 are unrelated types.
| A trait you want might look like this:
template <typename B, typename D>
struct is_base_of // check if B is a base of D
{
typedef char yes[1];
typedef char no[2];
static yes& test(B*);
static no& test(...);
static D* get(void);
static const bool value = sizeof(test(get()) == sizeof(yes);
};
Then you just need a static assert of some sort:
// really basic
template <bool>
struct static_assert;
template <>
struct static_assert<true> {}; // only true is defined
#define STATIC_ASSERT(x) static_assert<(x)>()
Then put the two together:
template<class R1, class R2>
bool operator==(Manager<R1> m1, Manager<R2> m2)
{
STATIC_ASSERT(is_base_of<R1, R2>::value || is_base_of<R2, R1>::value);
return p1.internal_field == p2.internal_field;
}
If one does not derive from the other, the function will not compile. (Your error will be similar to "static_assert<false> not defined", and it will point to that line.)
|
2,631,837 | 2,631,915 | Compatibility between Qt and Boost sockets libraries | In my work, I'm developing a Viewer client for a Offshore simulation server, using sockets to send the simulation data from the Simulator to de Viewer.
But, the server uses Boost.asio as it's sockets library. As the client uses Qt for it's GUI, I was wondering if there is any problem in using de Qt Networking library for handling the sockets. Is there any compatibility issues?
Thanks in advance, and sorry for my bad english.
| There shouldn't be any "compatibility" problem. You only have to implement the communication protocol agreed with the server side correctly.
|
2,631,904 | 2,632,026 | How to create a bold and italic label in MFC? | Please do not mark it as a dupe of this question just yet:
Bold labels in MFC
That question does not help me; for some reason I do not see the rich edit control. Instead I believe I have to do it in code. here is a sample I found:
http://www.tech-archive.net/Archive/VC/microsoft.public.vc.mfc/2006-10/msg00245.html
My problem is that I prefer not to re-invent the wheel and test for errors myself or through QA.
Someone must have implemented this before. Please share your code.
What I would like to do is:
Keep the same font size, family, etc. as in the already created label, but make it bold and italic as well.
Keep the memory footprint reasonably low (do not create any new unnecessary objects), but do not get the app into an inconsistent state either.
I appreciate your help.
| You will want to do the following before the static text control is shown on the parent window.
Get a handle to the window: CWnd * pwnd = GetDlgItem(IDC_LABEL);
Get the current font for the static text: CFont * pfont = pwnd->GetFont();
Get the characteristics of the font: LOGFONT lf; pfont->GetLogFont(&lf);
Change the lfWeight and lfItalic fields in lf.
Put a CFont object in your parent window, so it will exist for the entire lifetime of the child window.
Initialize the CFont: m_font.CreateFontIndirect(&lf);
Set the font into the static text window: pwnd->SetFont(&m_font);
|
2,631,907 | 2,632,180 | GraphViz: which graph library to use? | I've just started developing a small C++ program using GraphViz's graph library and noticed there are actually three different API's: libgraph, libcgraph and libagraph. WTF?
I would like to know what is the difference between them, which one to use and where to look for API documentation. I have looked at the GraphViz documentation and mailing list archives but I've found many broken links, lots of wrong or misleading information and now I'm confused.
| Looks like one should use libcgraph, compiling with the flags given by pkg-config libcgraph --cflags --libs and including #include <cgraph.h>.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.