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 a self exercise, I endeavor to code most of it myself. Eventually I'd like to have the game runnable on arbitrarily large game worlds. (to the point where i envision havening the game networked and span over many monitors in a computer lab). Right now, I've got some code that can read and write to arbitrary sections of a text console, and a simple partitioning system set up so that i can path-find efficiently. And now the question: I've ran some benchmarks, and the biggest bottleneck is the re-drawing of text consoles. Having a game world that large will require an intelligent update of the display. I don't want to have to re-push my entire game buffer every frame... I need some pointers on how to set it up so that it only draws sections of the game have have been updated. (and not just individual characters as I've got now) I've been manipulating the windows console via windows.h, but I would also be interested in getting it to run on linux machines over a puTTY client connected to the server. I've tried adapting some video-processing routines, as there is nearly a 1:1 ratio between pixel and character, but I had no luck. Really I want a simple explanation of some of the principles behind it. But some example (psudo)code would be nice too.
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 don't waste kernel resources like I would with a Win32 Mutex or Event? But I just have a nagging doubt...? To be honest, not all those objects probably need to be thread-safe for my application, but the critical section is in some low-level base class in a library, and I do need a couple of thousand of them! I may have the opportunity to modify this library, so I was wondering if there is any way to lazily create (and then use from then on) the critical section only when I detect the object is being used from a different thread to the one it was created in? Or is this what Windows would do for me?
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 object is "allocated on demand." I do not know of any documentation that says what conditions satisfy 'on demand,' but I would suspect that it is not created until a thread blocks while entering the critical section. For critical sections with a spin count, it may not be until the spin wait is exhausted. Empirically speaking, I have worked on an application that I know to have created at least 60,000 live COM objects, each of which synchronizes itself with its own CRITICAL_SECTION. I have never seen any errors that suggested I had exhausted the supply of kernel objects.
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 host name. Any ideas what I am missing?
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(....., OutType* Out) Now, in the C library, LName takes parameter Out, and calles a function named SaveH where Out is the return value (Out=SaveH(...)) and in SaveH, Out is malloc'ed as OutType returnOut=(OutType*)malloc(1,sizeof(OutType)); As far as I see, Out is perfectly malloc'ed, and in LName function I can get the address of the memory area that was allocated. But when I return to my C++ code, where I call LName and pass Out as a parameter, that parameter always has 0 as the address. If I leave everything same, but just change SaveH so that Out is not a return value, but a parameter as SaveH(....,OutType* Out) and alloc that value in C++ code before passing everything is fine. Is it normal? Is there some problem with pointer allocated in C library, using in C++ code? Thanks
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 your C code will be modifying the same original pointer.
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 do per switch statement with the same macro. Is there are more elegant solution then having all that stuff in the switch statement? Like passing the macro itself to the function? I have read about eval() like methods in C++ but they just don't feel right to me. Another way could be do determine into what the macro expands but I haven't found any info on this. Oh, it's openGL actually.
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; struct hostent *host; struct sockaddr_in sa; sa.sin_family = AF_INET; sa.sin_port = htons(xxxx); sa.sin_addr.s_addr = inet_addr("xxx.xxx.xxx.xxx"); net = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); err = connect(net, (struct sockaddr *)&sa, sizeof(sa)); if(err >= 0){ cout << "Port is Open"; } else { cout << "Port is Closed"; } } I found this on stack overflow but it just doesn't make sense to me using a select() command. Question is can we make the connect() function timeout so we dont wait a year for it to come back with an error?
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 */ ... } alarm( 0 ); /* cancel alarm */ Though using select is not much harder :) You might want to learn about raw sockets too.
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", matches, re.assign("(a)bc")); return 0; } edit: I am using boost 1.39
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 same -malign-double flag as your application. This is one of several possible scenarios where your boost library will not have binary compatibility with your application.
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 thing to what you really want to do would be to use Notifications to message between components. If you don't have the Window object around at compile time, the compiler may complain it doesn't know if Window can handle the message you are sending. For those cases you can use: [window performSelector:@selector(myMessage)] There are alternate versions of this call that allow passing objects as parameters.
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 got it covered on Windows, but I haven't a clue on Mac. Any idea of what I need to do, or where I can go for information on this would be great! Edit: For anybody else that is interested in this, this is the code I ended up using with Qt's QProcess class: QProcess proc; QStringList args; args << "-c" << "ioreg -rd1 -c IOPlatformExpertDevice | awk '/IOPlatformUUID/ { print $3; }'"; proc.start( "/bin/bash", args ); proc.waitForFinished(); QString uID = proc.readAll(); Note: I'm using C++.
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", @"|", @"grep", @"model", nil]; NSTask * task = [NSTask new]; [task setLaunchPath:@"/usr/sbin/ioreg"]; [task setArguments:args]; NSPipe * pipe = [NSPipe new]; [task setStandardOutput:pipe]; [task launch]; NSArray * args2 = [NSArray arrayWithObjects:@"/IOPlatformUUID/ { split($0, line, \"\\\"\"); printf(\"%s\\n\", line[4]); }", nil]; NSTask * task2 = [NSTask new]; [task2 setLaunchPath:@"/usr/bin/awk"]; [task2 setArguments:args2]; NSPipe * pipe2 = [NSPipe new]; [task2 setStandardInput:pipe]; [task2 setStandardOutput:pipe2]; NSFileHandle * fileHandle2 = [pipe2 fileHandleForReading]; [task2 launch]; NSData * data = [fileHandle2 readDataToEndOfFile]; NSString * uuid = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
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 (!block) return false; uint32 bufSize = (uint32)block->size; uint64 fileSize = UTIL::FS::UTIL_getFileSize(m_szFile); if (fileSize < (block->size + block->fileOffset)) return false; char* buffer = new char[bufSize]; FHANDLE fh=NULL; try { fh = UTIL::FS::UTIL_openFile(m_szFile, UTIL::FS::FILE_READ); UTIL::FS::UTIL_seekFile(fh, block->fileOffset); UTIL::FS::UTIL_readFile(fh, buffer, bufSize); UTIL::FS::UTIL_closeFile(fh); } catch (gcException &) { SAFE_DELETEA(buffer); UTIL::FS::UTIL_closeFile(fh); return false; } bool res = false; for (uint32 x=0; x<bufSize; x++) { if (buffer[x] != 0) { res = true; break; } } SAFE_DELETEA(buffer); return res; }
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 file is not already in a cache somewhere in memory, then you may be limited to in the order of 100-150 MB/s at a maximum before the bandwidth of the disk is saturated. If you have already hit this point, then you may first need to look at an approach that avoids having to load the file, or just accept the fact that it's not going to be faster than that.
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 invalidateRect,invalidateRgn and so on. or, how can i invalidate parent without send wm_paint to child window? thx!
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 { ... // ----------------------------------------------------------------- // // Cast operator, for [] inline operator float* () { return (float*)this; } // Const cast operator, for const [] inline operator const float* () const { return (const float*)this; } // ----------------------------------------------------------------- // ... // Vertex / Vector struct { float x, y, z, w; }; // Color struct { float r, g, b, a; }; } vec4; My problem is when I now coded a 'matrix4' class, with operator vec4* which supports extracting rows from the matrix, and also have the 'side-effect' of having matrix[][] operator which is nice. typedef struct mat4 { ... // ----------------------------------------------------------------- // // Cast operator, for [] inline operator vec4* () { return (vec4*)this; } // Const cast operator, for const [] inline operator const vec4* () const { return (const vec4*)this; } // ----------------------------------------------------------------- // private: float f[16]; } mat4; My question is, why doesn't the compiler detect the ability to convert a mat4 to float*? I would suspect that the heritage of mat4 -> vec4 -> float* is reasonable, but it doesn't seem so. It came to my mind that the compiler might see it as mat4 -> vec4* -> float* which is not defined, but that assumption was invalid, since defining the operator inline operator const vec4 () const { return (vec4)*this; } does not work, and calling glMultMatrixf(mat4(...)); (for example) produces the same error message as without the operator. defining operator float* in mat4 is of course impossible, since that will eliminate the ability to use [][] (ambigious operators) Any solutions for this? or do I have to manually cast to vec4 everytime I want to autocast to float*? Auto-casting is a really nice feature and it interpolates the code with OpenGL neatly.
... 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 { float& operator[](int index) { return f[index]; } const float& operator[](int index) const { return f[index]; } operator float*() { return f; } operator const float*() const { return f; } float f[4]; }; struct mat4 { vec4& operator[](int row) { return v[row]; } const vec4& operator[](int row) const { return v[row]; } operator float*() { return f; } operator const float*() const { return f; } union { vec4 v[4]; float f[16]; }; }; int main(void) { mat4 m; ::memset(&m, 0, sizeof(mat4)); m[0][1] = 1; cout << m[0][1] << endl; // it prints 1. return 0; }
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 monitors edges. Like the ball in the game Pong. I have made programs like this that move the mouse, But I can't seem to get my head around this one. This is what I have so far, I have limited experience when it comes to a lot of functions in the Windows API. Keep in mind this is a hardcore rough draft. EDIT I haven't implemented any of the collision detection yet I just wanted to get the moving portion working. #include <windows.h> #include <math.h> int newX(int oldx); int newY(int oldy); double SmoothMoveELX(double x); int main() { int lengthInMs = 10*1000; HWND notepad = FindWindow("Notepad",NULL); RECT window; SetTimer( notepad, NULL, 30, (TIMERPROC)NULL ); int startTime = GetTickCount(); int pos = elap / lengthInMs; while(1) { RECT window; GetWindowRect(notepad,&window); int elap = (GetTickCount() - startTime); if(elap >= lengthInMs) { int NEWX = NewX(window.x); int NEWY = NewY(window.y); MoveWindow( notepad, NEWX, NEWY, 100, 100, TRUE ); } } } int NewX(int oldx) { int newx = oldx*(1-SmoothMoveELX(pos)) + 10 *SmoothMoveELX(pos)); return newx; } int newY(int oldy) { int newy = oldy*(1-SmoothMoveELX(pos)) + 10 *SmoothMoveELX(pos)); return newy; } double SmoothMoveELX(double x) { double PI = Atan(1) * 4; return ((cos(1 - x) * PI + 1) /2 ) }
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 sine function.
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 Perl and C well, it's not such a big step. Have a look at the following core documents on XS: perlxstut (XS tutorial) perlxs (XS reference) perlapi (Interpreter API) Additionally, there's plenty of tutorials and how-tos on the internet. Now, interfacing to C++ using XS requires some additional steps. It can be a bit frustrating to work out at first, but neatly falls into place once you get it. In this regard, the core documentation is sparse at best. But all is not lost. Mattia Barbon, the creator of the wxWidgets bindings for Perl, wrote a great tool "XS++" that makes this almost dead simple (or as simple as XS). It's included in Wx, but we're working on splitting it out into its own distribution. This is work in progress. You can find Mattia's XS++ code and a modified version of mine on github. Barring a release of a standalone XS++ to CPAN, I would suggest learning to write XS for C++ from other resources: Quite a long time ago, John Keiser wrote an excellent tutorial on XS and C++. It also includes further pointers to useful tools and documentation. I learned XS&C++ from that tutorial and some examples I found on CPAN. I don't recall what I looked at then. But now I can point to my own work as a (good or bad, I don't know) example: Math::SymbolicX::FastEvaluator. Similarly, the planned XS++ distribution contains a complete (albeit pointless) example of using XS++ to interface C++ and Perl. Since XS++ is translated to plain XS, you can use it to generate examples. PS: There's also the Inline::CPP module. If that works, it is probably the easiest solution. I doubt it can handle templates, though.
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 "/" (absolute path) this is the path. Otherwise if argv[0] contains "/" (relative path) append it to cwd (assuming it hasn't been changed yet). Otherwise search directories in $PATH for executable argv[0]. Afterwards it may be reasonable to check whether the executable isn't actually a symlink. If it is resolve it relative to the symlink directory. This step is not necessary in /proc method (at least for Linux). There the proc symlink points directly to executable. Note that it is up to the calling process to set argv[0] correctly. It is right most of the times however there are occasions when the calling process cannot be trusted (ex. setuid executable). On Windows: use GetModuleFileName(NULL, buf, bufsize)
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) { myVec.push_back(MyTest(i, i + 1)); } //Sort the vector in descending order on m_first without using stand alone function or functors return 0; } Is it possible to sort the vector on the variable m_first without using any stand alone functions or functors? Also, please note that I am not using boost.
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 and then calling through the usual function call mechanism. However, I have found out that the generated code is simply not inline. There is a CALL instrction for the isquare function. Why is this happening? How can I use inline functions then? EDIT: The command line options used: **** Build of configuration Debug for project InlineCpp **** **** Internal Builder is used for build **** g++ -O0 -g3 -Wall -c -fmessage-length=0 -osrc\InlineCpp.o ..\src\InlineCpp.cpp g++ -oInlineCpp.exe src\InlineCpp.o
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 functions. EDIT: njsf gives the proper gcc keyword in his response.
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 = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } The problem is that many bytes of the UTF-8 string will have a negative value, and Bison interprets negative values as an EOF, and stops. Is there a way around this?
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 I can use $stdin, or 2) convert $stdin into something the C++ class can understand. Anyone have experience with binding iostreams in C++ to Ruby? Thanks.
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 instantiate an istream that uses your stream buffer.
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 = (*env)->GetObjectClass(env, obj); jmethodID mid = (*env)->GetMethodID(env, cls, "callback", "()V"); if (mid == NULL) { return; /* method not found */ } printf("In C\n"); (*env)->CallVoidMethod(env, obj, mid); } Java Program: class InstanceMethodCall { private native void nativeMethod(); private void callback() { System.out.println("In Java"); } public static void main(String args[]) { InstanceMethodCall c = new InstanceMethodCall(); c.nativeMethod(); } static { System.loadLibrary("InstanceMethodCall"); } } What are the differences in which JNI interacts with C and C++? Any help is greatly appreciated. Thanks, Pete
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 entity than a C pointer. (And JNI can actually provide real objects for your C++ code to manipulate, since C++ actually supports objects.) So "env->" has a different meaning in C++, it means "call the method that is contained in the object pointed to by "env". The other difference, I believe, is that many of the C-JNI functions require that one of your parameters be the "JNIEnv *env". So in C you might have to say (*env)->foo(env, bar). With c++, the second reference to "env" is not necessary, so you can instead say "env->foo(bar)" Unfortunately, I don't have the above book in front of me, so I can't quite confirm this! But I think investigating those two things (specifically looking for them on google or in other JNI code) will get you pretty far.
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". For example - compile this with the /clr switch #include "NativeType.h" public ref class ManagedType { NativeType* NativePtr; public: ManagedType() : NativePtr(new NativeType()) {} ~ManagedType() { delete NativePtr; } void ManagedMethod() { NativePtr->NativeMethod(); } }; Then in C#, add a reference to your ManagedType assembly, and use it like so: ManagedType mt = new ManagedType(); mt.ManagedMethod(); Check out this blog post for a more explained example.
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, and is there a way to get rid of this warning without using strcat_s? Also, if the only way to get rid of the warning is to use strcat_s, how does it work (syntax-wise: apparently it does not take two arguments).
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 to pass in the length of the buffer into which you are copying the string; it will truncate the string if necessary to make sure that the buffer is not overrun. google strcat_s to see precisely how to use it.
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++ is limited to only the first dimension being variable. Another efficient option is to do the 2d indexing manually into a big 1d array, as another answer shows, allowing the same compiler optimizations as a real 2D array (e.g. proving or checking that arrays don't alias each other / overlap). Otherwise, you can use an array of pointers to arrays to allow 2D syntax like contiguous 2D arrays, even though it's not an efficient single large allocation. You can initialize it using a loop, like this: int** a = new int*[rowCount]; for(int i = 0; i < rowCount; ++i) a[i] = new int[colCount]; The above, for colCount= 5 and rowCount = 4, would produce the following: Don't forget to delete each row separately with a loop, before deleting the array of pointers. Example in another answer.
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, the obj files, creating a map file and ripping through it. edit again So objdump along with a python script seems to have done what I want.
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 which member variable (some are hard failures, some are soft).
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 returns the status code as the return value and then returns the message status via an 'out' parameter. If you are simply returning a set of 'codes', it might make more sense to construct a struct type and return that. In that case, I would be prone to pass it in as an out parameter and have the method internally update it instead of allocating a new one each time. Are you planning on doing this once or many times?
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 you know of any existing controls/sample code (I couldn't find anything). Otherwise, if I subclass the control to provide this functionality what would be a good approach?
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( HWND hwnd ) { SubclassWindow( hwnd ); } void SetStatusMessage( const std::wstring& msg ) { m_message = msg; } void OnPaint( HDC hDc ) { SetMsgHandled( FALSE ); if( GetItemCount() == 0 ) { if( !m_message.empty() ) { CRect cRect, hdrRect; GetClientRect( &cRect ); this->GetHeader().GetClientRect( &hdrRect ); cRect.top += hdrRect.Height() + 5; PAINTSTRUCT ps; SIZE size; WTL::CDCHandle handle = this->BeginPaint( &ps ); handle.SelectFont( this->GetFont() ); handle.GetTextExtent( m_message.c_str(), (int)m_message.length(), &size ); cRect.bottom = cRect.top + size.cy; handle.DrawText( m_message.c_str(), -1, &cRect, DT_CENTER | DT_SINGLELINE | DT_VCENTER ); this->EndPaint( &ps ); SetMsgHandled( TRUE ); } } } }; After the search runs, if there are no results, I call SetStatusMessage and the message is displayed centered under the header. That's what I wanted. I'm kind of a newbie at subclassing controls so I'm not sure if this is the best solution.
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.begin()); if (values.empty()) return; MapIndex *&mi = mapM[s]; // <- question about this line if (!mi) mi = new MapIndex(); mi->add(values); } } The main concern I have is whether the mapM[s] expression would return reference to NULL pointer if new item is added to the map? The SGI docs say this: data_type& operator[](const key_type& k) Returns a reference to the object that is associated with a particular key. If the map does not already contain such an object, operator[] inserts the default object data_type(). So, my question is whether the insertion of default object data_type() will create a NULL pointer, or it could create an invalid pointer pointing somewhere in the memory?
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 can be opened from a series of calls.
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 std::wstring GetKeyPathFromKKEY(HKEY key) { std::wstring keyPath; if (key != NULL) { HMODULE dll = LoadLibrary(L"ntdll.dll"); if (dll != NULL) { typedef DWORD (__stdcall *NtQueryKeyType)( HANDLE KeyHandle, int KeyInformationClass, PVOID KeyInformation, ULONG Length, PULONG ResultLength); NtQueryKeyType func = reinterpret_cast<NtQueryKeyType>(::GetProcAddress(dll, "NtQueryKey")); if (func != NULL) { DWORD size = 0; DWORD result = 0; result = func(key, 3, 0, 0, &size); if (result == STATUS_BUFFER_TOO_SMALL) { size = size + 2; wchar_t* buffer = new (std::nothrow) wchar_t[size/sizeof(wchar_t)]; // size is in bytes if (buffer != NULL) { result = func(key, 3, buffer, size, &size); if (result == STATUS_SUCCESS) { buffer[size / sizeof(wchar_t)] = L'\0'; keyPath = std::wstring(buffer + 2); } delete[] buffer; } } } FreeLibrary(dll); } } return keyPath; } int _tmain(int argc, _TCHAR* argv[]) { HKEY key = NULL; LONG ret = ERROR_SUCCESS; ret = RegOpenKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft", &key); if (ret == ERROR_SUCCESS) { wprintf_s(L"Key path for %p is '%s'.", key, GetKeyPathFromKKEY(key).c_str()); RegCloseKey(key); } return 0; } This will print the key path on the console: Key path for 00000FDC is '\REGISTRY\MACHINE\SOFTWARE\Microsoft'.
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 template<> syntax that I'm used to seeing before it, declaring this as a template specialization. But it does compile. Is this safe? Is this correct?
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: class Visitor { public: // corrected as pointed by stefanB, thanks template <typename T> void operator()( T data ) { std::cout << "generic template" << std::endl; } void operator()( bool data ) { std::cout << "regular member function" << std::endl; } }; template <> // Corrected: specialization is a new definition, not a declaration, thanks again stefanB void Visitor::operator()( int data ) { std::cout << "specialization" << std::endl; } int main() { Visitor v; v( 5 ); // specialization v( true ); // regular member function v.operator()<bool>( true ); // generic template even if there is a non-templated overload // operator() must be specified there (signature of the method) for the compiler to // detect what part is a template. You cannot use <> right after a variable name } In your code there is not much of a difference, but if your code needs to pass the template parameter type it will get funnier: template <typename T> T g() { return T(); } template <> int g() { return 0; } int g() { return 1; } int main() { g<double>(); // return 0.0 g<int>(); // return 0 g(); // return 1 -- non-templated functions take precedence over templated ones }
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; file.read(reinterpret_cast<char*>(&data), sizeof(data)); return data; } but that required that I create a variable of the type to use every time I wanted to use FileRead, and I really don't feel like redesigning an entire program just because of one function, so is there anyway to use a typename as a parameter?
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 streaming it out of a file anyway. Call it like this: char value=FileRead<char>(file, pos); If you do not want to have to specify the type in the call, you could modify your API: template<typename T> void FileRead(std::fstream &file, int pos, T &data) { file.read(reinterpret_cast<char*>(&data), sizeof(T)); } Then call it like this - the type is inferred: char value; FileRead(file, pos, value);
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 the vector 'by const reference' from any other class that i declare the Node object instead of passing a copy?
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 reference, so you don't make a copy.
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 templates, but I'll use Boost's variant here for simplicity. Why isn't something like this: typedef variant < class Foo { ... }, class Bar { ... } > Baz; allowed? I know I can define the types separately, but that means I can't use some nice macros. In most cases in C++ you are allowed to define a new type where you are using it, for example: struct Foo { ... } bar; Here I am defining a new type Foo, and a variable bar of type Foo. If things like this are allowed, why doesn't it work with templates?
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 doesn't provide this method? I just decided to use a deque instead of a queue, but still I'm interested to know why this is?
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] create a templated struct inheriting the desired adaptor, provide just the constructors and forward the args to the adaptor class, writing a swap member is a snap since the required items are protected members of the standard 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 specialization (full specialization) of the form: template< typename A > struct AA {}; template<> struct AA<int> {}; // hope this is correct, specialize for int However for function templates: template< typename A > void f( A ); template< typename A > void f( A* ); // overload of the above for pointers template<> void f<int>(int); // full specialization for int Where does this fit into this scenarion?: template<> void doh::operator()<>(bool b) {} Example code that seems to work and does not give any warnings/error (gcc 3.3.3 used): #include <iostream> using namespace std; struct doh { void operator()(bool b) { cout << "operator()(bool b)" << endl; } template< typename T > void operator()(T t) { cout << "template <typename T> void operator()(T t)" << endl; } }; // note can't specialize inline, have to declare outside of the class body template<> void doh::operator()(int i) { cout << "template <> void operator()(int i)" << endl; } template<> void doh::operator()(bool b) { cout << "template <> void operator()(bool b)" << endl; } int main() { doh d; int i; bool b; d(b); d(i); } Output: operator()(bool b) template <> void operator()(int i)
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 of the same name, which could be used to generate a specialization of the same type, can both be declared in a class. When both exist, a use of that name and type refers to the non-template member unless an explicit template argument list is supplied. And it provides an example: template <class T> struct A { void f(int); template <class T2> void f(T2); }; template <> void A<int>::f(int) { } // non-template member template <> template <> void A<int>::f<>(int) { } // template member int main() { A<char> ac; ac.f(1); //non-template ac.f(’c’); //template ac.f<>(1); //template } Note that in Standard terms, specialization refers to the function you write using an explicit specialization and to the function generated using instantiation, in which case we have to do with a generated specialization. specialization does not only refer to functions you create using explicitly specializing a template, for which it is often only used. Conclusion: GCC gets it wrong. Comeau, with which i also tested the code, gets it right and issues a diagnostic: "ComeauTest.c", line 16: error: "void doh::operator()(bool)" is not an entity that can be explicitly specialized template<> void doh::operator()(bool i) Note that it isn't complaining about the specialization of the template for int (only for bool), since it doesn't refer to the same name and type: The function type that specialization would have is void(int), which is distinct from the function type of the non-template member function, which is void(bool).
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.g.| 4 bytes for foobar| 8 bytes for function1 | etc | )
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 the platform. Some platforms are very strict about alignment, while others (x86) are more forgiving, but will perform significantly better with proper alignment. So, even the compiler optimization setting can affect the object size. Inheritance and virtual functions add an additional complication. As others have said, the member functions of your class themselves do not take up "per object" space, but the existence of virtual functions in that class's interface generally implies the existence of a virtual table, essentially a lookup table of function pointers used to dynamically resolve the proper function implementation to call at runtime. The virtual table (vtbl) is accessed generally via a pointer stored in each object. Derived class objects also include all data members of their base classes. Finally, access specifiers (public, private, protected) grant the compiler certain leeway with packing of data members. The short answer is that sizeof(myObj) or sizeof(MyClass) will always tell you the proper size of an object, but its result is not always easy to predict.
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 effect: clog.rdbuf(myTee.rdbuf()); So how can I modify the tee class to have its own rdbuf() which can then be the target of clog? Thanks. -William
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 information on how to derive your own streambuf class, see here.
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 <boost/python.hpp> using namespace boost; using namespace boost::python; using namespace boost::python::api; int main(void) { Py_Initialize(); object main_module = import("__main__"); object main_namespace = main_module.attr("__dict__"); main_namespace["urllib2"] = import("urllib2"); object ignored = exec( "print 'time'\n", main_namespace); } Here, I've tried to import urllib2 using the boost import function, this compiles and runs properly, but with the following exec statement, it gives an error. object ignored = exec( "print urllib2\n" "print 'time'\n", main_namespace); Or when I remove the boost import function and do the import from within the embedded code also, it gives an error. I tried using a try: except: block but that doesn't work either. Is this because the C++ app isn't able to find the location of the urllib2 py module or something? Is there a way to set the path of the module before trying to import? This is being built only for internal use, so some hard coding of the paths is acceptable. Edit: More info: This is what happens. I did a try .. catch and called the PyErr_Print() when ever there is an exception, and got this as error all the time when there are module imports or even function calls. Error message: Traceback (most recent call last): File "<string>", line 1, in <module> TypeError: 'NoneType' object does not support item assignment Can anyone think of any reason?
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::python::object http = boost::python::import("urllib2"); try { boost::python::object response = http.attr("urlopen")("http://www.google.com"); boost::python::object read = response.attr("read")(); std::string strResponse = boost::python::extract<string>(read); cout << strResponse << endl; } catch(...) { PyErr_Print(); PyErr_Clear(); } } Anyways, thanks for the answer Jonas
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 whatever needs to be stored in the second string.
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, check the success of transmission with the check bit, and then construct quint8 out of it. Once again, it's not a practical but educational task, so don't suggest me to use real algoriths like CRC... So my question is: how do I convert any data type (in this case quint8) into QBitArray? I mean any data in computer is a bit array, but how do I access it is the question. Thanks, Dmitri.
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 ; ++byte ) { for ( int bit=0; bit<bitsInByte; ++bit ) { result.setBit ( byte*bitsInByte + bit, data[byte] & (1<<bit) ) ; } } return result; } void Foo () { Bar b ; QBitArray qb = toQBit ( b ) ; }
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 look at the Linux Kernel, with the help of a book such as Understanding The Linux Kernel.
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 from 20 minutes to a few seconds. Th shortest paths also vary by 1-2%. Which is the best implementation you know? EDIT: My Data is a hydraulic network, with 1 to 5 vertices per node. Its comparable to a street map. I made some modifications to a already accelerated algorithm (using a sorted list for all remaining nodes) and now find to the same results in a fraction of time. I have searched for such a thing quite a while. I wonder if such a implementation already exists. I can not explain the slight differences in results. I know that Dijkstra is not heuristic, but all the implementations seem to be correct. The faster solutions have the results with shorter paths. I use double precision math exclusively. EDIT 2: I found out that the differences in the found path are indeed my fault. I had inserted special handling for some vertices (only valid in one direction) and forgot about that in the other implementation. BUT im still more than surprised that Dijkstra can be accelerated dramatically by the following change: In general a Dijkstra algorithm contains a loop like: MyListType toDoList; // List sorted by smallest distance InsertAllNodes(toDoList); while(! toDoList.empty()) { MyNodeType *node = *toDoList.first(); toDoList.erase(toDoList.first()); ... } If you change this a little bit, it works the same, but performs better: MyListType toDoList; // List sorted by smallest distance toDoList.insert(startNode); while(! toDoList.empty()) { MyNodeType *node = *toDoList.first(); toDoList.erase(toDoList.first()); for(MyNeigborType *x = node.Neigbors; x != NULL; x++) { ... toDoList.insert(x->Node); } } It seems, that this modification reduces the runtime by a order not of magnitude, but a order of exponent. It reduced my runtime form 30 Seconds to less than 2. I can not find this modification in any literature. It's also very clear that the reason lies in the sorted list. insert/erase performs much worse with 100.000 elements that with a hand full of. ANSWER: After a lot of googling i found it myself. The answer is clearly: boost graph lib. Amazing - i had not found this for quite a while. If you think, that there is no performance variation between Dijkstra implementations, see wikipedia.
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]; s2: .... goto s[v]; } Does anyone have a idea how to perform this?
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 other applications do this without asking the user for details. How do I achieve this?
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 in a file pointer that contains no information and therefore breaks on the last line with access violations. Any ideas? EDIT: On Tobias' advice the fopen does appear to open the file ok but the jpeg_read_header is in turn failing with the access violation still. EDIT: After a little more digging JPEG support with ijg - getting access violation
"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. My guess: it needs to be constructed using the jpeg_create_decompress macro.
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 don't have a particular problem, rather general discussion here.) Is there some way to, from the caught exception or otherwise, realize what class failed? A have pondered to make a wrapper of my own which stores a variable like gLastCreateAttemptUuid, but it feel cumbersome. Also, suppose that SomeClass in turn attempt to instanciate something else, which isn't registered. Can one then figure out the underlying issue?
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 the same set of parameters but doesn't throw exceptions. Then you could check the HRESULT and handle the error and provide the class id you just used to the error handler. However it will not help ypu if the problem happens in the code you don't control. In extreme cases you can use Process Monitor to monitor registry queries and detect which class id is causing the problem.
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); } void print() { std::cout << "x = " << x << std::endl; } }; typedef std::vector<foo> foo_vect; int main() { foo_vect fvect; for (int i = -num; i < num; i++) { fvect.push_back(foo(i)); } foo_vect::iterator found; found = std::find_if(fvect.begin(), fvect.end(), boost::bind(&foo::is_equal, _1, 0)); if (found != fvect.end()) { found->print(); } return 0; } Is there a way to use some sort of negator adaptor with foo::is_equal() to find first non zero element. I don't want to write foo::is_not_equal(int) method, I believe there is a better way. I tried to play with std::not2, but without success.
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> myFloats; as a class member. How to expose this as a property with the Q_PROPERTY macro. So at the end I like to have the following view in the property editor widget: MyClass value of myFloats[0] value of myFloats[1] value of myFloats[2] ... ... Thanks in advance!
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 properties[%1]").arg(i); setProperty( qPrintable(propertyName) ,properties.at(i) ); } }
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_type; break; Anyone has a clue why the same line compiles fine for 32-bit but fails for 64-bit with such a high level error?
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 "unsigned int" is a perfect match for size_t. On 64-bit platforms size_t is 64 bits and doesn't match exactly on any operator declaration. The solution is to choose the exact operator by using the correct data type: case 't': os_ << (unsigned int)path->rnode->char_type; break; Or overload the operator using size_t: StringBuffer& operator<<(size_t) { _UITOA(n); }
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 undefined results. grrrrr. Obviously, I didn't notice this because Pthreads is in pure C and therefor uses void* as it's only way of accepting any type of arguments.
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 useful. Also a useful suggestion as posted by ephemient is linking to the API provided by libproc, which should be available in your repo (or already installed I would say) but you will need the "-dev" variation for the headers and what-not. Good Luck
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 to the cpu ? edit: OK, to clarify a bit more. I am not talking about optimisations. Assume none. I am talking about the end result of a compiled program, in an executable file format. Under the circumstances where the compiler decides not to use the MOV instruction, will the data 5 exist within the executables files data segment, or somewhere else? Is it possible for the 5 to exist as data without being an instruction, with that data later on being loaded into memory? Or, in general, will x = 5 result in a mov instruction when the program is executed.
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 initialized, usually the first one implies an assembly instruction, the others not. That's because the space allocation for them is usually made adding an offset to the stack pointer (in fact, subtracting - the stack grows backwards). When you declare your first int variable, an "ADD SP, 4" is generated; for the second, it's just changed to "ADD SP, 8". This instruction will not be at the place where you declare your variable, but instead at the function begin, because all the stack space for local variables must be allocated there. If you initialize a local variable at creation, then you will have a MOV instruction to load the value to its location in the stack. This instruction will be at the same place as the declaration, in relation to the rest of the code. These rules for local variables assume no optimization. One common form of optimization is to use CPU registers as variables, in this case no allocation is needed, but initialization will generate an instruction. Also, sometimes these registers must have their values preserved, so you'll see a PUSH instruction at the begin and a POP at the end of the function. The rules for objects when no constructor are involved (or the constructor is inlined) are a lot more complicated, but a similar logic applies. When you have a non-inlined constructor, of course you need at least an instruction for its call.
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 does it do?
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 example class HereIsMyClass; class Foo { void Bar(HereIsMyClass* p1) ... }; class HereIsMyClass { void Function(Foo f1); }
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 the time it takes to adjust. Don't refactor code you really need to implement, it might give you a loot of trouble. I however think C++0x great to play around with and also it can't hurt to be familiar with the syntax when 0x is globally accepted.
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 this is so that I can declare a general template with no definition, that users then specialize. Because users are specializing it, they always know about the type they're dealing with. But users can't specialize a template without it first being declared. You could do this: template<class T> class myclass; But that won't work if you pass in a templated T, for example myclass<std::vector> won't work. So then we try this: template<class T> class myclass; template<template<class> T> class myclass; This might be the right track, but it won't work as is because class templates can't be overloaded. So let's switch it to function templates, which can be: template<class T> void myfunc(); template<template<class> T> void myfunc(); Sweet, so we're done right? Well, there might be different numbers of parameters given to the template template parameter, so we'll need to take that into account too. template<class T> void myfunc(); template<template<class> T> void myfunc(); template<template<class, class> T> void myfunc(); template<template<class, class, class> T> void myfunc(); // etc. Ugly, but the Boost Preprocessor Library can generate this code for us (and in C++0x support for variadic templates will be added so this ugliness is only temporary). But we've still forgotten a case! What if one of T's parameters isn't a class, but a constant integer. Lets try to support that: template<class T> void myfunc(); template<template<class> T> void myfunc(); template<template<class, class> T> void myfunc(); template<template<class, class, class> T> void myfunc(); // etc. template<template<class> T> void myfunc(); template<template<class, int> T> void myfunc(); template<template<int, class> T> void myfunc(); template<template<int, class, class> T> void myfunc(); template<template<class, int, class> T> void myfunc(); template<template<class, class, int> T> void myfunc(); // etc. Uh oh. Given that any constant type can get passed into a template, in any number, mixed with class parameters, KABLOOEY combinatorial explosion. Just to make things more difficult, what if any of T's parameters are themselves templates?
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 int, char, bool, etc combination. I can't think of anything that would be more effective than the boost::mpl approach, and in general, I would think any approach would suffer a lot of problems; a class template is NOT a type, and it can't really be wedged into the type system that way (boost::mpl treats it as a function to create new types; more generically, it is used to create a "MetaFunction"). I'm not even sure if variadic templates are going to effect template template parameters (interesting question though).
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 Naveen, but it doesn't answer the question if it's possible to calculate floats at compile time using templates. Using recursion, for example. I can't find any info on the webs :/
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 seriously want to get into template programming, meta or otherwise, I strongly suggest getting hold of the book C++ Templates: The Complete Guide, which is excellent.
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 results would depend on the previously issued commands. The problem: I do not want to "reinvent the wheel". Are there existing patterns for both building the app and defining the "vocabulary"? Currently, it seems to me the best option would be to write a set of helpers and command parser "from scratch". P.S. If my API would be in .Net, I would look into PowerShell direction, but the API is large and wrapping it into .Net is very time consuming.
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, you have the right idea. But don't reinvent the wheel here, either. Encapsulate work in Command objects and look at using the Chain of Responsibility pattern; Commons Chain works well. There is also a .NET Chain port. If using these frameworks isn't an option, take a look at how they're implemented. Also if you've got a problem doing interop with some of these options, Ruby is really a nice swiss-army knife for doing this type of thing. It's relatively portable and the code can end up being really clean and easy to maintain. UPDATE: JCommander also looks interesting.
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 (they are not locked, I’ve checked) and its entry doesn’t disappear from the list of installed apps (whether I choose it to stay or not).
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 your setup DLL and try to remove as many as possible. I've found that dependencies to MSXML can cause problems. Remove any registry setup in your INF file, move it into your setup dll. I've found this to cause the uninstall to fail randomly on random devices because of this. What I needed up doing for existing customers is write a uninstall application to remove our application manually if the uninstall worked. If you do need to write a manual unistall you need to do the following: * Remove all your registry keys * Remove all your files * Remove registry key HKLM\Security\AppInstall{app name} * In WM6.1 you need to remove a database record from the EDB database "SwMgmtMetadataStore" where the SWT_INSTALL_NAME_TAG property equals your {app name}.
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 version number x.x.x.x.
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 (GetFileVersionInfo( szVersionFile, verHandle, verSize, verData)) { if (VerQueryValue(verData,"\\",(VOID FAR* FAR*)&lpBuffer,&size)) { if (size) { VS_FIXEDFILEINFO *verInfo = (VS_FIXEDFILEINFO *)lpBuffer; if (verInfo->dwSignature == 0xfeef04bd) { // Doesn't matter if you are on 32 bit or 64 bit, // DWORD is always 32 bits, so first two revision numbers // come from dwFileVersionMS, last two come from dwFileVersionLS TRACE( "File Version: %d.%d.%d.%d\n", ( verInfo->dwFileVersionMS >> 16 ) & 0xffff, ( verInfo->dwFileVersionMS >> 0 ) & 0xffff, ( verInfo->dwFileVersionLS >> 16 ) & 0xffff, ( verInfo->dwFileVersionLS >> 0 ) & 0xffff ); } } } } delete[] verData; }
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 parameter, but any code that already calls foo::bar should still receive what it expects. Should I extend and rename the old method and wrap it into a new one like int foo::extended_bar(int x, int y) { // ... return 2 * x + y; } int foo::bar(int x) { return extended_bar(x,4); } or should I declare a default argument in the header file like int bar(int x, int y=4); and just extend the function int foo::bar(int x, int y) { // ... return 2 * x + y; } What are advantages and disadvantages of each variant?
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 compatible to the old ones. This level can be achieved with both; default values and wrappers/overloading. A stronger level is binary-level backward compatibility, which even works without recompilation, e.g. when you don't have access to the calling code. Imagine you deploy your function in binary form, like in a DLL, etc. In such a case, the signatures have the be exactly the same to make it work, which is not the case for default values - they will break this level of compatibility. Another advantage of wrapper functions is - if your application has logging of any kind - you can dump out a warning in the old function that it will become obsolete in future versions and that it is recommended to use the new one.
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, where I set the application that the dll will be called from, and the application crashes a horrible, horrible death when called that way. I don't know if the fault lies with this dll or with the executable for that behavior, and it's just one of the myriad things I'd like to solve. I'm thinking that there should be some call to allow the dll to spin indefinitely until a debugger is attached to the process, at which point I should be able to debug the dll by attaching to the process. Does that make sense? Is there a better way to do this?
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 which does not have debug info and which you can't compile isn't debuggable in any meaningful way.
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)(FILEINFO*), FILEINFO* args, int type); Then here is where I'm actually calling the function MyFuncClass->MyFunc(GetNumber(), &BigClass::PassThis, GetArgs(), TheType); Any problems jump out?
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 pointer to that member function instead. Please see The Function Pointer Tutorials for more information. A better solution might be to look into using functors instead.
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 which code is compiled for which targets. Visual Studio's #ifdef highlighting can be helpful for visually identifying which code is compiled for which target, but changing the highlighting apparently requires modifications to the project file. I'm interested in finding a tool or method that can help coders quickly recognize which targets are using each line of code. Even if it requires some sort of manual in-source annotation I think it could still be helpful. Best case it's automated, not tied to a specific editor or IDE, and it could be configured to warn in certain conditions (eg "you modified some code on Target X, be sure to test your code on that platform!").
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. This is a lot more than preprocessor output since it literally hides blocks of code that would be excluded based on the macro definitions. This doesn't give you the ability to answer the question "Under what preprocessor conditions is this line of code included in compilation" though. The nice thing is that it applies the selective display filter to searches and printing.
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 nice toolset for what I need now, since I'm interested mostly in cross platform development. What would be good resources for someone like me to quickly re-learn C++ and best practices in shortest period of time? I have been doing mostly java and common lisp in the meantime, with a short strides to C, flex, Scala and Haskell.
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, deleting a void pointer will not call destructors, which can be a problem. In that sense, it is not "safe." There is no good reason to do what you are doing the way you are doing it. If you want to write your own deallocation functions, you can use function templates to generate functions with the correct type. A good reason to do that is to generate pool allocators, which can be extremely efficient for specific types. As mentioned in other answers, this is undefined behavior in C++. In general it is good to avoid undefined behavior, although the topic itself is complex and filled with conflicting opinions.
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 operator() to make it a functor? #include <iostream> struct A { template<int N> void operator()() { std::cout << N << std::endl; } }; int main() { A a; a<1>(); // <-- error, how do I do this? } Certainly if the operator() took parameters which were dependent on the template, the compiler could possibly deduce the template. But I just can't figure out the proper syntax to specify template parameters with a parameterless functor. Is there a proper way to do this? Obviously, this code would work since it bypasses the functor syntax: a.operator()<1>(); but that kinda defeats the purpose of it being a functor :-P.
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 both the default clog destination as well as to a log file on disk. Thanks. -William
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 std::streambuf* oldClogBuf = std::clog.rdbuf(); // create custom buffer which feeds both clog and an ofstream CustomBuffer* customBuf = new CustomBuffer( oldClogBuf ); // stash custom buffer std::clog.rdbuf( customBuf ); ...do stuff... // restore original clog buffer std::clog.rdbuf( oldClogBuf ); You can make the whole thing more robust by using the RAII idiom to manage the buffer switching.
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; MapType::iterator it = myMap.find(current_val); assert(current_val != myMap.end()); if (current_val == it->second) // end of the line return false; current_val = it->second; } } However, the while (true) seems... suspicious to me. I know this code works, and logically I know it should work. However, I can't shake the feeling that there should be some condition in the while, but really the only possible one is to use a bool variable just to say if it's done. Should I stop worrying? Or is this really bad form. EDIT: Thanks to all for noticing that there is a way to get around this. However, I would still like to know if there are other valid cases.
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.end()); if (current_val == it->second) // end of the line return false; current_val = it->second } return true; This seems to express the true intent of the loop better
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 to my map type. Calls to the map using the [] operator don't appear to affect the state of the map and calls to map->size() always return 0. It feels like I'm probably incorrectly using pthread_getspecific but from the examples I've looked at my code looks right. Code: typedef std::map<std::string, int> FailedSearchCacheMap; /** * Create the keyserver failed search cache key. Only called * internally and may only be called once per thread. */ static void sCreateKeyserverFailedSearchCache(void) { // Create the key used in refrencing the cache. // sFreeKeyserverFailedSearch called against the pointer when the thread exits pthread_key_create(&sFailedSearchCacheKey, sFreeFailedSearchCache); } /** * Get the keyserver failed search cache (also create one if it doesn't exist) */ static FailedSearchCacheMap * sGetKeyserverFailedSearch(void) { // Initializes the failed search cache key. // pthread_once guarantees that the create key routine is only called once static pthread_once_t sKeyserverFailedSearchOnce = PTHREAD_ONCE_INIT; pthread_once(&sKeyserverFailedSearchOnce, sCreateKeyserverFailedSearchCache); FailedSearchCacheMap* cache = static_cast<FailedSearchCacheMap *>(pthread_getspecific(sFailedSearchCacheKey)); if (IsNull(cache)) { cache = new FailedSearchCacheMap(); pthread_setspecific(sFailedSearchCacheKey, cache); } return cache; } Test Code: FailedSearchCacheMap* map_ptr1 = sGetKeyserverFailedSearch(); FailedSearchCacheMap* map_ptr2 = sGetKeyserverFailedSearch(); std::string ks("hostname"); FailedSearchCacheMap map1 = *map_ptr1; FailedSearchCacheMap map2 = *map_ptr2; int numFailedSearches = map1[ks] + 1; map1[ks] = numFailedSearches; std::cout << "numFailedSearches: " << numFailedSearches << std::endl; std::cout << "map_ptr1 address: " << map_ptr1 << std::endl; std::cout << "map_ptr2 address: " << map_ptr2 << std::endl; std::cout << "map_ptr1->size(): " << map_ptr1->size() << std::endl; std::cout << "map_ptr2->size(): " << map_ptr2->size() << std::endl; std::cout << "map1.size(): " << map1.size() << std::endl; std::cout << "map2.size(): " << map2.size() << std::endl; FailedSearchCacheMap::iterator i = map1.begin(); for(; i != map1.end(); i++) std::cout << (*i).first << ":" << (*i).second << std::endl; Test Code Output: numFailedSearches: 1 map_ptr1 address: 0x909ce88 map_ptr2 address: 0x909ce88 map_ptr1->size(): 0 map_ptr2->size(): 0 map1.size(): 1 map2.size(): 0 hostname:1
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 incremented but map_ptr1's size did not). Any modifications you want to make to the original maps must be done using the pointers that sGetKeyserverFailedSearch() returns, for example: FailedSearchCacheMap* map_ptr = sGetKeyserverFailedSearch(); std::string ks("hostname"); int numFailedSearches = (*map_ptr)[ks] + 1; (*map_ptr)[ks] = numFailedSearches; std::cout << "numFailedSearches: " << numFailedSearches << std::endl; std::cout << "map_ptr address: " << map_ptr << std::endl; std::cout << "map_ptr->size(): " << map_ptr->size() << std::endl; FailedSearchCacheMap::iterator i = map_ptr->begin(); for(; i != map_ptr->end(); i++) std::cout << (*i).first << ":" << (*i).second << std::endl;
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 more undesired behaviour from the recompiled program?
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 of all your objects. Such tracking is required, because in the case of an exception, all the proper destructors need to be called, the stack has to be unwinded, and a lot of clean up is done. Such tracking requires organizational overhead (= additional code) - this can be dropped by setting the option to "No". I haven't tried by myself, but it looks like you still can throw and catch exceptions if the option is set to "No", but the clean up and unwinding is missing, which might have very bad consequences (not recommended ;) ..
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 a quick look i couldnt find any thing. Visual studio 2005
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 way. The contradiction here is that I have remote memory of someone's remind not to use union anymore however it seems to be a cleaner solution in this case.
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 example). Case (1) Is fine because you're not changing the meaning of the type - you can read and write any of the members of the union without breaking anything. This makes it a very convenient and efficient way of accessing the same data in slightly different forms. Case (2) can be useful, but is extremely dangerous because you need to always access the right type of data from within the union. If you write an int and try to read it back as a float, you'll get a meaningless value. Unless memory usage is your primary consideration it might be better to use a simple struct with two members in it. Unions used to be vital in C. In C++ there are usually much nicer ways to achieve the same ends (e.g. a class can be used to wrap a value and allow it to be accessed in different ways). However, if you need raw performance or have a critical memory situation, unions may still be a useful approach.
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.DoModal(); CDC dcPrint; if(dcPrint.Attach(printDialog.GetPrinterDC())) { int iHorzRes = dcPrint.GetDeviceCaps(HORZRES); int iVertRes = dcPrint.GetDeviceCaps(VERTRES); int iHorzResCDC = m_CDC.GetDeviceCaps(HORZRES); int iVertResCDC = m_CDC.GetDeviceCaps(VERTRES); dcPrint.m_bPrinting = TRUE; dcPrint.BitBlt(0,0, iHorzRes, iVertRes, &m_CDC, iHorzResCDC, iVertResCDC, SRCCOPY); CFont* pOldFont = dcPrint.SelectObject(&m_HeaderFont); dcPrint.TextOut(0,0,"HelloWorld") ; dcPrint.SelectObject(pOldFont); CPrintInfo printInfo; printInfo.m_rectDraw.SetRect(0,0, iHorzRes, iVertRes); dcPrint.StartDoc("Report Print"); dcPrint.StartPage(); if(dcPrint.EndPage()) dcPrint.EndDoc(); else dcPrint.AbortDoc(); } dcPrint.DeleteDC(); m_CDC is the memory DC that I use to buffer and display the entire report on screen.
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 out on a 600DPI printer, the size of the image will be about 1/6" by 1/6" - much smaller. This is a bane of the publishing world - images that look fine on displays often look either tiny or terrible when printed. You could, as has been suggested, use StretchBlt rather than BitBlt to scale up your image. Depending on the difference between your display and printer, this will either look a bit blocky, or utterly hideously blocky. A much better option is to rewrite your code that does the drawing of the control so that you've got a method that takes a device context (and some co-ordinates) and draws into it. Your normal window painting code can pass the memory DC to this routine and then BitBlt the result to the window, and your painting code can call this method with the printer DC and some suitable co-ordinates. When writing this routine you'll have to worry about scaling: for example, you'll need to create fonts for the given device context, and with a scaling-indepdendant size (that is, specify the font size in points, not pixels), rather than relying on a pre-created font.
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 4.3 series also added -msse4.2 if you wish to optimize that aspect of FP maths. Here is some discussion comparing tuning in Intel's compiler versus some gcc flags.
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 destroyed. How would it work if dlg wasn't a pointer but declared on the stack - wouldn't the destructor destroy the window when dlg goes out of scope.
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 must override the PostNcDestroy member function in your derived class. To add auto-cleanup to your class, call your base class and then do a delete this. To remove auto-cleanup from your class, call CWnd::PostNcDestroy directly instead of the PostNcDestroy member in your direct base class. void MyDialog::PostNcDestroy() { CDialog::PostNcDestroy(); delete this; } How this works (from MSDN): When destroying a Windows window, the last Windows message sent to the window is WM_NCDESTROY. The default CWnd handler for that message (CWnd::OnNcDestroy) will detach the HWND from the C++ object and call the virtual function PostNcDestroy. Some classes override this function to delete the C++ object. "delete this" will free any C++ memory associated with the C++ object. Even though the default CWnd destructor calls DestroyWindow if m_hWnd is non-NULL, this does not lead to infinite recursion since the handle will be detached and NULL during the cleanup phase. You can also refer MSDN (Destroying Window Objects ) for further details. Note: This works for modeless dialog that can be allocated on the heap.
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_back(Avector[i].GetPtr()) With me so far? I want to check that when I resolve the pointers in Bvector, and retreive the internal IndexHandlers index_ptr, that they point to the same index_ptr as class A's... How can I check they are pointing to the same memory address?... How do i print the address of the value pointed to by both sets of pointers?
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 IndexHandler is pointing to a value within the IndexHandler then it can become invalidated if the vector is resized, and pointers to anything above an index WILL be invalidated if an item is inserted or deleted at that index. Because of this, it's generally a bad idea to keep pointers to items in a vector and if you want to do this then it's better practice to use a std::list container instead (which doesn't invalidate pointers to items in the list when you insert or delete new values)
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 header) option for the same file. Certain declarations (such as declarations including __declspec dllexport) make this invalid. We are using dllexport and precompiled headers in this case. Have anyone encountered this before and know of any workaround? Any input to shed some light on this problem is greatly appreciated. Thanks
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 not of the type, most of us are familiar with, typedef complex_type simple_alias; Rather it is a way to declare pointer to a function which takes int as argument and returns double (same as the prototype). So my question now is that, how come pointer to a function (without dereferencing) be called with address of a function as an argument? This also doesn't match with the prototype. Somebody please explain!
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 probably being extra careful with the output.
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 thing in C++? Any pointer on this would be highly appreciated.
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 did ask for the C++ version ;)) The C++ standard library only provides new functions when there's actually room for improvement. It has a string class, because a string class is an improvement over char pointers as C has. It has a vector class, because, well, it's useful. For something like tempnam, what would C++ be able to bring to the party, that we didn't already have from C? So they didn't do anything about it, other than making the old version available.
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 best approach would be? Should I create the UI by hand coding or would it be easier to use eclipse's GUI designer - I had a quick look at this and there doesn't seem to be an OpenGL widget built in. Thanks
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 as the header Hit Add Select the QGLWidget from the list of promoted widgets at the top of the dialog Hit Promote This way you don't have to go through the placeholder route and create an additional layer.
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 you take a look at the liblame library or use this decoding lib http://www.codeproject.com/KB/audio-video/madlldlib.aspx as a starting point. For OGG there aren't many choices. You need libogg and libvorbis. Easy as that. The example codes that come with the libs show you how to do the encoding. Good luck.
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 <stdio.h> #include <string.h> #include "StringFuncs.h" JNIEXPORT jstring JNICALL Java_StringFuncs_changeWord(JNIEnv *env, jobject obj, jstring inStr, jint inLen) { const char *inString; inString = env->GetStringUTFChars(inStr, NULL); char otherString[40]; strcpy_s(otherString,inString); if(myMethod()) { memset(otherString, '-', inLen); } jstring newString = env->NewStringUTF((const char*)otherString); return newString; } bool myMethod() { return true; } int main() { return 0; } Any words of wisdome?
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 byte array to a readable string) <\0!\0-\0-\0 \0N\0o\0r\0m\0a\0l\0 \0x\0m\0l\0 \0f\0i\0l\0e\0-\0- Is it a marshalling problem? What do you say? Why is it 0 extended and why unicode caracter doesn't appear on the C# side?
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 autodetect UTF-16 for XML files (IIRC). You'll potentially have problems if the XML declaration declares it to be UTF-8 when it's really UTF-16 though. Alternatively, use suitable encoding classes on the C++ side to genuinely send UTF-8. This would take extra processing time, but usually save bandwidth if that's a consideration.
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 *lpntme, DWORD FontType, LPARAM lParam ) { AfxMessageBox(lpelfe->elfFullName); //Return non--zero to continue enumeration return 1; }
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 the array to hold each line?
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 loop are for updating a simulation. Every 30ms, I'd like to update the viewport.
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 waiting */ } }
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; } private: void __fastcall OnButtonClick( TObject* Sender ) { // Do some button click stuff } }; // Snip TButton button = new TButton( this ); TBitBtn bitBtn = new TBitBtn( this ); CButtonPopupMenu popupButton = new CButtonPopupMenu( button ); CButtonPopupMenu popupBitBtn = new CButtonPopupMenu( bitBtn ); This all use to compile, but with 2009 it's failing. Looking at the inheritance chain for 2007 TBitBtn used to derive from TButton. Therefore, events that are expected on any button control (i.e. OnClick) were shared by the TButton class. Therefore, I was able to treat my TBitBtn class as a TButton. 2007 inheritance chain: TBitBtn : TButton 2009 inheritance chain: TBitBtn : TCustomButton TButton : TCustomButton In 2009, both TButton and TBitButton derive from TCustomButton, which would be fine I suppose if the button like attributes were held there. If this were the case, I could just change the code to deal with a TCustomButton instead. Unfortunately, TCustomButton does not hold things like OnClick. Therefore, I can no longer treat a TBitBtn like a TButton. Both of these classes, now have their own separate button like attributes (i.e. they both have their own OnClick event declared). I mean, at least provide an interface or something, like IButton that both TButton and TBitBtn implement. It seems that these types of seemingly innocent changes are the ones that can wreak unnecessary havoc. This seems odd and am wondering if anyone knows why CodeGear (or any Framework author for that matter) would do this type of thing? More importantly, given this fragmented inheritance, is there and elegant solution to treat a TBitBtn like a TButton?
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 TCustom... classes, does not promote protected members from base classes to published. TButton and TBitBtn promote the protected TControl::OnClick event to published individually. But the event itself still exists at the TControl level. Since it is protected at the TControl level, you can use an accessor class to reach it, ie: class TCustomButtonAccess { public: __property OnClick; }; class CButtonPopupMenu { // Snip public: void Init( TCustomButton* SrcButton ) { ((TCustomButtonAccess*)SrcButton)->OnClick = OnButtonClick; } private: void __fastcall OnButtonClick( TObject* Sender ) { // Do some button click stuff } }; Or, for any general TControl pointer: class TControlAccess { public: __property OnClick; }; class CControlPopupMenu { // Snip public: void Init( TControl* SrcControl ) { ((TControlAccess*)SrcControl)->OnClick = OnControlClick; } private: void __fastcall OnControlClick( TObject* Sender ) { // Do some click stuff } }; A more elegant solution would be to use RTTI instead, which would also allow you to handle other types of objects, such as TSpeedButton, which have their own OnClick event, ie: #include <TypInfo.hpp> class TControlAccess { public: __property OnClick; }; class CControlPopupMenu { // Snip public: void Init( TControl* SrcControl ) { TMethod m; m.Code = &OnControlClick; m.Data = this; SetMethodProp(SrcControl, "OnClick", m); } private: void __fastcall OnControlClick( TObject* Sender ) { // Do some click stuff } }; Or even: #include <TypInfo.hpp> class CObjectPopupMenu { // Snip public: void Init( TObject* SrcObject ) { TMethod m; m.Code = &OnObjectClick; m.Data = this; SetMethodProp(SrcObject, "OnClick", m); } private: void __fastcall OnObjectClick( TObject* Sender ) { // Do some click stuff } };
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 the user, which is fine as I have used cpp code from Adobe to generate a stripped down viewer, however the problem I'm faced with is integrating his web application into my windows application. It would be easier for me to just create my own login/database query, but then I'd basically be removing his entire piece of the project. That in itself presents a problem, as really this entire thing is his project and he asked me for help. So that's why I'm stuck with this situation where I"m attempting to insert a web applet in the application to present his login page. From that login page, after it authenticates, he can return a path to that particular file. He was previously just launching the associated PDF viewer (Acrobat), but what we need is a fully integrated solution. Make sense?
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 could have him write you a web service.
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 macros that the preprocessor subsitutes into a statement that takes C++ style stream operations. index does not appear to be declared, so I'm assuming that it was supposed to read: DEBUG_MSG("Data received from Device "<<(int)_nodeId << "for index " <<(int)msgIn.index<<"."); and index would be a function* to the "char* index(const char*, int)" function in the standard library, but what does the index function do? Google seems useless as it pulls up indexes of books related to C++. Is there something I'm missing in my interpretation of this warning?
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 first place and help you to understand when its useful versus when its just overkill. In the same vein, you'll learn what it's like to not rely on libraries to do things for you. By noting what features C++ developers turned into libraries, you get a better sense of how to abstract your own code when the time comes. It would be bad to just feel like you need to abstract everything in every situation. That said, you don't have to learn C. If you know C++ you can drag yourself through most projects. However, by looking at the lower-level languages, you will improve your programming style, even in the higher-level ones.
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 (setting %ebp) and jumping to a label address. It totally works, with gcc and icc both, without any stack corruption at all. The day this worked was a cool day. Now I'm taking the same program and re-writing it in C, and it doesn't work. Specifically, it doesn't work with gcc v4.0.1 (Mac OS). Once I jump to the new stack frame (with the stack base pointer set correctly), the following instructions execute, being just before a call to fprintf. The last instruction listed here crashes, dereferencing NULL: lea 0x18b8(%ebx), %eax mov (%eax), %eax mov (%eax), %eax I've done some debugging, and I've figured out that by setting the %ebx register manually when I switch stack frames (using a value I observed before leaving the function in the first place), I fix the bug. I've read that this register deals with "position independent code" in gcc. What is position independent code? How does position independent code work? To what is this register pointing?
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 a data value that defines a "base" and the target address is decided by performing calculations on the base. The base is usually set by the loader again. Finally, other schemes use various trampolines that call to known relative offsets. The relative offsets contain code and/or data that are updated by a loader. There are different reasons why different schemes are chosen. Some are fast when run, but slower to load. Some are fast to load, but have less runtime performance.