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 |
|---|---|---|---|---|
932,441 | 932,454 | Help with algorithm to dynamically update text display | First, some backstory:
I'm making what may amount to be a "roguelike" game so i can exersize some interesting ideas i've got floating around in my head. The gameplay isn't going to be a dungeon crawl, but in any case, the display is going to be done in a similar fasion, with simple ascii characters.
Being that this is... | I am not going to claim to understand this, but I believe this is close to the issue behind James Gosling's legendary Gosling Emacs redrawing code. See his paper, titled appropriately, "A Redisplay Algorithm", and also the general string-to-string correction problem.
|
932,519 | 932,528 | Opening a file on unix using c++ | I am trying to open a file in c++ and the server the progam in running on is based on tux.
string filename = "../dir/input.txt"; works but
string filename = "~jal/dir1/dir/input.txt"; fails
Is there any way to open a file in c++ when the filename provided is in the second format?
| The ~jal expansion is performed by the shell (bash/csh/whatever), not by the system itself, so your program is trying to look into the folder named ~jal/, not /home/jal/.
I'm not a C coder, but getpwent() may be what you need.
|
932,823 | 933,024 | How many CRITICAL_SECTIONs can I create? | Is there a limit to the number of critical sections I can initialize and use?
My app creates a number of (a couple of thousand) objects that need to be thread-safe. If I have a critical section within each, will that use up too many resources?
I thought that because I need to declare my own CRITICAL_SECTION object, I ... | If you read carefully the documentation for IntializeCriticalSectionWithSpinCount(), it is clear that each critical section is backed by an Event object, although the API for critical sections treats them as opaque structures. Additionally, the 'Windows 2000' comment on the dwSpinCount parameter states that the event ... |
932,824 | 1,362,976 | How do I get the system proxy using Qt? | I have the following code that I am trying to extract the systems proxy settings from:
QList<QNetworkProxy> listOfProxies = QNetworkProxyFactory::systemProxyForQuery();
foreach ( QNetworkProxy loopItem, listOfProxies ) {
qDebug() << "proxyUsed:" << loopItem.hostName();
}
I only get one item back and with a blank h... | By putting:
QNetworkProxyQuery npq(QUrl("http://www.google.com"));
QList<QNetworkProxy> listOfProxies = QNetworkProxyFactory::systemProxyForQuery(npq);
I appear get the proxy out.
|
933,003 | 933,015 | Using Pointer Returned from C Library in C++ | I am using a library developed in C (particularly: HTK). I've made a bit modifications to source and trying to get a pointer (to beginning of a linked list) from a function.
Not to go into too much detail; say I have a struct named OutType. In my C++ code I declare:
OutType* Out; and pass it to some function LName(....... | You are passing a copy of the pointer, which is why the change in the C library isn't seen in your C++ code.
Since you're already modifying the library, you should have that C function take a pointer to a pointer.
LName(....., OutType** Out)
*Out=SaveH(...);
Now you'll be passing the address of the C++ pointer, so yo... |
933,020 | 933,028 | Macro use depending on integer | I have to use a macro multiple times inside a function and the macro that needs to be used depends on a number I pass into the function.
e.g.
function(int number) {
switch(number) {
case 0: doStuff(MACRO0); break;
case 1: doStuff(MACRO1); break;
}
}
The problem is: I have a lot stuff to... | I would use a function object
struct Method1 {
void operator()() { ... }
};
template<typename Method>
void function(Method m) {
...
m();
...
}
int main() {
function(Method1());
}
|
933,122 | 933,167 | Socket Timeout in C++ Linux | Ok first of all I like to mention what im doing is completely ethical and yes I am port scanning.
The program runs fine when the port is open but when I get to a closed socket the program halts for a very long time because there is no time-out clause. Below is the following code
int main(){
int err, net;
stru... | The easiest is to setup an alarm and have connect be interrupted with a signal (see UNP 14.2):
signal( SIGALRM, connect_alarm ); /* connect_alarm is you signal handler */
alarm( secs ); /* secs is your timeout in seconds */
if ( connect( fs, addr, addrlen ) < 0 )
{
if ( errno == EINTR ) /* timeout */
...
}... |
933,143 | 933,151 | boost::regex segfaults when using capture | I get a seg fault for the simple program below. It seems to be related to the destructor match_results.
#include <iostream>
#include <vector>
#include <string>
#include <boost/regex.hpp>
using namespace std;
int main(int argc, char *argv)
{
boost::regex re;
boost::cmatch matches;
boost::regex_match("abc"... | boost::regex is one of the few components of boost that doesn't exist solely in header files...there is a library module.
It is likely that the library you are using was built with different settings than your application.
Edit: Found an example scenario with this known boost bug, where boost must be built with the sam... |
933,203 | 933,210 | What is the equivalent (if any) to the C++/Windows SendMessage() on the Mac? | Is there an equivalent function to SendMessage in the Mac OS?
| Ironically, every method call in Objective-C is the equivalent of SendMessage. Objective-C is at heart a message passing system.
So you just say:
[window myMessage]
and the myMessage routine will be executed by passing myMessage to the Window object and having it process that method...
It's also possible the closer t... |
933,460 | 944,103 | Unique hardware ID in Mac OS X | Mac OS X development is a fairly new animal for me, and I'm in the process of porting over some software. For software licensing and registration I need to be able to generate some kind of hardware ID. It doesn't have to be anything fancy; Ethernet MAC address, hard drive serial, CPU serial, something like that.
I've g... | Try this Terminal command:
ioreg -rd1 -c IOPlatformExpertDevice | awk '/IOPlatformUUID/ { split($0, line, "\""); printf("%s\n", line[4]); }'
From here
Here is that command wrapped in Cocoa (which could probably be made a bit cleaner):
NSArray * args = [NSArray arrayWithObjects:@"-rd1", @"-c", @"IOPlatformExpertDevice"... |
933,581 | 933,595 | fastest way to check if memory is zeroed | i got a program that needs to check if a chunk of a file is zeroed or has data. This alg runs for the whole file for sizes upto a couple of gigs and takes a while to run. Is there a better way to check to see if its zeroed?
Platform: Linux and windows
bool WGTController::isBlockCompleted(wgBlock* block)
{
if (!bloc... | How long is 'a while'? ... I'd say attempting to compare as many values in parallel as possible will help, maybe use some SIMD instructions to compare more than 4 bytes at a time?
Do keep in mind though, that no matter how fast you make the comparison, ultimately the data still needs to be read from the file. If the fi... |
933,584 | 933,621 | how to invalidate parent window without sending wm_paint to child window? | the parent and the child window is in the same size.
and the the parent listens to the child's repainting
when child repainting, the parent repainting.
so I cannot use invalidate to clean the parent window,
cos this will send wm_paint to child window, then a endless cycle.
how can i clean up parent widnow without use i... | You could set the WS_CLIPCHILDREN style on your window, or try calling the RedrawWindow function specifying RDW_NOCHILDREN as the final parameter. This may do what you want, although it's somewhat difficult to tell.
|
933,680 | 933,927 | Recursive type casting | I got a typical 'vector4' class with an operator float* to autocast it for gl*4fv as well as [].
There's also 'const' version for optimizations for the compiler as well as const refrences, and this works fine:
typedef struct vec4
{
...
// ----------------------------------------------------------------- //
... | ... One of those rules is that no sequence of conversions is allowed to contain more than one user-defined conversion (i.e., a call to a single arguement constructor or an implicit type conversion operator). - More Effective C++, Scott Meyers
You might want to overload operator[] for vec4 and mat4.
struct vec4
{
f... |
933,821 | 934,746 | Simulating movement of a window and have it react to collisions | I was reading this topic and I decided to give it a shot. To my astonishment it really seemed easier than what I am making it I guess. I have some confusion about the "DesiredPos" variable. Well at least in my implementation. I am trying to move a window around constantly and have it react like a ball when it hits the ... | My advice is to take a look on the "verlet integration". It is a quite easy way to simulate basic mechanics. Google for it and you'll find many examples for it, including collision detection and friction. On the long run this will give you more natrual results then estimating the velocity or the new position with a sin... |
933,844 | 935,706 | How can I use a C++ class from Perl? | I have a set of classes written in C++. What would be best way to call them from a Perl script? Thanks.
| I'm not particularly fond of SWIG and prefer to write the interfacing code myself. Perl comes with a sort of pseudo language called 'XS' for interfacing to C or C++. Unfortunately, in order to use it, you will need to know at least C, Perl, and then learn something about the interpreter API, too. If you already know Pe... |
933,850 | 933,996 | How do I find the location of the executable in C? | Is there a way in C/C++ to find the location (full path) of the current executed program?
(The problem with argv[0] is that it does not give the full path.)
| To summarize:
On Unixes with /proc really straight and realiable way is to:
readlink("/proc/self/exe", buf, bufsize) (Linux)
readlink("/proc/curproc/file", buf, bufsize) (FreeBSD)
readlink("/proc/self/path/a.out", buf, bufsize) (Solaris)
On Unixes without /proc (i.e. if above fails):
If argv[0] starts with "/" (abs... |
933,886 | 933,902 | std::sort without functors | I have a question regarding the std::sort algorithm. Here is my test code:
struct MyTest
{
int m_first;
int m_second;
MyTest(int first = 0, int second = 0) : m_first(first), m_second(second)
{
}
};
int main(int argc,char *argv[])
{
std::vector<MyTest> myVec;
for(int i = 0; i < 10; ++i)
... | Yes, so long as the value type in the range to be sorted has an operator < that defines a "strict weak ordering", that is to say, it can be used to compare two MyTest instances correctly. You might do something like:
class MyTest
{
...
bool operator <(const MyTest &rhs) const
{
return m_first<rhs.m_first;
}... |
934,358 | 934,384 | What type to use for integers larger than 2^32 in C++? | I have an integer variable, that can get a value larger than 4294967295.
What type should I use for it (long long, or double, or something else)?
| There is no portable way of doing this in C++, as the language does not specify the size of integer types (except sizeof char is 1). You need to consult your compiler documentation.
|
934,412 | 934,426 | How to get into image manipulation programming? | How can I do simple thing like manipulate image programmatically ? ( with C++ I guess .. )
jpgs/png/gif .....
| check out BOOST , it has a simple Image Processing Library called GIL. It also has extensions to import common formats.
http://www.boost.org/doc/libs/1_39_0/libs/gil/doc/index.html
|
934,529 | 934,537 | C++ inline functions using GCC - why the CALL? | I have been testing inline function calls in C++.
Thread model: win32
gcc version 4.3.3 (4.3.3-tdm-1 mingw32)
Stroustrup in The C++ Programming language wirtes:
The inline specifier is a hint to the compiler that it should attempt to generate code [...] inline rather than laying down the code for the function once an... | There is no generic C++ way to FORCE the compiler to create inline functions. Note the word 'hint' in the text you quoted - the compiler is not obliged to listen to you.
If you really, absolutely have to make something be in-line, you'll need a compiler specific keyword, OR you'll need to use macros instead of function... |
935,144 | 935,158 | Can Bison parse UTF-8 characters? | I'm trying to make a Bison parser to handle UTF-8 characters. I don't want the parser to actually interpret the Unicode character values, but I want it to parse the UTF-8 string as a sequence of bytes.
Right now, Bison generates the following code which is problematic:
if (yychar <= YYEOF)
{
yychar = yytok... | bison yes, flex no. The one time I needed a bison parser to work with UTF-8 encoded files I ended up writing my own yylex function.
edit: To help, I used a lot of the Unicode operations available in glib (there's a gunicode type and some file/string manipulation functions that I found useful).
|
935,231 | 935,241 | how to get filenames from folder in C++ | suppose I want to write ls or dir. how do I get the list of files in a given directory?
something equivalent of .NET's Directory.GetFiles, and additional information.
not sure about the string syntax, but:
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
| Look at the FindFirstFile and FindNextFile APIs
http://msdn.microsoft.com/en-us/library/aa364418.aspx
|
935,290 | 935,845 | $stdin compatibility with std::istream using swig, C++, and Ruby | I have a function in C++ that takes in an std::istream as the input:
class Foo {
Foo(std::istream &);
}
Using SWIG, I've bound it to Ruby, but Ruby's $stdin variable is fundamentally different from anything like the stream classes in C++, so I'm not sure how to either 1) expose the C++ class to Ruby in a way that ... | You can use an instance of std::istream that implements its operations with Ruby methods on $stdin called through the C interface (e.g., using rb_funcall). You can't do it by deriving a class from std::istream itself, because its methods are not virtual; instead you'll need to derive from std::stream_buf and instantiat... |
935,379 | 936,148 | JNI Calls different in C vs C++? | So i have the following code in C that utilizes Java Native Interface however i would like to convert this to C++ but am not sure how.
#include <jni.h>
#include <stdio.h>
#include "InstanceMethodCall.h"
JNIEXPORT void JNICALL
Java_InstanceMethodCall_nativeMethod(JNIEnv *env, jobject obj)
{
jclass cls = (*e... | I used to have the book Essential JNI. And while it is kinda dated, much of it still works today.
If I recall correctly, in C, Java constructs are simply pointers. Thus, in your code, "(*env)->" is dereferencing pointers to give you access to the underlying methods.
For C++, "env" is actually an object - a different en... |
935,664 | 935,713 | Possible to call C++ code from C#? | Is it possible to call C++ code, possibly compiled as a code library file (.dll), from within a .NET language such as C#?
Specifically, C++ code such as the RakNet networking library.
| One easy way to call into C++ is to create a wrapper assembly in C++/CLI. In C++/CLI you can call into unmanaged code as if you were writing native code, but you can call into C++/CLI code from C# as if it were written in C#. The language was basically designed with interop into existing libraries as its "killer app"... |
936,468 | 936,493 | Why does MSVC++ consider "std::strcat" to be "unsafe"? (C++) | When I try to do things like this:
char* prefix = "Sector_Data\\sector";
char* s_num = "0";
std::strcat(prefix, s_num);
std::strcat(prefix, "\\");
and so on and so forth, I get a warning
warning C4996: 'strcat': This function or variable may be unsafe. Consider using strcat_s instead.
Why is strcat considered unsafe,... | Because the buffer, prefix, could have less space than you are copying into it, causing a buffer overrun.
Therefore, a hacker could pass in a specially crafted string which overwrites the return address or other critical memory and start executing code in the context of your program.
strcat_s solves this by forcing you... |
936,678 | 936,694 | What is the simplest way to convert a const char[] to a string in c++ | Is there a simple way of creating a std::string out of an const char[] ?
I mean something simpler then:
std::stringstream stream;
stream << const_char;
std::string string = stream.str();
| std::string has multiple constructors, one of which is string( const char* str );.
You can use it like this:
std::string myString(const_char);
You could also use assignment, if you need to set the value at some time later than when the variable is declared:
myString = const_char;
|
936,687 | 936,702 | How do I declare a 2d array in C++ using new? | How do i declare a 2d array using new?
Like, for a "normal" array I would:
int* ary = new int[Size]
but
int** ary = new int[sizeY][sizeX]
a) doesn't work/compile and b) doesn't accomplish what:
int ary[sizeY][sizeX]
does.
| If your row length is a compile time constant, C++11 allows
auto arr2d = new int [nrows][CONSTANT];
See this answer. Compilers like gcc that allow variable-length arrays as an extension to C++ can use new as shown here to get fully runtime-variable array dimension functionality like C99 allows, but portable ISO C++ i... |
936,744 | 936,762 | Are dollar-signs allowed in identifiers in C++03? | What does the C++ standard say about using dollar signs in identifiers, such as Hello$World? Are they legal?
| A c++ identifier can be composed of any of the following: _ (underscore), the digits 0-9, the letters a-z (both upper and lower case) and cannot start with a number.
There are a number of exceptions as C99 allows extensions to the standard (e.g. visual studio).
|
936,799 | 936,899 | Determining what object files have caused .dll size increase [C++] | I'm working on a large c++ built library that has grown by a significant amount recently. Due to it's size, it is not obvious what has caused this size increase.
Do you have any suggestions of tools (msvc or gcc) that could help determine where the growth has come from.
edit
Things i've tried: Dumpbin the final dll, t... | If gcc, objdump. If visual studio, dumpbin.
I'd suggest doing a diff of the output of the tool for the old (small) library, vs. the new (large) library.
|
936,928 | 936,939 | how to return multiple error codes from C++ function | What is a good way to return success or one or more error codes from a C++ function?
I have this member function called save(), which saves to each of the member variables, there are at least ten of these member variables that are saved-to, for the call to save(), I want to find out if the call failed, and if so, on wh... | You can either return an object that has multiple error fields or you can use 'out'parameters.
How you do this depends on your design and what exactly you are trying to return back. A common scenario is when you need to report back a status code along with a message of sorts. This is sometimes done where the function... |
936,997 | 937,432 | WTL CListViewCtrl with status text | I have a Windows Template Library CListViewCtrl in report mode (so there is a header with 2 columns) with owner data set. This control displays search results. If no results are returned I want to display a message in the listbox area that indicates that there were no results. Is there an easy way to do this? Do yo... | I ended up subclassing the control and handling OnPaint like this:
class MsgListViewCtrl : public CWindowImpl< MsgListViewCtrl, WTL::CListViewCtrl >
{
std::wstring m_message;
public:
MsgListViewCtrl(void) {}
BEGIN_MSG_MAP(MsgListViewCtrl)
MSG_WM_PAINT( OnPaint )
END_MSG_MAP()
void Attach( ... |
936,999 | 937,002 | What is the default constructor for C++ pointer? | I have code like this:
class MapIndex
{
private:
typedef std::map<std::string, MapIndex*> Container;
Container mapM;
public:
void add(std::list<std::string>& values)
{
if (values.empty()) // sanity check
return;
std::string s(*(values.begin()));
values.erase(values.... | It'll create a NULL (0) pointer, which is an invalid pointer anyway :)
|
937,044 | 937,379 | Determine path to registry key from HKEY handle in C++ | Given a handle to a Windows Registry Key, such as the ones that are set by ::RegOpenKeyEx(), is it possible to determine the full path to that key?
I realize that in a simple application all you have to do is look up 5 or 10 lines and read... but in a complex app like the one I'm debugging, the key I'm interested in ca... | Use LoadLibrary and NtQueryKey exported function as in the following code snippet.
#include <windows.h>
#include <string>
typedef LONG NTSTATUS;
#ifndef STATUS_SUCCESS
#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
#endif
#ifndef STATUS_BUFFER_TOO_SMALL
#define STATUS_BUFFER_TOO_SMALL ((NTSTATUS)0xC0000023L)
#endif
... |
937,107 | 937,185 | Do template specializations require template<> syntax? | I have a visitor class resembling this:
struct Visitor
{
template <typename T>
void operator()(T t)
{
...
}
void operator()(bool b)
{
...
}
};
Clearly, operator()(bool b) is intended to be a specialization of the preceding template function.
However, it doesn't have the te... | Your code is not a template specialization, but rather a non-templated function. There are some differences there. The non-templated operator() will take precedence over a templated version (for an exact match, but type conversions will not take place there) but you can still force the templated function to be called:
... |
937,268 | 937,275 | How to take a typename as a parameter in a function? (C++) | I need to be able to pass a typename as a parameter:
int X = FileRead(file, 9, char);
The concept is for FileRead(std::fstream, int pos, ???) to read pos*sizeof(whatever the type is) to get the desired position. I tried templates:
template<typename T>
T FileRead(std::fstream file, int pos, T type)
{
T data;
f... | To use the name of a type as a parameter, use a template.
template<typename T>
T FileRead(std::fstream &file, int pos)
{
T data;
file.read(reinterpret_cast<char*>(&data), sizeof(T));
return data;
}
This assumes that the type is default constructible. If it is not, I guess you would have difficulty streamin... |
937,378 | 937,392 | access a variable by reference from a class in c++ | I have a class in c++ a portion of which is below
class Node{
public:
vector<string> getNames() const;
private:
vector<string> names_;
};
vector<string> Node::getNames(){
return names_;
}
the function getNames() passes a copy of the vector. How can i modify my class so that i can reference t... | Try this:
class Node
{
public:
const vector<string>& getNames() const;
private:
vector<string> names_;
};
const vector<string>& Node::getNames() const
{
return names_;
}
Few things:
getNames() is now a const method, because the Node does not logically change.
Return as a constant referenc... |
937,486 | 937,542 | Why can't you define new types in a C++ template argument? | I'm creating a library to allow OCaml/Haskell-like algebraic data types and pattern matching. The algebraic data types are implemented using a class similar to Boost.Variant. I would like to be able to define new types (the constructor) in the template arguments, but I get an error. I'm using my own type with variadic ... | I guess it's because template arguments are treated similar to function arguments and you can not declare
void func( class A{} a, class B{} b );
either. I also think it would be impossible to obey the ODR if you need the classes in more than one template (typedef).
|
937,621 | 937,632 | Why does std queue not define a swap method specialisation | I've read that all stl containers provide a specialisation of the swap algorithm so as to avoid calling the copy constructor and two assignment operations that the default method uses. However, when I thought it would be nice to use a queue in some code I was working on I noticed that (unlike vector and deque) queue do... | C++0x will add swap to container adapters like std::queue. I could only speculate why it is missing from the current standard.
In this discussion someone proposes a workaround:
There is a solution since the standard makes the needed parts protected,
called inheritance. [just don't destruct via the std adaptors]
... |
937,744 | 937,762 | Function template specialization format | What is the reason for the second brackets <> in the following function template:
template<> void doh::operator()<>(int i)
This came up in SO question where it was suggested that there are brackets missing after operator(), however I could not find the explanation.
I understand the meaning if it was a type specializat... | I've looked it up, and found that it is specified by 14.5.2/2:
A local class shall not have member templates. Access control rules (clause 11) apply to member template names. A destructor shall not be a member template. A normal (non-template) member function with a given name and type and a member function template o... |
937,773 | 937,800 | How do you determine the size of an object in C++? | For example, say I have a class Temp:
class Temp
{
public:
int function1(int foo) { return 1; }
void function2(int bar) { foobar = bar; }
private:
int foobar;
};
When I create an object of class Temp, how would I calculate how much space it needs, and how is it represented in memory (e... | To a first order approximation, the size of an object is the sum of the sizes of its constituent data members. You can be sure it will never be smaller than this.
More precisely, the compiler is entitled to insert padding space between data members to ensure that each data member meets the alignment requirements of th... |
937,805 | 942,750 | How to redefine clog to tee to original clog and a log file? | I saw a useful start here:
http://www.cs.technion.ac.il/~imaman/programs/teestream.html
And it works great to make a new stream which goes to both clog and a log file.
However, if I try to redefine clog to be the new stream it does not work because the new stream has the same rdbuf() as clog so the following has no eff... | If you really want to keep using std::clog for the tee instead of sending output to a different stream, you need to work one level lower: Instead of deriving from ostream, derive from streambuf. Then you can do this:
fstream logFile(...);
TeeBuf tbuf(logFile.rdbuf(), clog.rdbuf());
clog.rdbuf(&tbuf);
For more informat... |
937,884 | 982,670 | How do I import modules in boost::python embedded python code? | I'm using boost::python to embed some python code into an app. I was able to get print statements or other expressions to be evaluated properly, but when I try to import modules, it is not importing and application is exiting. Further the globals() function call in the embedded code gives a runtime error too.
#include ... | That didn't help, but I found a different solution to my problem. My current code looks like this:
#include <boost/python.hpp>
#include <iostream>
using namespace std;
using namespace boost;
using namespace boost::python;
using namespace boost::python::api;
int main(void) {
Py_Initialize();
boost::pyt... |
938,230 | 938,261 | Matching order in PCRE | How can I set which order to match things in a PCRE regular expression?
I have a dynamic regular expression that a user can supply that is used to extract two values from a string and stores them in two strings. However, there are cases where the two values can be in the string in reverse order, so the first (\w+) or w... | you can extract the strings by name using
(?<name>\w+)
and get the values with
pcre_get_named_substring
|
938,239 | 938,423 | C++ Qt: bitwise operations | I'm working on a little project for college, and I need to model transmission over network, and to impment and visualize different sorts of error correction algorithms. My improvized packet consists of one quint8: I need to convert it into a bit array, like QBitArray, append a check bit to it, trasfer it over UDP, chec... | Lets see if we can get it correct
template < class T >
static QBitArray toQBit ( const T &obj ) {
int const bitsInByte= 8;
int const bytsInObject= sizeof(T);
const quint8 *data = static_cast<const quint8*>(&obj) ;
QBitArray result(bytsInObject*bitsInByte);
for ( int byte=0; byte<bytsInObject ; ++by... |
938,309 | 938,419 | Implementing Semaphores, locks and condition variables | I wanted to know how to go about implementing semaphores, locks and condition variables in C/C++. I am learning OS concepts but want to get around implementing the concepts in C.
Any tutorials?
| Semaphores, locks, condition variables etc. are operating system concepts and must typically be implemented in terms of features of the operating system kernel. It is therefore not generally possible to study them in isolation - you need to consider the kernel code too. Probably the best way of doing this is to take a... |
938,338 | 938,875 | What is the fastest Dijkstra implementation you know (in C++)? | I did recently attach the 3rd version of Dijkstra algorithm for shortest path of single source into my project.
I realize that there are many different implementations which vary strongly in performance and also do vary in the quality of result in large graphs. With my data set (> 100.000 vertices) the runtime varies ... | The best implementations known for road networks (>1 million nodes) have query times expressed in microseconds. See for more details the 9th DIMACS Implementation Challenge(2006). Note that these are not simply Dijkstra, of course, as the whole point was to get results faster.
|
938,518 | 938,555 | How to store goto labels in an array and then jump to them? | I want to declare an array of "jumplabels".
Then I want to jump to a "jumplabel" in this array.
But I have not any idea how to do this.
It should look like the following code:
function()
{
"gotolabel" s[3];
s[0] = s0;
s[1] = s1;
s[2] = s2;
s0:
....
goto s[v];
s1:
....
goto s[v]... | It is possible with GCC feature known as "labels as values".
void *s[3] = {&&s0, &&s1, &&s2};
if (n >= 0 && n <=2)
goto *s[n];
s0:
...
s1:
...
s2:
...
It works only with GCC!
|
938,780 | 943,715 | How to I authenticate with a ISA proxy from my application seamlessly? | I am trying to us Qt to access a website and download updates, the problem is that one install base is using a Microsoft ISA proxy server which requires authentication.
Qt gives me a function to supply a username and password:
http://doc.qt.io/archives/4.6/qnetworkaccessmanager.html#proxyAuthenticationRequired
However ... | What type of proxy are you running? See
http://doc.qt.io/archives/4.6/qnetworkproxy.html
to find what proxies Qt support.
|
939,152 | 939,360 | c++ fopen is returning a file * with <bad ptr>'s | I copied this code from the libjpeg example and im passing it standard files;
FILE *soureFile;
if ((soureFile = fopen(sourceFilename, "rb")) == NULL)
{
fprintf(stderr, "can't open %s\n", sourceFilename);
exit(1);
}
jpeg_stdio_src(&jpegDecompress, soureFile);
jpeg_read_header(&jpegDecompress, true);
It results... | "select isn't broken".
If fopen returned a valid file pointer, and jpeg_read_header can't use it, someone between those two statements has done something bad to it.
The only one in between is the jpg_stdio_src call, which wouldn't fail if all it's preconditions are fulfilled.
Bottom line: see why jpg_stdio_src fails. ... |
939,215 | 939,276 | "class not registered" which class? | Consider this code:
try {
ISomeObject pObj(__uuidof(SomeClass));
ISomeObject pObj2(__uuidof(SomeOtherClass));
} catch ( _com_error& e ) {
// Log what failed
}
I.e. I have a block of code which instanciates my objects.
Sometimes (a bad install) it failes because some class wasn't properly registered.
(I do... | It's the duty of CoCreateInstance() caller to provide enough information about what it was trying to instantiate - both ATL and Native COM Support have no built-in features for that.
Instead of calling a smart pointer constructor parameterized with a class id you can call its CreateInstance() method - it has exactly th... |
939,614 | 939,731 | Negator adaptors in STL | Consider following example:
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
#include <boost/bind.hpp>
const int num = 3;
class foo {
private:
int x;
public:
foo(): x(0) {}
foo(int xx): x(xx) {}
~foo() {}
bool is_equal(int xx) const {
return (x == xx);
... | Since you're using Boost.Bind:
std::find_if(fvect.begin(), fvect.end(),
!boost::bind(&foo::is_equal, _1, 0)
);
(Note the "!")
|
939,620 | 944,097 | Runtime-dynamic properties in QPropertyEditor | I am using the QPropertyEditor from Qt-Apps.org.
is it possible to create a class with exposed Properties where the amount of properties is runtime-dynamic? So for example you have a class which represents a vector of floats with an arbitrary length which is not known at compile time. So you have a
vector<float> myFloa... | By using dynamic properties ...
In your class u can set at runtime the dynamic properties of that class
DynamicPropertiesClassForQPropertyEditor()
{
QVector<int> properties;
///.... fill in thevalues
for (int i=0 ; i!=properties.size() ; ++i )
{
const QString propertyName = QString( "value of p... |
939,622 | 939,702 | c2593 error (operator identifier is ambiguous) when compiling for x64 platform | I'm trying to compile a C++ project using Microsoft VisualStudio 2008. This particular project compiles fine if you use Win32 as target platform. If I try to compile the same project for the x64 platform I get a C2593 'operator identifier' is ambiguous error in this line:
case 't': os_ << (size_t)path->rnode->char_typ... | Ok, got it. The problem is the size_t data type which has different sizes for the two different plattforms. The operator << is defined for a various list of data types:
StringBuffer& operator<<(unsigned short int n) { _UITOA(n); }
StringBuffer& operator<<(unsigned int n) { _UITOA(n); }
On a 32-bit platform "unsi... |
939,747 | 941,797 | segmentation fault on pthread_mutex_lock | I'm getting a segmentation fault when I try to do
pthread_mutex_lock(&_mutex).
This is really odd, I'm not sure what might have caused it. I have initialized _mutex in the constructor with
pthread_mutex_init(&_mutex,NULL).
anything I can do?
| solved it, and I am very annoyed at this.
I wanted to send a Producer* as an argument to the function the Pthread runs, so I used &(*iter), where iter is an iterator that runs on a producers vector.
little did I notice it was (rightfully) a vector< Producer* >, which meant I've been sending Producer* * which produced u... |
939,778 | 939,855 | Linux API to list running processes? | I need a C/C++ API that allows me to list the running processes on a Linux system, and list the files each process has open.
I do not want to end up reading the /proc/ file system directly.
Can anyone think of a way to do this?
| http://procps.sourceforge.net/
http://procps.cvs.sourceforge.net/viewvc/procps/procps/proc/readproc.c?view=markup
Is the source of ps and other process tools. They do indeed use proc (indicating it is probably the conventional and best way). Their source is quite readable. The file
/procps-3.2.8/proc/readproc.c
May be... |
939,857 | 946,876 | is declaring a variable an instruction | Is declaring/assigning a variable in a high level language such as c++, an explicit instruction?
e.g. x = 5;
It would be handled by the loader, and treated as state information, correct?
It is not an instruction, but a state object, as opposed to something like a for loop, which is an instruction, which makes it's way ... | If your variable is a primitive type (int, char, etc.):
For a global or static variable, no. This is just an entry in the BSS or DATA segment (depending on if it is initialized or not), no executable code required. Except, of course, if the initializer has to be evaluated at runtime.
For a local variable, if it's not i... |
939,859 | 939,868 | One line class definition? | I'm updating some code and while I was working in a header, I came across the following line.
.
.
.
class HereIsMyClass;
.
.
.
That's it. It's just one line that precedes another, longer class definition. HereIsMyClass is in fact another class somewhere else, but I don't understand why this line is written here. What ... | This line in C++ is a forward declaration. It's stating that at some point in the future a class named HereIsMyClass will likely exist. It allows for you to use a class in a declaration before it's completely defined.
It's helpful for both breaking up circularly dependent classes and header file management.
For exam... |
940,087 | 940,119 | What's the correct way to use printf to print a size_t? | Size_t is defined as an unsigned integer, but the size of it depends on whether you're on a 32 or 64-bit machine. What's the correct and portable way to print out a size_t?
| Try using the %zu format string
size_t val = get_the_value();
printf("%zu",val);
The z portion is a length specifier which says the argument will be size_t in length.
Source - http://en.wikipedia.org/wiki/Printf#printf_format_placeholders
|
940,100 | 940,175 | Have You Started Using C++0x? | Most of the compilers already support C++0x. Have you started using C++0x or are you waiting for the definition of x? I have to do some refactoring of my code; should I start using the new features?
| C++0x is not a completed standard yet.
It's likely that there will be many revisions before an international accepted standard is released.
So it all depends, what are you writing code for? If it's for an work-assignment i would stick with regular C++, wait for the standard to be set and give the programming community ... |
940,216 | 940,296 | How to write a C++ template that accepts every class and class template? | Be forewarned: This question seems way more obvious than it actually is.
I'd like to write a template that can accept any concrete class or template class as a template parameter. This might seem useless because without knowing whether the passed in T is templated or not you won't know how to use it. The reason I want ... | boost::mpl does something like this (here's their idea of binding an argument). However, you have to make a lot of assumptions to make it work, like using;
template <class T> foo { }; typedef foo< int_<4> > my_foo_4;
instead of
template <int T> foo { }; typedef foo<4> my_foo_4;
to not have to offer overloads for all ... |
940,354 | 940,389 | Calculate float at compile-time using templates | I'm new to this whole Template Metaprogramming in C++ mess and I simply can't get this right.
The scenario:
For example, I've got fractions 2/5, 6/9,... I want to calculate the result of those fractions at compile-time and sort them later using that value at run-time.
Is this even possible?
Macros maybe?
Edit:
Thanks N... | Not sure what you are asking. Do you mean something like this:
#include <iostream>
using namespace std;;
template <int a, int b> struct Fract {
double value() const {
const double f = a / double(b);
return f;
}
};
int main() {
Fract <2,5> f;
cout << f.value() << endl;
}
Edit: If you s... |
940,373 | 940,891 | How would you create a console application from an existing object oriented API? | I have:
existing object oriented native code API (non GUI)
GUI application that works with this API
The goal:
To create an additional console application that lets user do some set of workflows (similar to ones of the above GUI app) by typing commands. This app should be "stateful" - available commands and their re... | To get started on the command line, first don't reinvent the wheel. There are a lot of options out there to parse commands.
In Java there is Commons CLI which provides you everything you need. There is a .NET CLI port as well.
InfiniteRed has a good writeup of how to do this in Ruby.
As far as implementation goes, yo... |
940,407 | 940,778 | Windows Mobile fails to uninstall | Testing my app on some WM Std 6.1 I found out that it fails to uninstall. I receive this error:
“[app] was not completely removed. Do you want to remove it from the list of installed programs?"
Checking my setup.dll I can tell that Uninstall_Init and Uninstall_Exit are being called each time but all the files stays (th... | There are really only three possible reasons for this:
Uninstall_Init doesn't return continue.
Uninstall_Exit doesn't return continue.
The installer engine failed.
If you have verified that 1 & 2 then ok then 3 is going to be tough to figure out.
Some problems that I have encounted:
Check the DLL dependencies of you... |
940,707 | 940,743 | How do I programmatically get the version of a DLL or EXE file? | I need to get the product version and file version for a DLL or EXE file using Win32 native APIs in C or C++. I'm not looking for the Windows version, but the version numbers that you see by right-clicking on a DLL file, selecting "Properties", then looking at the "Details" tab. This is usually a four-part dotted versi... | You would use the GetFileVersionInfo API.
See Using Version Information on the MSDN site.
Sample:
DWORD verHandle = 0;
UINT size = 0;
LPBYTE lpBuffer = NULL;
DWORD verSize = GetFileVersionInfoSize( szVersionFile, &verHandle);
if (verSize != NULL)
{
LPSTR verData = new char[verSize];
if (GetFileVer... |
940,877 | 940,889 | Extend an existing API: Use default argument or wrapper function? | I have an existing method (or function in general) which I need to grow additional functionality, but I don't want to break any use of the method elsewhere in the code. Example:
int foo::bar(int x)
{
// a whole lot of code here
return 2 * x + 4;
}
is widely used in the codebase. Now I need to make the 4 into a param... | I usually use a wrapper function (via overloading most of the time) instead of default parameters.
The reason is that there are two levels of backward compatibility:
Having source-level backward compatibility means that you have to recompile the calling code without changes, because the new function signatures are com... |
941,032 | 941,065 | how do I stop a C++ application during execution to debug into a dll? | I have an application for which I do not have the code, and a dll for which I do have the code. I need to be able to debug into the dll, but lacking the source for the exe, how do I do this?
The dll code is mfc c++; I believe that the main app is the same thing as well.
I've tried doing a 'set target application' deal... | If the application is linked against a non-debug DLL and does not have debug symbols itself, this isn't really likely to be fruitful. You might want to look here for information on using windows symbol packages to help you if you're curious about what's going in inside windows DLL's, but by and large, an application w... |
941,571 | 941,607 | Function pointer problem | I am trying to use a function pointer, but the 3 lines below just do not seem to want to cooperate...
I'm getting error code C3867.
Can you see what I'm doing wrong?
In .h file
void MyFunc(int, FILEINFO*(*)(FILEINFO*), FILEINFO*, int);
The definition in the .cpp file
void MyFunc(int number, FILEINFO*(*GetFiles)(FILEIN... | You cannot pass a non-static member function of a class as an
ordinary function pointer, since a member function implicitly uses the
this-pointer. A solution for this is to define a static member function that takes a pointer
to the class as it's first argument and wraps the call to BigClass::PassThis and pass a pointe... |
941,669 | 941,818 | Visually marking conditional compilation | We have a large amount of C/C++ code that's compiled for multiple targets, separated by #ifdefs. One of the targets is very different from the others and it's often important to know if the code you're editing is compiled for that target. Unfortunately the #ifdefs can be very spread out, so it's not always obvious wh... | Check out Visual SlickEdit. The "Selective Display" option might be what you are looking for. I can't find any on-line documentation on it, but it will allow you to essentially apply a set of macro definitions to the code. So you can tell it to show you the code as the compiler will see it with a set of macros defined.... |
941,809 | 941,844 | Re-learn modern C++ resources? | I haven't touch C++ in more then 8 years. I recently had to do fix some C++ code, and although I still can code, I feel like I no more belongs to the camp of C++ programmers. I don't know any libraries, didn't pay attention to the new language features / improvements / best practices.
Qt Creator and Qt seems like a nic... | Get to know the S.tandard T.emplate L.ibrary.
Get to know boost, if you are really on the cutting edge.
Read the books "effective c++", and "effective STL" by scott meyers.
Read the "C++ faq lite".
(not necsissarily in that order)
|
941,832 | 941,953 | Is it safe to delete a void pointer? | Suppose I have the following code:
void* my_alloc (size_t size)
{
return new char [size];
}
void my_free (void* ptr)
{
delete [] ptr;
}
Is this safe? Or must ptr be cast to char* prior to deletion?
| It depends on "safe." It will usually work because information is stored along with the pointer about the allocation itself, so the deallocator can return it to the right place. In this sense it is "safe" as long as your allocator uses internal boundary tags. (Many do.)
However, as mentioned in other answers, delet... |
942,170 | 942,182 | c++ functor and function templates | consider this simple and pointless code.
#include <iostream>
struct A {
template<int N>
void test() {
std::cout << N << std::endl;
}
};
int main() {
A a;
a.test<1>();
}
It is a very simple example of a function template. What if however, I wanted to replace A::test with an overloaded oper... | There's not another "direct" way I know other than the:
a.operator()<1>();
syntax. If you're open to changing the code, moving the template parameter to the class would work, or using a (boost|tr1)::bind to make a (boost|tr1)::function object.
|
942,251 | 942,261 | In C/C++ why does the do while(expression); need a semi colon? | My guess is it just made parsing easier, but I can't see exactly why.
So what does this have ...
do
{
some stuff
}
while(test);
more stuff
that's better than ...
do
{
some stuff
}
while(test)
more stuff
| Because you're ending the statement. A statement ends either with a block (delimited by curly braces), or with a semicolon. "do this while this" is a single statement, and can't end with a block (because it ends with the "while"), so it needs a semicolon just like any other statement.
|
942,399 | 993,795 | How to redefine clog's rdbuf() to be a tee to the original rdbuf() of clog and that of a log file? | Does anyone have an example of how to redefine the C++ built in clog to instead have a new associated rdbuf() which is processed to be a tee to the original clog.rdbuf() and the rdbuf() of a ofstream object to a log file on disk.
The intention is to have the code use the std::clog throughout but to have it go to the bo... | You will have to write a custom streambuf derived class. Have it spit out data to to both your ofstream's rdbuf and your original clog rdbuf.
A general example of writing a custom streambuf:
http://www.dreamincode.net/code/snippet2499.htm
Stashing the new stream buffer can be done as follows:
// grab buffer for clog
s... |
942,421 | 942,432 | Are endless loops in bad form? | So I have some C++ code for back-tracking nodes in a BFS algorithm. It looks a little like this:
typedef std::map<int> MapType;
bool IsValuePresent(const MapType& myMap, int beginVal, int searchVal)
{
int current_val = beginVal;
while (true)
{
if (current_val == searchVal)
return true;
... | I believe that there are cases where it's fine for seemingly infinite loops to exist. However this does not appear to be one of them. It seems like you could just as easily write the code as follows
while (current_val != searchVal ) {
MapType::iterator it = myMap.find(current_val);
assert(current_val != myMap... |
942,574 | 942,639 | Using pthread_setspecific and pthread_getspecific to store a pointer to a std::map instance | I'm using a map as a thread specific cache to keep track of failed LDAP searches. I dynamically allocate the map and store the pointer using pthread_setspecific. When checking the cache or incrementing the failure count I use pthred_getspecific in order to retrieve the void* pointer and static_cast the pointer back t... | When your test code calls sGetKeyserverFailedSearch(), it is then assigning the pointers to local map variables, thus making copies of the map contents. Any changes you make to those variables will not be reflected in the original maps that you store with pthread_setspecific(), as evident by your logging (map1's size ... |
943,087 | 943,155 | What exactly will happen if I disable C++ exceptions in a project? | Visual C++ has a compiler setting "Enable C++ Exceptions" which can be set to "No". What exactly will happen if I set it this way? My code never explicitly throws or catches exceptions (and therefore the first thrown exception will terminate the program anyway) and doesn't rely on stack unwinding - should I expect any ... | The MSDN documentation of the setting explains the different exception modes and even gives code examples to show the difference between the different modes. Furthermore, this article might be interesting, even though it's pretty old.
Bottom line: The option basically enables or disables the tracking of the life-spans ... |
943,245 | 943,301 | replace spin lock with signal | i have alot of spin locks in my multithread code and most of the time they are waiting for other threads to do work and thus chew alot of cpu usage. In linux i normally use pthread_cond_wait and pthread_cond_signal to pause a thread and wake up when signaled. Is there something like this in the boost libraries? Having ... | Found it, boost calls them condition variables: http://www.boost.org/doc/libs/1_39_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref
|
943,267 | 943,294 | Is it a good practice to use unions in C++? | I need to define a class like this:
class Color
{
private:
union Data
{
unsigned int intValue;
unsigned char argbBytes[4];
}
private:
Data m_data;
};
Another way is of course define the data as integer and cast it to char array whenever necessary.
I'm wondering which one is the preferred wa... | Unions can be fine, as long as you use them carefully.
They can be used in two ways:
To allow a single type of data to be accessed in several ways (as in your example, accessing a colour as an int or (as you probably intended) four chars)
To make a polymorphic type (a single value that could hold an int or a float for... |
943,279 | 948,550 | Printed CDC appears tiny on paper | When I print the CDC for a report control that I've created it appears tiny (less than 1 square inch on paper). How can I get the report to be printed to occupy the entire page ?
Or in other words, how can I make the entire report to appear in one printed page.
CPrintDialog printDialog(FALSE);
printDialog.... | As others have said, this is because, in general, the display resolution of printers is a lot higher than displays. Displays are usually 96 to 120DPI: at 96DPI this means that an image of 96 pixels (dots) by 96 pixels occupies approximately 1 square inch on the display. However, if you just take that image and print it... |
943,755 | 944,171 | gcc optimization flags for Xeon? | I'd want your input which gcc compiler flags to use when optimizing for Xeons?
There's no 'xeon' in mtune or march so which is the closest match?
| Xeon is a marketing term, as such it covers a long list of processors with very different internals.
If you meant the newer Nehalem processors (Core i7) then this slide indicates that as of 4.3.1 gcc should be use -march=generic (though your own testing of your own app may find other settings that outperform this). The... |
944,033 | 944,190 | Is this a memory leak in MFC | // CMyDialog inherits from CDialog
void CMyFrame::OnBnClickedCreate()
{
CMyDialog* dlg = new CMyDialog();
dlg->Create( IDD_MYDIALOG, m_thisFrame );
dlg->ShowWindow( SW_SHOW );
}
I'm pretty sure this leaks. What I'm really asking is: is there any "magic" in MFC that does dialog cleanup when the dialog is ... | Yes, it is memory leak in your case but you can avoid memory leak in cases where modeless dialog allocated on the heap by making use of overriding PostNcDestroy.
Dialogs are not designed for auto-cleanup ( where as Main frame windows, View windows are).
In case you want to provide the auto-cleanup for dialogs then you ... |
944,302 | 944,361 | copy block of memory | I need a suggestion on on how do I copy a block of memory efficiently, in single attempt if possible, in C++ or assembly language.
I have a pointer to memory location and offset. Think of a memory as a 2D array that I need to copy consisting of rows and columns.
| If you need to implement such functionality yourself, I suggest you to check up Duff's Device if it has to be done efficiently.
|
944,370 | 944,396 | How to get the address of a value, pointed to by a pointer | I have a pointer to an int.
int index = 3;
int * index_ptr = &index;
index_ptr is a member variable of a class IndexHandler.
class A has a std::vector of IndexHandlers, Avector.
class B has a std::vector of pointers to IndexHandlers, Bvector, which I set to point to the items in class A's vector, thusly:
Bvector.push_... | the non-iterator method to print them out side-by-side:
for (size_t i = 0; i < Avector.size(); i++)
{
std::cout << "Avector ptr:" << Avector[i].GetPtr() << ", Bvector ptr:" << Bvector[i] << std::endl;
}
This will print out the pointer values of each one.
One thing you should be aware of though. If the pointer in the... |
944,429 | 947,005 | error C1854: cannot overwrite information formed during creation of the precompiled header in object file | foo.cpp(33918) : fatal error C1854: cannot overwrite information formed
during creation of the precompiled header in object file: 'c:\somepath\foo.obj'
Consulting MSDN about this gives me the following information:
You specified the /Yu (use precompiled
header) option after specifying the
/Yc (create precompiled... | I think you can find the answer here: http://social.msdn.microsoft.com/forums/en-US/vclanguage/thread/b3aa10fa-141b-4a03-934c-7e463f92b2a5/
Basically, you need to set the stdafx.cpp file to "Create Precompiled Headers" and all the other .cpp files to "Use Precompiled Headers"
|
944,479 | 944,567 | How come pointer to a function be called without dereferencing? | I have a weird typedef statement in a C++ program, generated by Py++.
double radius(int); // function to be wrapped
typedef double (*radius_function_type)(int);
bp::def("radius", radius_function_type(&radius)); // bp::def is a function for wrapping
What I figured out so far is that the above typedef statemnt is... | Your question is confusing. Are you asking what this does:
radius_function_type(&radius)"
This is just a C++ typecast, a bit like:
radius (int (42));
but since radius is already of type radius_function_type then you can just as easily do:
bp::def("radius", radius);
but as this is code generated by Py++, it's probab... |
944,579 | 944,626 | tempnam equivalent in C++ | I need to generate random names which I'll be using to create temporary files in a directory. Currently I am using C standard function tempnam() for this. My code is in C++ and would like to use C++ equivalent for doing the same task. The code needs to work on Solaris as well as on Windows.
Is anyone aware of such thin... | Try std::tempnam in the cstdio header. ;)
The C standard library is still available in C++ code. For convenience, they provide C++ wrappers (in headers with the 'c' prefix, and no extension), and available in the std namespace.
You can also use the plain C version (stdio.h and tempnam in the global namespace, but you d... |
944,665 | 944,806 | Designing a Qt + OpenGL application in Eclipse | I'm starting a C++ project using OpenGL and Qt for the UI in eclipse. I would like to create a UI where a portion of the window contains a frame for OpenGL rendering and the rest would contain other Qt widgets such as buttons and so on.
I haven't used Qt or the GUI editor in eclipse before and I'm wondering what the b... | If you are using Qt Designer (which I think is available via Eclipse Integration), you can place a base QWidget in the layout and then "promote" that widget to a QGLWidget. To do this:
Add the QWidget to the desired place in the layout
Right-click on the widget
Select "Promote To"
Enter QGLWidget as the class name and... |
944,925 | 945,009 | c++ audio conversion ( mp3 -> ogg ) question | I was wondering if anyone knew how to convert an mp3 audio file to an ogg audio file. I know there are programs you can buy online, but I would rather just have my own little app that allowed me to convert as many files I wanted.
| It's realtive simple. I wouldn't use the Windows Media Format SDK. Simply because of the fact that it's overkill for the job.
You need a MP3 decoder and a OGG encoder and a little bit of glue code around that (opening files, setting up the codecs, piping raw audio data around ect.)
For the MP3 decoder I suggest that yo... |
945,087 | 945,227 | Method Calls in C++ with JNI? | So i have been looking into JNI calls so i can interact with some pre written C++ programs, i dont know any C++ but am trying to learn some basics. I have just been trying to do a simple call to a method outside my JNI method but always get the following error:
error c3861 'myMethod': identifier not found
#include <std... | You have to declare your methods before you call them. So in your header type
bool myMethod();
Or you can move the code above your _changeWord function, then the declaration/definition is in one.
|
945,309 | 945,321 | From C++ wchar_t to C# char via socket | I am currently building a C++ application that communicate via socket to a C# application.
My C++ app sends wchar_t* via socket.
Here is an overview of what is send :
<!-- Normal xml file--
Here is what I receive on the other side (I do a stream.read to a byte array and use
UTF8Encoding.GetString() to convert the byt... | Looks like it's sending UTF-16, not UTF-8, which makes sense - wchar_t is basically a 16-bit type (in Windows), and you're sending it down "raw" as far as I can tell. I suggest that if you're going to convert the data into an XDocument or XmlDocument, you do it with the binary data - the framework knows how to autodete... |
945,547 | 945,629 | How can I get a list of installed fonts on Windows, using unmanaged C++? | I've explored a bit, and so far I've found EnumFontFamiliesEx(...). However, it looks like this function is used to return all the charsets for a given font (e.g. "Arial").
I can't quite figure out how to get the list of installed fonts to begin with. Any help/suggestions would be appreciated.
Thank you in advance.
| You can do it something like this:
LOGFONT lf;
lf.lfFaceName[0] = '\0';
lf.lfCharSet = DEFAULT_CHARSET;
HDC hDC = ::GetDC();
EnumFontFamiliesEx(hDC, &lf, (FONTENUMPROC)&EnumFontFamExProc, 0, 0);
ReleaseDC(hDC);
Then define a callback function:
int CALLBACK EnumFontFamExProc(
ENUMLOGFONTEX *lpelfe,
NEWTEXTMETRICEX... |
945,555 | 945,566 | What caused the "Fatal error in ccfe" compilation error in the Solaris C++ compiler? | I got this error message from the C++ compiler:
CC: Fatal error in ccfe: Segmentation Fault (core dumped)
What could cause it?
| My user stack limit was very low (1MB). Since the compiler is heavily recursive, this limit as not enough. In solaris, the command for diplaying and changing this limit is ulimt. Other memory limits (virtual, heap) could cause this too.
http://forums.sun.com/thread.jspa?threadID=5389815&tstart=0
|
945,872 | 945,878 | Separating a large string | How do you say something like this?
static const string message = "This is a message.\n
It continues in the next line"
The problem is, the next line isn't being recognized as part of the string..
How to fix that? Or is the only solution to create an array of strings and then initialize t... | Enclose each line in its own set of quotes:
static const string message = "This is a message.\n"
"It continues in the next line";
The compiler will combine them into a single string.
|
946,167 | 946,212 | What is the best way to exit out of a loop after an elapsed time of 30ms in C++ | What is the best way to exit out of a loop as close to 30ms as possible in C++. Polling boost:microsec_clock ? Polling QTime ? Something else?
Something like:
A = now;
for (blah; blah; blah) {
Blah();
if (now - A > 30000)
break;
}
It should work on Linux, OS X, and Windows.
The calculations in the ... | The code snippet example in this link pretty much does what you want:
http://www.cplusplus.com/reference/clibrary/ctime/clock/
Adapted from their example:
void runwait ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait)
{
/* Do stuff while waiti... |
946,316 | 946,770 | What happened to TBitBtn and TButton inheritance chain? | I've recently began to upgrade my RAD Studio 2007 project to RAD Studio 2009. One thing I noticed is when seemingly simple code all of a sudden failed to compile.
Example Code:
class CButtonPopupMenu
{
// Snip
public:
void Init( TButton* SrcButton )
{
SrcButton->OnClick = OnButtonClick;
}
pri... | TButton and TBitBtn do still continue to share a common OnClick event, as it is implemented all the way down at the TControl level to begin with, and always has been. TButton was merely promoting the protected TControl::OnClick event to published, which TBitBtn would then inherit.
In D2009, TCustomButton, like other T... |
946,460 | 946,564 | How can I pass an argument from a web page that is loaded inside a web browser applet in a C# program, back to the C# application? | This is a probably a dumb question but here is what I've got.
A web developer has a secure login page that after a user logs into it, a database reference is made and it grants rights to a particular PDF file on our network. There is desire to have a custom locally designed application used to present that PDF file to... | InvokeScript.
http://msdn.microsoft.com/en-us/library/cc491132.aspx
Have the webmaster write something like this:
<script type="text/javascript">
function getPdfPath() {
return "/path/to/my.pdf";
}
</script>
You should then be able to:
var path = (string) oWebBrowser.InvokeScript("getPdfPath");
Alternately, you cou... |
946,642 | 946,658 | Compile error related to "index"- is it actually a function? | I'm removing all warnings from our compile, and came across the following:
warning: the address of `
char* index(const char*, int)', will always be 'true'
for the following line of code:
DEBUG_MSG("Data received from Device "<<(int)_nodeId << "for" << index <<(int)msgIn.index<<".");
DEBUG_MSG is one of our logging... | Here's a man page for index:
http://kernel.org/doc/man-pages/online/pages/man3/index.3.html
|
946,855 | 946,923 | What if any, programming fundamentals are better learned in C as opposed to C++? | As a person who wanted to increase his fundamental programming skills, I chose to learn C++ instead of C. Which leads me to ask: Is there any fundamental skills that I leave in C that might not be obtained by learning C++?
Related question: Should I learn C before learning C++?
| If all you've ever used is object-oriented programming languages like C++ then it would be worthwhile to practice a little C. I find that many OO programmers tend to use objects like a crutch and don't know what to do once you take them away. C will give you the clarity to understand why OO programming emerged in the f... |
947,211 | 947,284 | What does the PIC register (%ebx) do? | I have written a "dangerous" program in C++ that jumps back and forth from one stack frame to another. The goal is to be jump from the lowest level of a call stack to a caller, do something, and then jump back down again, each time skipping all the calls inbetween.
I do this by manually changing the stack base address ... | PIC is code that is relocated dynamically when it is loaded. Code that is non-PIC has jump and call addresses set at link time. PIC has a table that references all the places where such values exist, much like a .dll.
When the image is loaded, the loader will dynamically update those values. Other schemes reference ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.