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
|
|---|---|---|---|---|
238,517
| 238,522
|
What's a quick way to trace the entry and exit of functions in a Visual Studio 2005 c++ multithreaded program?
|
I have intermittent crashes occurring in my ActiveMQ libraries due to the way I'm using the activemq-cpp API. It'd be much easier to debug the issue if I could observe every function being called leading up to the crash. Are there any quick ways to trace the entry and exit of functions in a Visual Studio 2005 c++ multithreaded program?
Thanks in advance!
|
Use a Tracer object. Something like this:
class Tracer
{
public:
Tracer(const char *functionName) : functionName_(functionName)
{
cout << "Entering function " << functionName_ << endl;
}
~Tracer()
{
cout << "Exiting function " << functionName_ << endl;
}
const char *functionName_;
};
Now you can simply instantiate a Tracer object at the top the function, and it will automatically print "exiting... " when the function exits and the destructor is called:
void foo()
{
Tracer t("foo");
...
}
|
238,535
| 238,568
|
C++ performance of accessing member variables versus local variables
|
Is it more efficient for a class to access member variables or local variables? For example, suppose you have a (callback) method whose sole responsibility is to receive data, perform calculations on it, then pass it off to other classes. Performance-wise, would it make more sense to have a list of member variables that the method populates as it receives data? Or just declare local variables each time the callback method is called?
Assume this method would be called hundreds of times a second...
In case I'm not being clear, here's some quick examples:
// use local variables
class thisClass {
public:
void callback( msg& msg )
{
int varA;
double varB;
std::string varC;
varA = msg.getInt();
varB = msg.getDouble();
varC = msg.getString();
// do a bunch of calculations
}
};
// use member variables
class thisClass {
public:
void callback( msg& msg )
{
m_varA = msg.getInt();
m_varB = msg.getDouble();
m_varC = msg.getString();
// do a bunch of calculations
}
private:
int m_varA;
double m_varB;
std::string m_varC;
};
|
Executive summary: In virtually all scenarios, it doesn't matter, but there is a slight advantage for local variables.
Warning: You are micro-optimizing. You will end up spending hours trying to understand code that is supposed to win a nanosecond.
Warning: In your scenario, performance shouldn't be the question, but the role of the variables - are they temporary, or state of thisClass?
Warning: First, second and last rule of optimization: measure!
First of all, look at the typical assembly generated for x86 (your platform may vary):
// stack variable: load into eax
mov eax, [esp+10]
// member variable: load into eax
mov ecx, [adress of object]
mov eax, [ecx+4]
Once the address of the object is loaded, int a register, the instructions are identical. Loading the object address can usually be paired with an earlier instruction and doesn't hit execution time.
But this means the ecx register isn't available for other optimizations. However, modern CPUs do some intense trickery to make that less of an issue.
Also, when accessing many objects this may cost you extra. However, this is less than one cycle average, and there are often more opprtunities for pairing instructions.
Memory locality: here's a chance for the stack to win big time. Top of stack is virtually always in the L1 cache, so the load takes one cycle. The object is more likely to be pushed back to L2 cache (rule of thumb, 10 cycles) or main memory (100 cycles).
However, you pay this only for the first access. if all you have is a single access, the 10 or 100 cycles are unnoticable. if you have thousands of accesses, the object data will be in L1 cache, too.
In summary, the gain is so small that it virtually never makes sense to copy member variables into locals to achieve better performance.
|
238,740
| 238,797
|
Visio & UML - Showing pointers in attributes and return values
|
I have the requirement of generating UML Diagrams for one of my C++ assignments. I'm using Visio 2007 and I'm having trouble representing C++ pointers. I've found a way to add a suffix to Datatypes however it's rather time consuming to do this for every pointer used or returned in my program.
Basically I'm trying to get -object1 : Object* = NULL and +Object() : Object* without digging into the properties and adding * to the suffix field every time.
I'm pretty much stuck with Microsoft software for making diagrams and coding so please don't suggest I use different software. However, if Visual Studio 2003 supports making UML Diagrams in a less painful way than Visio, I wouldn't object to using Visual Studio but please tell me where that option is.
|
One solution is to create a custom datatype with Object* as the name but that would need to be done for every class.
|
238,764
| 238,785
|
Visio & UML - Showing vectors
|
I have the requirement of generating UML Diagrams for one of my C++ assignments. I'm using Visio 2007 and I'm having trouble representing C++ vectors. The only way I can see this working is creating a custom C++ datatype or creating a vector class in my project, then for each instance of a vector in the UML, I need to dig into the properties and add <Class> into the suffix field.
Basically I'm trying to get vector<Object> without digging into the properties and adding <Class> to the suffix field every time.
I'm pretty much stuck with Microsoft software for making diagrams and coding so please don't suggest I use different software. However, if Visual Studio 2003 supports making UML Diagrams in a less painful way than Visio, I wouldn't object to using Visual Studio but please tell me where that option is.
|
You don't need to stipulate that it's a vector on the UML diagram.
In the example you're giving, there is a one-to-many relationship between one class and another. That's the significant information you need to communicate.
You've chosen to implement this as a vector: this is an implementation detail that doesn't need to go on the diagram - just display a one-to-many association.
If, for some reason, you need to change this to a std::list, or a std::deque, or any other stl container, you won't need to update the diagram, because the one-to-many concept is still the same.
Remember that you are displaying an abstraction of the code. If you want to convey how all the classes conceptually relate to eachother, a UML class diagram is ideal.
If somebody wants to know the details of how it's implemented, he or she can always use the diagram as a starting point before looking at the source code itself.
For an example of one-to-many relationships displayed using UML, click here
|
239,302
| 239,307
|
Is it useful to test the return of "new" in C++?
|
I usually never see test for new in C++ and I was wondering why.
Foo *f = new Foo;
// f is assumed as allocated, why usually, nobody test the return of new?
|
As per the current standard, new never returns NULL, it throws a std::bad_alloc instead. If you don't want new to throw(as per the old standard) but rather return NULL you should call it by postfixing it with "(std::nothrow)".
i.e.
Foo* foo = new (std::nothrow) Foo;
Of course, if you have a very old or possibly broken toolchain it might not follow the standard.
|
239,315
| 239,353
|
How to embed Ruby in C++?
|
What's the best way to embed Ruby as a scripting language in C++? Using ruby.h? SWIG? Something else? What I need is to expose some C++ objects to Ruby and have the Ruby interpreter evaluate scripts that access these objects. I don't care about extending Ruby or accessing it in C++.
I've found this article on embedding Ruby in C++, and while it's very useful, it's kinda old and I was wondering if there are any other resources on the subject (or open source implementations of similar engines).
|
swig is probablly the way to go..... but ruby doesnt embed too well......
if you want a language that embeds nicely into C++, try lua
|
239,344
| 239,348
|
How could I improve this C++ code
|
I want your suggestion on the following pseudo-code. Please suggest how could I improve it, whether or not I could use some design patterns.
// i'm receiving a string containing : id operation arguments
data = read(socket);
tokens = tokenize(data," "); // tokenize the string based on spaces
if(tokens[0] == "A") {
if(tokens[1] == "some_operation") {
// here goes code for some_operation , will use the remaining tokens as arguments for function calls
}
else if(tokens[1] == "some_other_operation") {
// here goes code for some_other_operation , will use the remaining tokens
}
...
else {
// unknown operation
}
}
else if(tokens[0] == "B") {
if(tokens[1] == "some_operation_for_B") {
// do some operation for B
}
else if(tokens[1] == "yet_another_operation") {
// do yet_another_operation for B
}
...
else {
// unknown operation
}
}
I hope you get the point . The thing is I have a large number of id's and each has it's own operations , and I think it's kinda ugly to have 10 screens of code containing a lot of if's and else if's.
|
Have a class for each ID which implements a common interface. Basically the Strategy pattern IIRC.
So you'd call (pseudo)code like:
StrategyFactory.GetStrategy(tokens[0]).parse(tokens[1..n])
|
239,588
| 239,627
|
STL sorted set where the conditions of order may change
|
I have a C++ STL set with a custom ordering defined.
The idea was that when items get added to the set, they're naturally ordered as I want them.
However, what I've just realised is that the ordering predicate can change as time goes by.
Presumably, the items in the set will then no longer be in order.
So two questions really:
Is it harmful that the items would then be out of order? Am I right in saying that the worst that can happen is that new entries may get put into the wrong place (which actually I can live with). Or, could this cause crashes, lost entries etc?
Is there a way to "refresh" the ordering of the set? You can't seem to use std::sort() on a set. The best I can come up with is dumping out the contents to a temp container and re-add them.
Any ideas?
Thanks,
John
|
set uses the ordering to lookup items. If you would insert N items according to ordering1 and insert an item according to ordering2, the set cannot find out if the item is already in.
It will violate the class invariant that every item is in there only once.
So it does harm.
|
240,184
| 240,235
|
Freeing memory on the heap. Should I and how?
|
I'm writing a CESetup.dll for a Windows Mobile app. It must be unmanaged, which I have little experience with. So I'm unsure of whether I should free the memory I allocate and how I do it.
Here's the function I've written:
Uninstall_Init(
HWND hwndParent,
LPCTSTR pszInstallDir
)
{
LPTSTR folderPath = new TCHAR[256];
_stprintf(folderPath, _T("%s\\cache"), pszInstallDir);
EmptyDirectory(folderPath);
RemoveDirectory(folderPath);
_stprintf(folderPath, _T("%s\\mobileadmin.dat"), pszInstallDir);
DeleteFile(folderPath);
// To continue uninstallation, return codeUNINSTALL_INIT_CONTINUE
// If you want to cancel installation,
// return codeUNINSTALL_INIT_CANCEL
return codeUNINSTALL_INIT_CONTINUE;
}
As I understand it, folderPath is allocated on the heap. EmptyDirectory() is my own function that removes all content in the directory. RemoveDirectory() and DeleteFile() are system calls.
My question is should I deallocate folderPath before the function exits? If I should, how do I do it?
|
I think you want to use this:
delete [] folderPath;
It looks like you're allocating an array of TCHARs, which makes sense since it's a string. When you allocate an array, you must delete using the array delete operator (which you get by including the brackets in the delete statement). I'm pretty sure you'll get a memory leak with Treb's solution.
|
240,212
| 240,308
|
What is the difference between new/delete and malloc/free?
|
What is the difference between new/delete and malloc/free?
Related (duplicate?): In what cases do I use malloc vs new?
|
new / delete
Allocate / release memory
Memory allocated from 'Free Store'.
Returns a fully typed pointer.
new (standard version) never returns a NULL (will throw on failure).
Are called with Type-ID (compiler calculates the size).
Has a version explicitly to handle arrays.
Reallocating (to get more space) not handled intuitively (because of copy constructor).
Whether they call malloc / free is implementation defined.
Can add a new memory allocator to deal with low memory (std::set_new_handler).
operator new / operator delete can be overridden legally.
Constructor / destructor used to initialize / destroy the object.
malloc / free
Allocate / release memory
Memory allocated from 'Heap'.
Returns a void*.
Returns NULL on failure.
Must specify the size required in bytes.
Allocating array requires manual calculation of space.
Reallocating larger chunk of memory simple (no copy constructor to worry about).
They will NOT call new / delete.
No way to splice user code into the allocation sequence to help with low memory.
malloc / free can NOT be overridden legally.
Table comparison of the features:
Feature
new / delete
malloc / free
Memory allocated from
'Free Store'
'Heap'
Returns
Fully typed pointer
void*
On failure
Throws (never returns NULL)
Returns NULL
Required size
Calculated by compiler
Must be specified in bytes
Handling arrays
Has an explicit version
Requires manual calculations
Reallocating
Not handled intuitively
Simple (no copy constructor)
Call of reverse
Implementation defined
No
Low memory cases
Can add a new memory allocator
Not handled by user code
Overridable
Yes
No
Use of constructor / destructor
Yes
No
Technically, memory allocated by new comes from the 'Free Store' while memory allocated by malloc comes from the 'Heap'. Whether these two areas are the same is an implementation detail, which is another reason that malloc and new cannot be mixed.
|
240,874
| 240,881
|
Is there an easy way to use a base class's variables?
|
When you have a derived class, is there an simpler way to refer to a variable from a method other than:
BaseClass::variable
EDIT
As it so happens, I found a page that explained this issue using functions instead:
Template-Derived-Classes Errors. Apparently it makes a difference when using templates classes.
|
If the base class member variable is protected or public than you can just refer to it by name in any member function of the derived class. If it is private to the base class the compiler will not let the derived class access it at all. Example:
class Base
{
protected:
int a;
private:
int b;
};
class Derived : public Base
{
void foo()
{
a = 5; // works
b = 10; // error!
}
};
There is also something to be said for keeping all member variables private, and providing getters and setters as needed.
Also, beware of "hiding" data members:
class Base
{
public:
int a;
};
class Derived : public Base
{
public:
int a;
};
This will create two variables named a: one in Base, one in Derived, and it will likely lead to confusion and bugs.
|
241,144
| 251,586
|
How to set an initial size of a QScrollArea?
|
I know that this is a very specific C++ and Qt related question, but maybe someone can help me, anyway ...
See the code below: I want to display an image within a scroll area. The view port of the scroll area shall have a defined initial size. That means, if the image's size is bigger than the initial size of the view port, scroll bars will be visible, otherwise not.
// create label for displaying an image
QImage image( ":/test.png" );
QLabel *label = new QLabel( this );
label->setPixmap( image.toPixmap() );
// put label into scroll area
QScollArea *area = new QScrollArea( this );
area->setWidget( label );
// set the initial size of the view port
// NOTE: This is what I'd like to do, but this method does not exist :(
area->setViewPortSize( QSize( 300, 300 ) );
It shall be possible to resize the whole application so that the view port will get another size than the initial one.
Unfortunatelly I was not able to find out, how to set the size of the view port. Qt's layout mechanism seems to set a default size for the view port, but up to now I was not able to change it. Setting a new size with
area->setMinimumSize( QSize( 300, 300 ) );
will actually set the demanded size, but then the scroll area looses the ability to get resized to a size smaller than 300x300.
Any ideas?
|
I think that you are looking at the problem the wrong way. The QScrollArea is just a widget that you put in a frame or QMainWindow. The size of the widget is controlled by the layout of the widget that contains it.
Take a look at this example from Trolltech: Image Viewer Example
|
241,274
| 241,358
|
How do I view the contents of an IXMLDOMElementPtr when building an XML file?
|
I'm using IXMLDOM in MSXML 6 to build an XML file in a C++ MFC application. Is there a way to see the contents of the xml document while it is in memory?
For example, an XPATH query is failing about halfway through creating the file. How would I view the entire contents of the xml doc?
Thanks!
|
IXMLDOMElement derives from IXMLDOMNode, and IXMLDOMNode has an xml property that you can use to get the textual representation of the XML in memory.
IXMLDOMElementPtr spElement = ...;
_bstr_t xmlContents = spElement->xml();
If you're looking for a way to see the contents of the XML in the debugger without changing existing code to add this call, that may be possible, but I'm not exactly sure where to look.
|
241,327
| 242,226
|
Remove C and C++ comments using Python?
|
I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)
I realize that I could .match() substrings with a Regex, but that doesn't solve nesting /*, or having a // inside a /* */.
Ideally, I would prefer a non-naive implementation that properly handles awkward cases.
|
I don't know if you're familiar with sed, the UNIX-based (but Windows-available) text parsing program, but I've found a sed script here which will remove C/C++ comments from a file. It's very smart; for example, it will ignore '//' and '/*' if found in a string declaration, etc. From within Python, it can be used using the following code:
import subprocess
from cStringIO import StringIO
input = StringIO(source_code) # source_code is a string with the source code.
output = StringIO()
process = subprocess.Popen(['sed', '/path/to/remccoms3.sed'],
input=input, output=output)
return_code = process.wait()
stripped_code = output.getvalue()
In this program, source_code is the variable holding the C/C++ source code, and eventually stripped_code will hold C/C++ code with the comments removed. Of course, if you have the file on disk, you could have the input and output variables be file handles pointing to those files (input in read-mode, output in write-mode). remccoms3.sed is the file from the above link, and it should be saved in a readable location on disk. sed is also available on Windows, and comes installed by default on most GNU/Linux distros and Mac OS X.
This will probably be better than a pure Python solution; no need to reinvent the wheel.
|
241,403
| 241,584
|
How do I get a list of domain user accounts with win32 api?
|
How do I get a list of domain user accounts with win32 api?
In particular, I can't get this list when the computer is not the domain controller. Instead it is a member of the domain.
|
Look into the LDAP API. This will let you query the LDAP server which will have a list of the user accounts.
|
241,516
| 241,521
|
Howto determine the size of a string give the current font in wxWidgets
|
Is there a way to determine the display length of a given string (in pixels) based on the currently selected font in (C++) wxWidgets?
For example if I print out the string "Speed:" and want to put 10 pixels between the ':' and the value about to follow, I need to know how long the "Speed:" string was. Is there a way to determine this? I can't seem to find anything in the API documentation but I may be missing something.
|
Maybe http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcgettextextent ?
Note: I'm not a wxWidgets user.
|
241,581
| 241,840
|
Boost C++ libraries for gcc-arm toolchain
|
I have no trouble building 1.35.0, as well as 1.36.0 on the timesys arm-gcc toolchain, both statically (link-static) as well as dynamically (.so, default option).
However, when I try to link a simple sample filesystem app:
#include <boost/filesystem.hpp>
#include <iostream>
namespace fs = boost::filesystem;
int main(int argc, char *argv[]) {
const char* fileName = argv[1];
std::cout << "file: " << fileName << " => " << fs::exists(fileName) << std::endl;
return 0;
}
I get the following linker error:
developer@eldp01:~/boost/test$ /opt/timesys/at91sam9263_ek/toolchain/bin/armv5l-timesys-linux-gnueabi-gcc
exists.cpp -o exists.exe -I ../boost_1_35_0/ -lboost_filesystem -lboost_system -lstdc++ -L .
/tmp/ccex3NGb.o: In function `boost::detail::atomic_decrement(int*)':
exists.cpp:(.text._ZN5boost6detail16atomic_decrementEPi[boost::detail::atomic_decrement(int*)]+0x1c):
undefined reference to `__sync_fetch_and_add_4'
/tmp/ccex3NGb.o: In function `boost::detail::atomic_increment(int*)':
exists.cpp:(.text._ZN5boost6detail16atomic_incrementEPi[boost::detail::atomic_increment(int*)]+0x1c):
undefined reference to `__sync_fetch_and_add_4'
collect2: ld returned 1 exit status
Does anyone know how I can get Boost to build for the gcc-arm toolchain?
|
You need to add in file 'boost_1_35_0/boost/config/user.hpp':
#define BOOST_SP_USE_PTHREADS
btw, you need to set the gcc tool-chain in file 'boost_1_35_0/tools/build/v2/user-config.jam' to:
using gcc
: arm
: /opt/timesys/at91sam9263_ek/toolchain/bin/armv5l-timesys-linux-gnueabi-gcc
;
This will solve the problem of linking now.
|
241,936
| 241,997
|
Gentle introduction to JIT and dynamic compilation / code generation
|
The deceptively simple foundation of dynamic code generation within a C/C++ framework has already been covered in another question. Are there any gentle introductions into topic with code examples?
My eyes are starting to bleed staring at highly intricate open source JIT compilers when my needs are much more modest.
Are there good texts on the subject that don't assume a doctorate in computer science? I'm looking for well worn patterns, things to watch out for, performance considerations, etc. Electronic or tree-based resources can be equally valuable. You can assume a working knowledge of (not just x86) assembly language.
|
Well a pattern I've used in emulators goes something like this:
typedef void (*code_ptr)();
unsigned long instruction_pointer = entry_point;
std::map<unsigned long, code_ptr> code_map;
void execute_block() {
code_ptr f;
std::map<unsigned long, void *>::iterator it = code_map.find(instruction_pointer);
if(it != code_map.end()) {
f = it->second
} else {
f = generate_code_block();
code_map[instruction_pointer] = f;
}
f();
instruction_pointer = update_instruction_pointer();
}
void execute() {
while(true) {
execute_block();
}
}
This is a simplification, but the idea is there. Basically, every time the engine is asked to execute a "basic block" (usually a everything up to next flow control op or whole function in possible), it will look it up to see if it has already been created. If so, execute it, else create it, add it and then execute.
rinse repeat :)
As for the code generation, that gets a little complicated, but the idea is to emit a proper "function" which does the work of your basic block in the context of your VM.
EDIT: note that I haven't demonstrated any optimizations either, but you asked for a "gentle introduction"
EDIT 2: I forgot to mention one of the most immediately productive speed ups you can implement with this pattern. Basically, if you never remove a block from your tree (you can work around it if you do but it is way simpler if you never do), then you can "chain" blocks together to avoid lookups. Here's the concept. Whenever you return from f() and are about to do the "update_instruction_pointer", if the block you just executed ended in either a call, unconditional jump, or didn't end in flow control at all, then you can "fixup" its ret instruction with a direct jmp to the next block it'll execute (cause it'll always be the same one) if you have already emited it. This makes it so you are executing more and more often in the VM and less and less in the "execute_block" function.
|
241,955
| 241,972
|
Checking lists and running handlers
|
I find myself writing code that looks like this a lot:
set<int> affected_items;
while (string code = GetKeyCodeFromSomewhere())
{
if (code == "some constant" || code == "some other constant") {
affected_items.insert(some_constant_id);
} else if (code == "yet another constant" || code == "the constant I didn't mention yet") {
affected_items.insert(some_other_constant_id);
} // else if etc...
}
for (set<int>::iterator it = affected_items.begin(); it != affected_items.end(); it++)
{
switch(*it)
{
case some_constant_id:
RunSomeFunction(with, these, params);
break;
case some_other_constant_id:
RunSomeOtherFunction(with, these, other, params);
break;
// etc...
}
}
The reason I end up writing this code is that I need to only run the functions in the second loop once even if I've received multiple key codes that might cause them to run.
This just doesn't seem like the best way to do it. Is there a neater way?
|
Since you don't seem to care about the actual values in the set you could replace it with setting bits in an int. You can also replace the linear time search logic with log time search logic. Here's the final code:
// Ahead of time you build a static map from your strings to bit values.
std::map< std::string, int > codesToValues;
codesToValues[ "some constant" ] = 1;
codesToValues[ "some other constant" ] = 1;
codesToValues[ "yet another constant" ] = 2;
codesToValues[ "the constant I didn't mention yet" ] = 2;
// When you want to do your work
int affected_items = 0;
while (string code = GetKeyCodeFromSomewhere())
affected_items |= codesToValues[ code ];
if( affected_items & 1 )
RunSomeFunction(with, these, params);
if( affected_items & 2 )
RunSomeOtherFunction(with, these, other, params);
// etc...
|
242,695
| 242,709
|
Long strings with newlines
|
I have seen C# code that uses the @ to tell the compiler the string has newlines in it and that it should be all in one line.
Is there something like that for C/C++?
Like if I want to put something like:
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
In a string I don't want to place it all in one line but just put it like that and have the compiler know that that is only one line.
|
C and C++ have automatic concatenation of adjacent quoted strings. This means that
const char *a = "a" "b";
and
const char *b = "ab";
will make a and b point at identical data. You can of course extend this, but it becomes troublesome when the strings contain quotes. Your example seems not to, so it might be practical then.
|
242,894
| 254,521
|
CUDA Driver API vs. CUDA runtime
|
When writing CUDA applications, you can either work at the driver level or at the runtime level as illustrated on this image (The libraries are CUFFT and CUBLAS for advanced math):
(source: tomshw.it)
I assume the tradeoff between the two are increased performance for the low-evel API but at the cost of increased complexity of code. What are the concrete differences and are there any significant things which you cannot do with the high-level API?
I am using CUDA.net for interop with C# and it is built as a copy of the driver API. This encourages writing a lot of rather complex code in C# while the C++ equivalent would be more simple using the runtime API. Is there anything to win by doing it this way? The one benefit I can see is that it is easier to integrate intelligent error handling with the rest of the C# code.
|
The CUDA runtime makes it possible to compile and link your CUDA kernels into executables. This means that you don't have to distribute cubin files with your application, or deal with loading them through the driver API. As you have noted, it is generally easier to use.
In contrast, the driver API is harder to program but provided more control over how CUDA is used. The programmer has to directly deal with initialization, module loading, etc.
Apparently more detailed device information can be queried through the driver API than through the runtime API. For instance, the free memory available on the device can be queried only through the driver API.
From the CUDA Programmer's Guide:
It is composed of two APIs:
A low-level API called the CUDA driver API,
A higher-level API called the CUDA runtime API that is implemented on top of
the CUDA driver API.
These APIs are mutually exclusive: An application should use either one or the
other.
The CUDA runtime eases device code management by providing implicit
initialization, context management, and module management. The C host code
generated by nvcc is based on the CUDA runtime (see Section 4.2.5), so
applications that link to this code must use the CUDA runtime API.
In contrast, the CUDA driver API requires more code, is harder to program and
debug, but offers a better level of control and is language-independent since it only
deals with cubin objects (see Section 4.2.5). In particular, it is more difficult to
configure and launch kernels using the CUDA driver API, since the execution
configuration and kernel parameters must be specified with explicit function calls
instead of the execution configuration syntax described in Section 4.2.3. Also, device
emulation (see Section 4.5.2.9) does not work with the CUDA driver API.
There is no noticeable performance difference between the API's. How your kernels use memory and how they are laid out on the GPU (in warps and blocks) will have a much more pronounced effect.
|
242,926
| 242,942
|
Comparison of C++ unit test frameworks
|
I know there are already a few questions regarding recommendations for C++ unit test frameworks, but all the answers did not help as they just recommend one of the frameworks but do not provide any information about a (feature) comparison.
I think the most interesting frameworks are CppUnit, Boost and the new Google testing framework. Has anybody done any comparison yet?
|
See this question for some discussion.
They recommend the articles:
Exploring the C++ Unit Testing Framework Jungle, By Noel Llopis.
And the more recent: C++ Test Unit Frameworks
I have not found an article that compares googletest to the other frameworks yet.
|
243,082
| 243,150
|
C++ casting programmatically : can it be done?
|
Let's say I have a Base class and several Derived classes. Is there any way to cast an object to one of the derived classes without the need to write something like this :
string typename = typeid(*object).name();
if(typename == "Derived1") {
Derived1 *d1 = static_cast< Derived1*>(object);
}
else if(typename == "Derived2") {
Derived2 *d2 = static_cast < Derived2*>(object);
}
...
else {
...
}
|
Don't.
Read up on polymorphism. Almost every "dynamic cast" situation is an example of polymorphism struggling to be implemented.
Whatever decision you're making in the dynamic cast has already been made. Just delegate the real work to the subclasses.
You left out the most important part of your example. The useful, polymorphic work.
string typename = typeid(*object).name();
if(typename == "Derived1") {
Derived1 *d1 = static_cast< Derived1*>(object);
d1->doSomethingUseful();
}
else if(typename == "Derived2") {
Derived2 *d2 = static_cast < Derived2*>(object);
d2->doSomethingUseful();
}
...
else {
...
}
If every subclass implements doSomethingUseful, this is all much simpler. And polymorphic.
object->doSomethingUseful();
|
243,242
| 243,829
|
Pointer-to-data-member-of-data-member
|
I had the following piece of code (simplified for this question):
struct StyleInfo
{
int width;
int height;
};
typedef int (StyleInfo::*StyleInfoMember);
void AddStyleInfoMembers(std::vector<StyleInfoMember>& members)
{
members.push_back(&StyleInfo::width);
members.push_back(&StyleInfo::height);
}
Now, we had to restructure this a bit, and we did something like this:
struct Rectangle
{
int width;
int height;
};
struct StyleInfo
{
Rectangle size;
};
typedef int (StyleInfo::*StyleInfoMember);
void AddStyleInfoMembers(std::vector<StyleInfoMember>& members)
{
members.push_back(&StyleInfo::size::width);
members.push_back(&StyleInfo::size::height);
}
If this all looks like a stupid thing to do, or if you feel there's a good opportunity to apply BOOST here for some reason, I must warn you that I really simplified it all down to the problem at hand:
error C3083: 'size': the symbol to the left of a '::' must be a type
The point I'm trying to make is that I don't know what the correct syntax is to use here. It might be that "StyleInfo" is not the correct type of take the address from to begin with, but in my project I can fix that sort of thing (there's a whole framework there). I simply don't know how to point to this member-within-a-member.
|
Remember a pointer to a member is just used like a member.
Obj x;
int y = (x.*)ptrMem;
But like normal members you can not access members of subclasses using the member access mechanism. So what you need to do is access it like you would access a member of the object (in your case via the size member).
#include <vector>
#include <iostream>
struct Rectangle
{
int width;
int height;
};
struct StyleInfo
{
Rectangle size;
};
typedef Rectangle (StyleInfo::*StyleInfoMember);
typedef int (Rectangle::*RectangleMember);
typedef std::pair<StyleInfoMember,RectangleMember> Access;
void AddStyleInfoMembers(std::vector<Access>& members)
{
members.push_back(std::make_pair(&StyleInfo::size,&Rectangle::width));
members.push_back(std::make_pair(&StyleInfo::size,&Rectangle::height));
}
int main()
{
std::vector<Access> data;
AddStyleInfoMembers(data);
StyleInfo obj;
obj.size.width = 10;
std::cout << obj.*(data[0].first).*(data[0].second) << std::endl;
}
This is not something I would recommend doing!
An alternative (that I recommend even less) is to find the byte offset from the beginning of the class and then just add this to the objects address. Obviously this will involve a lot of casting backwards and forwards so this looks even worse then the above.
|
243,269
| 243,304
|
How do I get a "busy wheel" on Windows Mobile 6?
|
Windows Mobile pops up a "busy wheel" - a rotating colour disk - when things are happening . I can't find in the documentation how this is done - can someone point me in the right direction?
We have a situation where we need to prompt the user to say we're doing stuff for a while, but we don't know how long it will take. So we can't do a progress bar, hence the proposal to use this busy wheel.
|
Use SetCursor/LoadCursor/ShowCursor APIs, like this:
SetCursor(LoadCursor(NULL, IDC_WAIT));
// my code
ShowCursor(FALSE);
|
243,322
| 1,141,107
|
Save State of a Direct3D Device
|
State should include at least the following:
All settings set via
SetStreamResource()
Indices
I have a class whose Draw() function will call SetStreamResource, set Indices and eventually call DrawIndexedPrimitive(). I would like to restore the device state before Draw() returns.
I am looking for something along the lines of GDI's SaveDC()/RestoreDC().
|
State blocks are the mechanism provided by the API to save and restore chunks of device state. I cover the details of state blocks in Chapter 3. Direct3D Devices from my book The Direct3D Graphics Pipeline. You can download the PDF for that chapter from the link above.
|
243,365
| 243,548
|
creating objects dynamically in C++
|
I was just reading this thread and it occurred to me that there is one seemingly-valid use of that pattern the OP is asking about. I know I've used it before to implement dynamic creation of objects. As far as I know, there is no better solution in C++, but I was wondering if any gurus out there know of a better way. Generally, I run into this situation when I need to create one of several subclasses of an object based one something unknown at compile time (such as based on a config file). I use the object polymorphically once it is created.
There's another related situation when you're using a message-passing scheme (usually over TCP/IP) where each message is an object. I like to implement that pattern as letting each message serialize itself into some serialization stream interface, which works well and is fairly clean on the sending end, but on the receiver, I always find myself examining a header on the message to determine the type, then constructing an appropriate message object using the pattern from the linked article, then having it deserialize itself from the stream. Sometimes I implement it so that the construction and deserialization happen at the same time as part of the constructor, which seems more RAII, but that's small consolation for the mess of if/else statements figuring out the type.
Any better solutions out there? If you're going to suggest a 3rd party library, it should be free (and ideally open source) and I'd appreciate it if you could explain how the library accomplishes this feat.
|
I think what you are asking is how to keep the object creation code with the objects themselves.
This is usually what I do. It assumes that there is some key that gives you a type (int tag, string, etc). I make a class that has a map of key to factory functions, and a registration function that takes a key and factory function and adds it to the map. There is also a create function that takes a key, looks it up in the map, calls the factory function, and returns the created object. As an example, take a int key, and a stream that contains the rest of the info to build the objects. I haven't tested, or even compiled, this code, but it should give you an idea.
class Factory
{
public:
typedef Object*(*Func)(istream& is);
static void register(int key, Func f) {m[key] = f;}
Object* create(key, istream& is) {return m[key](is);}
private:
std::map<key, func> m;
}
Then in each class derived from subobject, the register() method is called with the appropriate key and factory method.
To create the object, you just need something like this:
while(cin)
{
int key;
is >> key;
Object* obj = Factory::Create(key, is);
// do something with objects
}
|
243,381
| 243,562
|
Anything I should know before converting a large C++ program from VS2005 to VS2008?
|
Is there anything I should know before converting a large C++ program from VS2005 to VS2008?
|
I'm working on this very problem right now.
Running WinMerge to see what I've changed...
OK, here is what I had to fix in an huge Win32/MFC client application:
Some MFC functions have become virtual (which were not in the past - CWnd::GetMenu for one, if I recall correctly). Also something related to our legacy mouse wheel support (before Windows had built-in mouse wheel support) somehow broke (I just removed the feature, so I never really figured out why that broke).
Some ATL methods (or method params) have changed to const that were not originally (screwed up my overrides).
The Platform SDK is newer - be careful if you're setting the windows SDK version #defines correctly (we were not in all places - which was dumb). You may now be building with newer versions (Vista/2008) of Win32 structures. This didn't work so great on my XP box.
STDMETHOD now includes __declspec(nothrow) which is 100% right - except this found some problems in our code. Some interface that was written like it would be exposed through COM, but never was, threw exceptions.
The IDE has a bug where disabled breakpoints don't show the hollow circle in the margin if you don't have the break points set to highlight the whole line (which I think is the default for VC++, maybe?).
Most of these issues were due to subtle mistakes in our code or aggressive overloading of MFC/ATL libraries. Since everyone else's code is perfect, you should be fine ;)
|
243,383
| 243,447
|
Why can't C++ be parsed with a LR(1) parser?
|
I was reading about parsers and parser generators and found this statement in wikipedia's LR parsing -page:
Many programming languages can be parsed using some variation of an LR parser. One notable exception is C++.
Why is it so? What particular property of C++ causes it to be impossible to parse with LR parsers?
Using google, I only found that C can be perfectly parsed with LR(1) but C++ requires LR(∞).
|
There is an interesting thread on Lambda the Ultimate that discusses the LALR grammar for C++.
It includes a link to a PhD thesis that includes a discussion of C++ parsing, which states that:
"C++ grammar is ambiguous,
context-dependent and potentially
requires infinite lookahead to resolve
some ambiguities".
It goes on to give a number of examples (see page 147 of the pdf).
The example is:
int(x), y, *const z;
meaning
int x;
int y;
int *const z;
Compare to:
int(x), y, new int;
meaning
(int(x)), (y), (new int));
(a comma-separated expression).
The two token sequences have the same initial subsequence but different parse trees, which depend on the last element. There can be arbitrarily many tokens before the disambiguating one.
|
243,568
| 243,841
|
CTimeSpan.GetDays() and daylight savings time
|
I found in a bug in an old C++ MFC program we have that calculates an offset (in days) for a given date from a fixed base date. We were seeing results that were off by one for some reason, and I tracked it down to where the original programmer had used the CTimeSpan.GetDays() method. According to the documentation:
Note that Daylight Savings Time can cause GetDays to return a potentially surprising result. For example, when DST is in effect, GetDays reports the number of days between April 1 and May 1 as 29, not 30, because one day in April is shortened by an hour and therefore does not count as a complete day.
My proposed fix is to use (obj.GetTotalHours()+1)/24 instead. I think that would cover all the issues since this is a batch job that runs at about the same time every day, but I thought I'd ask the smart people here before implementing it if there might be a better way.
This is just a side issue, but I'm also curious how this would be handled if the program could be run at any time.
|
Your fix works fine to get the number of whole 24-hour periods between two times - as long as the events occur at the same time each day. Otherwise that "+1" in the expression could lead to an off-by-one error.
Sometimes you don't care what time of day the event occured, you just want to know which day. In that case, you need to zero out the hours, minutes, and seconds, then use your formula:
CTime startDay(start.GetYear(), start.GetMonth(), start.GetDay(), 0, 0, 0);
CTime finishDay(finish.GetYear(), finish.GetMonth(), finish.GetDay(), 0, 0, 0);
int days = ((finishDay - startDay).GetTotalHours() + 1) / 24;
|
243,696
| 244,584
|
Correctly over-loading a stringbuf to replace cout in a MATLAB mex file
|
MathWorks currently doesn't allow you to use cout from a mex file when the MATLAB desktop is open because they have redirected stdout. Their current workaround is providing a function, mexPrintf, that they request you use instead. After googling around a bit, I think that it's possible to extend the std::stringbuf class to do what I need. Here's what I have so far. Is this robust enough, or are there other methods I need to overload or a better way to do this? (Looking for portability in a general UNIX environment and the ability to use std::cout as normal if this code is not linked against a mex executable)
class mstream : public stringbuf {
public:
virtual streamsize xsputn(const char *s, std::streamsize n)
{
mexPrintf("*s",s,n);
return basic_streambuf<char, std::char_traits<char>>::xsputn(s,n);
}
};
mstream mout;
outbuf = cout.rdbuf(mout.rdbuf());
|
You don't really want to overload std::stringbuf, you want to overload std::streambuf or std::basic_streambuf (if you want to support multiple character types), also you need to override the overflow method as well.
But I also think you need to rethink your solution to your problem.
cout is just an ostream, so if all classes / functions takes an ostream then you can pass in anything you like. e.g. cout, ofstream, etc
If that's too hard then I would create my own version of cout, maybe called mycout that can be defined at either compiler time or runtime time (depending on what you want to do).
A simple solution may be:
#include <streambuf>
#include <ostream>
class mystream : public std::streambuf
{
public:
mystream() {}
protected:
virtual int_type overflow(int_type c)
{
if(c != EOF)
{
char z = c;
mexPrintf("%c",c);
return EOF;
}
return c;
}
virtual std::streamsize xsputn(const char* s, std::streamsize num)
{
mexPrintf("*s",s,n);
return num;
}
};
class myostream : public std::ostream
{
protected:
mystream buf;
public:
myostream() : std::ostream(&buf) {}
};
myostream mycout;
And the cout version could just be:
typedef std::cout mycout;
A runtime version is a bit more work but easily doable.
|
243,802
| 243,827
|
Memory allocation on Windows C code
|
I'd like to know which method is recommended on Windows C programming: using malloc or the Win32 HeapAlloc (maybe VirtualAlloc?) function.
I've read the MSDN Memory Management Functions article and the MSDN articles regarding malloc and HeapAlloc, but they do not say which one should be used and in what situations.
|
Stick with malloc unless you have a compelling reason to use something different. It will be implemented underneath in terms of the OS memory allocation primitives, but there is no real advantage in diving down to that layer yourself.
A few API calls I believe need a memory block allocated from a Windows heap, but you will know when you come across them.
Or if you want to do something more advanced, like use shared memory, or need to control the permissions on the memory pages directly then you will need to look at the Windows API calls like VirtualAlloc.
|
244,316
| 244,344
|
Reader/Writer Locks in C++
|
I'm looking for a good reader/writer lock in C++. We have a use case of a single infrequent writer and many frequent readers and would like to optimize for this. Preferable I would like a cross-platform solution, however a Windows only one would be acceptable.
|
Newer versions of boost::thread have read/write locks (1.35.0 and later, apparently the previous versions did not work correctly).
They have the names shared_lock, unique_lock, and upgrade_lock and operate on a shared_mutex.
|
244,453
| 244,583
|
Best documentation for Boost:asio?
|
The documentation available on the boost website is... limited.
From what I've been able to read, the general consensus is that it is simply difficult to find good documentation on the boost::asio library.
Is this really the case? If so, why?
Notes:
I have already found the (non-boost) Asio website - and the documentation looks to be identical to that on the boost website.
I know that Boost::asio is new! I'm looking for solutions not excuses.
Edit:
There is a proposal to add a networking library to standard library for TR2 written by the author of Boost:asio (Christopher Kohlhoff). While it isn't documentation for boost:asio, it does use it as a base for the TR2 proposal. Since the author put more effort into this document, I have found it to be somewhat helpful, if not as a reference, then at least as an overview.
|
First, I've been using Boost.Asio for quite a while already -- and I share your concern. To address your question:
There really is very scarce documentation about Boost.Asio aside from the introduction and tutorial. I am not the author, but this is mostly because there are just too many things to document for something as low-level as an Asynchronous IO Library.
The examples give more away than the tutorials do. If you don't mind spending a little time looking at the different examples, I would think they should suffice to get you started. If you want to run away with it, then the reference documentation should help you a lot.
Ask around in the Boost Users and Boost Developers mailing list if you're really stuck or looking for specific guidance. I'm pretty sure a lot of people will be willing to address your concerns on the mailing lists.
There are efforts (not part of Boost.Asio) to expose a lot of the functionality and possible alternative use cases. This at best is scattered around the web in blogs and other forms of non-packaged documentation.
One thing that is unclear and which will really need close coordination with the author and developers of the Boost.Asio library would be as far as extending and customizing it for a specific platform or adding specific new functionality. This should be improved though but the good thing is it's looking like Asio will be a reference implementation for a standard library technical report (for an asynchronous IO library in the STL) in the future.
|
244,487
| 244,507
|
How do I sort a CArray of a user defined type?
|
Is there a built-in way to sort a CArray in C++?
|
std::sort() should work:
CArray<int> arrayOfInts;
arrayOfInts.Add(7);
arrayOfInts.Add(114);
arrayOfInts.Add(3);
std::sort(arrayOfInts.GetData(), arrayOfInts.GetData()+arrayOfInts.GetSize());
This uses the pointer to the first element in the array as the start iterator, and the pointer to one past the last element as the last iterator (should never be dereferenced anyway, so all's well). You could also pass in a custom predicate if the array contained more interesting data:
struct Foo
{
int val;
double priority;
};
bool FooPred(const Foo& first, const Foo& second)
{
if ( first.val < second.val )
return true;
if ( first.val > second.val )
return false;
return first.priority < second.priority;
}
//...
CArray<Foo> bar;
std::sort(bar.GetData(), bar.GetData()+bar.GetSize(), FooPred);
Oh - and don't use CArray.
|
244,492
| 244,552
|
MFC Panel and window handle
|
Is there something like a panel that I can use in a MFC application. This is to overlay the default window in MFC (a dialog application). Then to paint the panel black and paint some random stuff on top of it. Something like a view port.
is there a better option than this to achieve the same effect ?
|
Sure. It's called a window! Create a class that derives from CWnd and overrides OnPaint().
In your dialog's OnInitInstance(), instantiate a CMyWnd object and call it's Create() member. Of course, make sure the lifetime of your CMyWnd object is the same as the dialog's object lifetime window. iow, make it a member of you CMyDialog class.
Not very complicated but obviously an area where MFC shows why it doesn't fall in the RAD tools category.
|
244,646
| 244,676
|
Get elapsed time in Qt
|
I'm looking for the equivalent in Qt to GetTickCount()
Something that will allow me to measure the time it takes for a segment of code to run as in:
uint start = GetTickCount();
// do something..
uint timeItTook = GetTickCount() - start;
any suggestions?
|
How about QTime? Depending on your platform it should have 1 millisecond accuracy. Code would look something like this:
QTime myTimer;
myTimer.start();
// do something..
int nMilliseconds = myTimer.elapsed();
|
244,784
| 245,261
|
YAML serialization library for C++?
|
YAML seems like a great format for configuration files & data binding persistent objects in human-readable form...
Is there a C++ library that handles YAML? Does Boost::Serialization have plans for a YAML option?
EDIT: I would prefer an OO library.
|
A quick search gave me this: yaml-cpp
|
244,845
| 244,859
|
Unit testing Visitor pattern architecture
|
I've introduced visitors as one of core architecture ideas in one of my apps. I have several visitors that operate on a same stuff. Now, how should I test it? Some tests I'm thinking of are a bit larger then a unit test should be (integration test? whatever) but I still wanna do it. How would you test code like the C++ sample from wiki art on Visitor Pattern
|
make a test visitor object and make it visit things.... test that it visited the right things.
|
245,475
| 245,483
|
How do I create a generic std::vector destructor?
|
Having a vector containing pointers to objects then using the clear function doesn't call the destructors for the objects in the vector. I made a function to do this manually but I don't know how to make this a generic function for any kind of objects that might be in the vector.
void buttonVectorCleanup(vector<Button *> dVector){
Button* tmpClass;
for(int i = 0; i < (int)dVector.size(); i++){
tmpClass = dVector[i];
delete tmpClass;
}
}
This is the function I have that works fine for a specific type of object in the vector but I'd like a single function that could take any kind of vector with object pointers.
|
The best thing to do is use smart pointers, such as from Boost. Then the objects will be deleted automatically.
Or you can make a template function
template <class T>
void vectorCleanup(vector<T *>& dVector){
T* tmpClass;
for(vector<T*>::size_type i = 0; i < dVector.size(); i++){
tmpClass = dVector[i];
delete tmpClass;
}
}
|
245,619
| 245,625
|
Howto initialise char array style string in constructor
|
I have a class which I'm serialising to send over a unix socket and it has to have a string which I've stored as a char array. Can I initialise it in the constructor differently to how I've done it here?
typedef struct SerialFunctionStatus_t {
SerialFunctionStatus_t()
: serial_rx_count(0), serial_tx_count(0), socket_rx_count(0), socket_tx_count(0)
{ port[0] = '\0'; }
uint32_t serial_rx_count;
uint32_t serial_tx_count;
uint32_t socket_rx_count;
uint32_t socket_tx_count;
char port[20];
} SerialFunctionStatus_t;
|
Put port() in the initializer list. This causes port to be 'value initialized' (12.6.2), which for arrays of builtins means zero initialized (8.5).
|
245,628
| 245,636
|
C++ Binary Search Tree Recursive search function
|
template <class T>
bool BST<T>::search(const T& x, int& len) const
{
return search(BT<T>::root, x);
}
template <class T>
bool BST<T>::search(struct Node<T>*& root, const T& x)
{
if (root == NULL)
return false;
else
{
if (root->data == x)
return true;
else if(root->data < x)
search(root->left, x);
else
search(root->right, x);
}
}
So this is my search function for my BST class with a T node. x is the data being searched for within the tree, len is just the amount of nodes it has to travel to come up with the matching node if it exists. I have not implented that yet, I'm just incrementally developing my assignment. I'm calling it by doing this:
if(t.search(v[1], len) == true)
cout << endl << "true";
v is just a vector I had to create to compare it to, and so this is just supplying it with an int. The error I'm getting:
BST.h: In member function âbool BST<T>::search(const T&, int&) const [with T = int]â:
prog5.cc:24: instantiated from here
BST.h:78: error: no matching function for call to âBST<int>::search(Node<int>* const&, const int&) constâ
BST.h:76: note: candidates are: bool BST<T>::search(const T&, int&) const [with T = int]
BST.h:83: note: bool BST<T>::search(Node<T>*&, const T&) [with T = int]
So I'm not sure what I'm doing wrong or where I'm doing wrong.
|
Okay, bool BST<T>::search(struct Node<T>*& root, const T& x) should probably have const after it like so: bool BST<T>::search(struct Node<T>*& root, const T& x) const. Basically, you've called a non-const function from a const function and this is a no-no.
BTW, this looks suspect to me "struct Node<T>*&"... I'd probably drop the & and work with Node<T>*... but maybe you need that because of the struct?
Also, this is C++, there is no reason to leave Node as a struct... needing to have struct in the parameter definition just looks bad, IMHO. Why not make Node a class?
|
245,742
| 245,761
|
Examples of good gotos in C or C++
|
In this thread, we look at examples of good uses of goto in C or C++. It's inspired by an answer which people voted up because they thought I was joking.
Summary (label changed from original to make intent even clearer):
infinite_loop:
// code goes here
goto infinite_loop;
Why it's better than the alternatives:
It's specific. goto is the
language construct which causes an
unconditional branch. Alternatives
depend on using structures
supporting conditional branches,
with a degenerate always-true
condition.
The label documents the intent
without extra comments.
The reader doesn't have to scan the
intervening code for early breaks
(although it's still possible for an
unprincipled hacker to simulate
continue with an early goto).
Rules:
Pretend that the gotophobes didn't
win. It's understood that the above
can't be used in real code because
it goes against established idiom.
Assume that we have all heard of
'Goto considered harmful' and know
that goto can be used to write
spaghetti code.
If you disagree with an example,
criticize it on technical merit
alone ('Because people don't like
goto' is not a technical reason).
Let's see if we can talk about this like grown ups.
Edit
This question seems finished now. It generated some high quality answers. Thanks to everyone,
especially those who took my little loop example seriously. Most skeptics were concerned
by the lack of block scope. As @quinmars pointed out in a comment, you can always put braces around the
loop body. I note in passing that for(;;) and while(true) don't give you the braces
for free either (and omitting them can cause vexing bugs). Anyway, I won't waste any more
of your brain power on this trifle - I can live with the harmless and idiomatic for(;;) and while(true) (just as well if I want to keep my job).
Considering the other responses, I see that many people view goto as something you always
have to rewrite in another way. Of course you can avoid a goto by introducing a loop,
an extra flag, a stack of nested ifs, or whatever, but why not consider whether goto is
perhaps the best tool for the job? Put another way, how much ugliness are people prepared to endure to avoid using a built-in language feature for its intended purpose? My take is that
even adding a flag is too high a price to pay. I like my variables to represent things in
the problem or solution domains. 'Solely to avoid a goto' doesn't cut it.
I'll accept the first answer which gave the C pattern for branching to a cleanup block. IMO, this makes the strongest case for a goto of all the posted answers, certainly
if you measure it by the contortions a hater has to go through to avoid it.
|
Heres one trick I've heard of people using. I've never seen it in the wild though. And it only applies to C because C++ has RAII to do this more idiomatically.
void foo()
{
if (!doA())
goto exit;
if (!doB())
goto cleanupA;
if (!doC())
goto cleanupB;
/* everything has succeeded */
return;
cleanupB:
undoB();
cleanupA:
undoA();
exit:
return;
}
|
245,838
| 245,928
|
Binary Search Tree Deletion (Inorder Pred method) C++
|
Ok so I thought it was fixed, but I'm getting totally inconsistent results.
I rewrote it kind of from scratch to start fresh and here are my results. I get no errors, no crashing, it just doesn't remove them. It just totally messes up the tree and gives me a ton more leaves, and mixes everything up. Not sure where else to go
template <class T>
void BST<T>::remove(struct Node<T>*& root, const T& x)
{
Node<T>* ptr = root;
bool found = false;
Node<T>* parent;
while (ptr != NULL && !found)
{
if (x < ptr->data)
{
parent = ptr;
ptr = ptr->left;
}
else if (x > ptr->data)
{
parent = ptr;
ptr = ptr->right;
}
else
found = true;
}
if (found == false)
return;
else
{
if(ptr->left != NULL && ptr->right != NULL)
{
Node<T>* inOrderPtr = ptr->left;
parent = ptr;
while (inOrderPtr->right != NULL)
{
parent = inOrderPtr;
inOrderPtr = inOrderPtr->right;
}
ptr->data = inOrderPtr->data;
ptr = inOrderPtr;
}
Node<T>* subPtr = ptr->left;
if (subPtr == NULL)
subPtr = ptr->right;
else if (parent->left == ptr)
parent->left = subPtr;
else
parent->right = subPtr;
delete ptr;
}
|
Are each T found in the tree unique? It looks like they are from your code...
It looks like this should work:
In the else case deleting the root node:
Node<T> *tmp_r = root->left;
Node<T> *parent = root;
while (tmp_r->right != NULL)
{
parent = tmp_r;
tmp_r = tmp_r->right;
}
Node<T> *tmp_l = tmp_r;
while (tmp_l->left != NULL)
tmp_l = tmp_l->left;
tmp_l->left = root->left;
tmp_r->right = root->right;
parent->right = NULL;
parent = root;
root = tmp_r;
delete parent;
|
246,071
| 246,083
|
Basic example of a scriptable plugin for Firefox in C++ with VS2005/8
|
My experience to write a plugin for Firefox is below zero. Is someone out there who could point me to sample code on how to get this accomplished in C++ with VS2005/8?
What I need to do with JavaScript in the hosting html page is something like this:
var obj = document.getElementById("MyFFPlugin");
var value = obj.CalculateValue;
// Work with calculated value
|
The SDK has basic samples on how to write mozzila plugins which can be downloaded here: http://mxr.mozilla.org/seamonkey/source/modules/plugin/tools/sdk/
Here is the official mozilla plugin site http://www.mozilla.org/projects/plugins/
Hope it helps.
|
246,077
| 246,084
|
How are Windows VK_ constants declared?
|
For example VK_LEFT, VK_DELETE, VK_ESCAPE, VK_RETURN, etc. How and where are they declared? Are they constants, #defines, or something else? Where do they come from?
If possible, please provide a file name/path where they are declared. Or some other info as specific as possible.
|
These are declared using #define in the file winuser.h in the Platform SDK. In my installation of Visual Studio 2008, the full path is
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WinUser.h
|
246,293
| 246,323
|
c++ dynamic_cast error handling
|
Is there any good practice related to dynamic_cast error handling (except not using it when you don't have to)? I'm wondering how should I go about NULL and bad_cast it can throw.
Should I check for both? And if I catch bad_cast or detect NULL I probably can't recover anyway...
For now, I'm using assert to check if dynamic_cast returned not NULL value. Would you accept this solution on a code review?
|
If the dynamic_cast should succeed, it would be good practice to use boost::polymorphic_downcast instead, which goes a little something like this:
assert(dynamic_cast<T*>(o) == static_cast<T*>(o));
return static_cast<T*>(o);
This way, you will detect errors in the debug build while at the same time avoiding the runtime overhead in a release build.
If you suspect the cast might fail and you want to detect it, use dynamic_cast and cast to a reference type. This cast will throw bad_cast in case of error, and will take down your program. (This is good if, as you say, you are not going to recover anyway)
T& t = dynamic_cast<T&>(o);
t.func(); //< Use t here, no extra check required
Use dynamic_cast to a pointer type only if the 0-pointer makes sense in the context. You might want to use it in an if like this:
if (T* t = dynamic_cast<T*>(o)) {
t->func(); //< Use t here, it is valid
}
// consider having an else-clause
With this last option you need to make sure that the execution path makes sense if the dynamic_cast returns 0.
To answer your question directly: I would prefer one of the two first alternatives I have given to having an explicit assert in the code :)
|
246,407
| 248,673
|
Disable sleep mode in Windows Mobile 6
|
Does anyone know how could I programatically disable/enable sleep mode on Windows Mobile?
Thanks!
|
If you want your program to not be put to sleep while it's running, the best way is to create a KeepAlive type function that calls SystemIdleTimerReset, SHIdleTimerReset and simulates a key touch. Then you need to call it a lot, basically everywhere.
#include <windows.h>
#include <commctrl.h>
extern "C"
{
void WINAPI SHIdleTimerReset();
};
void KeepAlive()
{
static DWORD LastCallTime = 0;
DWORD TickCount = GetTickCount();
if ((TickCount - LastCallTime) > 1000 || TickCount < LastCallTime) // watch for wraparound
{
SystemIdleTimerReset();
SHIdleTimerReset();
keybd_event(VK_LBUTTON, 0, KEYEVENTF_SILENT, 0);
keybd_event(VK_LBUTTON, 0, KEYEVENTF_KEYUP | KEYEVENTF_SILENT, 0);
LastCallTime = TickCount;
}
}
This method only works when the user starts the application manually.
If your application is started by a notification (i.e. while the device is suspended), then you need to do more or else your application will be suspended after a very short period of time until the user powers the device out of suspended mode. To handle this you need to put the device into unattended power mode.
if(!::PowerPolicyNotify (PPN_UNATTENDEDMODE, TRUE))
{
// handle error
}
// do long running process
if(!::PowerPolicyNotify (PPN_UNATTENDEDMODE, FALSE))
{
// handle error
}
During unattended mode use, you still need to call the KeepAlive a lot, you can use a separate thread that sleeps for x milliseconds and calls the keep alive funcation.
Please note that unattended mode does not bring it out of sleep mode, it puts the device in a weird half-awake state.
So if you start a unattended mode while the device in suspended mode, it will not wake up the screen or anything. All unattended mode does is stop WM from suspending your application. Also the other problem is that it does not work on all devices, some devices power management is not very good and it will suspend you anyway no matter what you do.
|
246,445
| 246,457
|
create std::string from char* in a safe way
|
I have a char* p, which points to a \0-terminated string. How do I create a C++ string from it in an exception-safe way?
Here is an unsafe version:
string foo()
{
char *p = get_string();
string str( p );
free( p );
return str;
}
An obvious solution would be to try-catch - any easier ways?
|
You can use shared_ptr from C++11 or Boost:
string
foo()
{
shared_ptr<char> p(get_string(), &free);
string str(p.get());
return str;
}
This uses a very specific feature of shared_ptr not available in auto_ptr or anything else, namely the ability to specify a custom deleter; in this case, I'm using free as the deleter.
|
246,564
| 246,568
|
What is the lifetime of a static variable in a C++ function?
|
If a variable is declared as static in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called?
void foo()
{
static string plonk = "When will I die?";
}
|
The lifetime of function static variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.
Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account.
Example
struct emitter {
string str;
emitter(const string& s) : str(s) { cout << "Created " << str << endl; }
~emitter() { cout << "Destroyed " << str << endl; }
};
void foo(bool skip_first)
{
if (!skip_first)
static emitter a("in if");
static emitter b("in foo");
}
int main(int argc, char*[])
{
foo(argc != 2);
if (argc == 3)
foo(false);
}
Output:
C:>sample.exe
Created in foo
Destroyed in foo
C:>sample.exe 1
Created in if
Created in foo
Destroyed in foo
Destroyed in if
C:>sample.exe 1 2
Created in foo
Created in if
Destroyed in if
Destroyed in foo
[0] Since C++98[2] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as Roddy mentions.
[1] C++98 section 3.6.3.1 [basic.start.term]
[2] In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.
|
246,683
| 246,715
|
CFile Error On Windows Ce
|
I am using Windows CE 4.2 and MS Embedded VC++ 4.0. The following code gives me the error Access to [file name] was denied., and it creates the file but does not write anything to it.
CString tmp;
tmp.Format(_T("%s%d"), mFileName, ++ctr);
TRY
{
mFile.Open(tmp, CFile::modeCreate);
mFile.Write(&data[ctr%2], 1);
mFile.Close();
}
CATCH (CException, e)
{
TCHAR szCause[255];
CString strFormatted;
e->GetErrorMessage(szCause, 255);
strFormatted += szCause;
AfxMessageBox(strFormatted);
}
END_CATCH
Interestingly, using CreateFile works fine:
CString tmp;
tmp.Format(_T("%s%d"), mFileName, ++ctr);
hFile = CreateFile(tmp, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL /*| FILE_FLAG_WRITE_THROUGH*/, 0);
WriteFile(hFile, &(data[ctr%2]), 1, &bytesWritten, NULL);
CloseHandle(hFile);
Why could this be? Can I even use CFile on WinCE? I'm just starting out with embedded development.
|
I've not used MFC on Windows CE, but on ordinary Windows, the usual idiom is
mFile.Open(tmp, CFile::modeCreate|CFile::modeWrite);
i.e. try adding "CFile::modeWrite" to the constructor. The MSDN documentation suggests that this is necessary:
You can combine options listed below by using the bitwise-OR (|) operator. One access permission and one share option are required; the modeCreate and modeNoInherit modes are optional.
This implies to me that one of "modeRead" or "modeWrite" must always be supplied.
|
246,806
| 246,811
|
I want to convert std::string into a const wchar_t *
|
Is there any method?
My computer is AMD64.
::std::string str;
BOOL loadU(const wchar_t* lpszPathName, int flag = 0);
When I used:
loadU(&str);
the VS2005 compiler says:
Error 7 error C2664:: cannot convert parameter 1 from 'std::string *__w64 ' to 'const wchar_t *'
How can I do it?
|
If you have a std::wstring object, you can call c_str() on it to get a wchar_t*:
std::wstring name( L"Steve Nash" );
const wchar_t* szName = name.c_str();
Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in MultiByteToWideChar routine. That will give you an LPWSTR, which is equivalent to wchar_t*.
|
247,093
| 248,604
|
Edit Registry Values
|
I want to change the registry values on the pocketPC. I ran the following code:
if(enabled)
{
dwData = 120;
}
if(RegSetValueEx(HKEY_LOCAL_MACHINE, _T("System\\CurrentControlSet\\Control\\Power\\Timeouts\\BattSuspendTimeout"), 0, REG_DWORD, (LPBYTE)&dwData, sizeof(DWORD)))
{
return FALSE;
}
but it doesn't shange the registry entry. Does anyone know how to set registry key values with c++?
Thanks!
|
There are a two problems with what you are doing:
1: RegSetValueEx does not take a path, only a valuename. So you need to open the key path first.
e.g.
HKEY key;
if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Control\\Power\\Timeouts", 0, 0, &key))
{
if(RegSetValueEx(key, _T("BattSuspendTimeout"), 0, REG_DWORD, (LPBYTE)&dwData, sizeof(DWORD)))
{
RegCloseKey(key);
return FALSE;
}
RegCloseKey(key);
}
2: That area of the registry requires Privileged code signing to work on all Windows Mobile devices. You can get away with it on most current touch-screen windows mobile devices if the user says "yes" to the unknown publisher question when the application is first run or installed. If you get a "Access Denied" error on the set, then you really need to be Privileged code signed for the set to work.
|
247,538
| 248,891
|
Which standard c++ classes cannot be reimplemented in c++?
|
I was looking through the plans for C++0x and came upon std::initializer_list for implementing initializer lists in user classes. This class could not be implemented in C++
without using itself, or else using some "compiler magic". If it could, it wouldn't be needed since whatever technique you used to implement initializer_list could be used to implement initializer lists in your own class.
What other classes require some form of "compiler magic" to work? Which classes are in the Standard Library that could not be implemented by a third-party library?
Edit: Maybe instead of implemented, I should say instantiated. It's more the fact that this class is so directly linked with a language feature (you can't use initializer lists without initializer_list).
A comparison with C# might clear up what I'm wondering about: IEnumerable and IDisposable are actually hard-coded into language features. I had always assumed C++ was free of this, since Stroustrup tried to make everything implementable in libraries. So, are there any other classes / types that are inextricably bound to a language feature.
|
std::type_info is a simple class, although populating it requires typeinfo: a compiler construct.
Likewise, exceptions are normal objects, but throwing exceptions requires compiler magic (where are the exceptions allocated?).
The question, to me, is "how close can we get to std::initializer_lists without compiler magic?"
Looking at wikipedia, std::initializer_list<typename T> can be initialized by something that looks a lot like an array literal. Let's try giving our std::initializer_list<typename T> a conversion constructor that takes an array (i.e., a constructor that takes a single argument of T[]):
namespace std {
template<typename T> class initializer_list {
T internal_array[];
public:
initializer_list(T other_array[]) : internal_array(other_array) { };
// ... other methods needed to actually access internal_array
}
}
Likewise, a class that uses a std::initializer_list does so by declaring a constructor that takes a single std::initializer_list argument -- a.k.a. a conversion constructor:
struct my_class {
...
my_class(std::initializer_list<int>) ...
}
So the line:
my_class m = {1, 2, 3};
Causes the compiler to think: "I need to call a constructor for my_class; my_class has a constructor that takes a std::initializer_list<int>; I have an int[] literal; I can convert an int[] to a std::initializer_list<int>; and I can pass that to the my_class constructor" (please read to the end of the answer before telling me that C++ doesn't allow two implicit user-defined conversions to be chained).
So how close is this? First, I'm missing a few features/restrictions of initializer lists. One thing I don't enforce is that initializer lists can only be constructed with array literals, while my initializer_list would also accept an already-created array:
int arry[] = {1, 2, 3};
my_class = arry;
Additionally, I didn't bother messing with rvalue references.
Finally, this class only works as the new standard says it should if the compiler implicitly chains two user-defined conversions together. This is specifically prohibited under normal cases, so the example still needs compiler magic. But I would argue that (1) the class itself is a normal class, and (2) the magic involved (enforcing the "array literal" initialization syntax and allowing two user-defined conversions to be implicitly chained) is less than it seems at first glance.
|
247,639
| 250,159
|
What is the Performance, Safety, and Alignment of a Data member hidden in an embedded char array in a C++ Class?
|
I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are:
Pool. This is a class which allocates memory efficiently, for some definition of 'efficient'. Pool is guaranteed to return a chunk of memory that is aligned for the requested size.
Obj_list. This class stores homogeneous collections of objects. Once the number of objects exceeds a certain threshold, it changes its internal representation from a list to a tree. The size of Obj_list is one pointer (8 bytes on a 64-bit platform). Its populated store will of course exceed that.
Aggregate. This class represents a very common object in the system. Its history goes back to the early 32-bit workstation era, and it was 'optimized' (in that same 32-bit era) to use as little space as possible as a result. Aggregates can be empty, or manage an arbitrary number of objects.
In this example, Aggregate items are always allocated from Pools, so they are always aligned. The only occurrences of Obj_list in this example are the 'hidden' members in Aggregate objects, and therefore they are always allocated using placement new. Here are the support classes:
class Pool
{
public:
Pool();
virtual ~Pool();
void *allocate(size_t size);
static Pool *default_pool(); // returns a global pool
};
class Obj_list
{
public:
inline void *operator new(size_t s, void * p) { return p; }
Obj_list(const Args *args);
// when constructed, Obj_list will allocate representation_p, which
// can take up much more space.
~Obj_list();
private:
Obj_list_store *representation_p;
};
And here is Aggregate. Note that member declaration member_list_store_d:
// Aggregate is derived from Lesser, which is twelve bytes in size
class Aggregate : public Lesser
{
public:
inline void *operator new(size_t s) {
return Pool::default_pool->allocate(s);
}
inline void *operator new(size_t s, Pool *h) {
return h->allocate(s);
}
public:
Aggregate(const Args *args = NULL);
virtual ~Aggregate() {};
inline const Obj_list *member_list_store_p() const;
protected:
char member_list_store_d[sizeof(Obj_list)];
};
It is that data member that I'm most concerned about. Here is the pseudocode for initialization and access:
Aggregate::Aggregate(const Args *args)
{
if (args) {
new (static_cast<void *>(member_list_store_d)) Obj_list(args);
}
else {
zero_out(member_list_store_d);
}
}
inline const Obj_list *Aggregate::member_list_store_p() const
{
return initialized(member_list_store_d) ? (Obj_list *) &member_list_store_d : 0;
}
You may be tempted to suggest that we replace the char array with a pointer to the Obj_list type, initialized to NULL or an instance of the class. This gives the proper semantics, but just shifts the memory cost around. If memory were still at a premium (and it might be, this is an EDA database representation), replacing the char array with a pointer to an Obj_list would cost one more pointer in the case when Aggregate objects do have members.
Besides that, I don't really want to get distracted from the main question here, which is alignment. I think the above construct is problematic, but can't really find more in the standard than some vague discussion of the alignment behavior of the 'system/library' new.
So, does the above construct do anything more than cause an occasional pipe stall?
Edit: I realize that there are ways to replace the approach using the embedded char array. So did the original architects. They discarded them because memory was at a premium. Now, if I have a reason to touch that code, I'll probably change it.
However, my question, about the alignment issues inherent in this approach, is what I hope people will address. Thanks!
|
Ok - had a chance to read it properly. You have an alignment problem, and invoke undefined behaviour when you access the char array as an Obj_list. Most likely your platform will do one of three things: let you get away with it, let you get away with it at a runtime penalty or occasionally crash with a bus error.
Your portable options to fix this are:
allocate the storage with malloc or
a global allocation function, but
you think this is too
expensive.
as Arkadiy says, make your buffer an Obj_list member:
Obj_list list;
but you now don't want to pay the cost of construction. You could mitigate this by providing an inline do-nothing constructor to be used only to create this instance - as posted the default constructor would do. If you follow this route, strongly consider invoking the dtor
list.~Obj_list();
before doing a placement new into this storage.
Otherwise, I think you are left with non portable options: either rely on your platform's tolerance of misaligned accesses, or else use any nonportable options your compiler gives you.
Disclaimer: It's entirely possible I'm missing a trick with unions or some such. It's an unusual problem.
|
247,703
| 247,721
|
Getting the name of the current method in c++
|
Is there a (standardized) way to get the name of the current method using c++?
Using GNU GCC you can do this by using the macro __FUNCTION__ and __PRETTY_FUNCTION__ (surrounded by 2 underscores), however, this is of course non portable. Is there a way to do this in standard c++ or a way to make it portable?
|
The __func__ identifier is part of the C99 standard and is in the C++0x draft.
The identifier __func__ is implicitly declared by the compiler as if the following were at the very start of each function body:
static const char __func__[] = "function-name";
where function-name is an implementation-defined string automatically provided by the compiler.
Until support for those standards is available (or more widely available) you're stuck with compiler-specific gunk.
|
247,738
| 247,764
|
Is it safe to assume that STL vector storage is always contiguous?
|
If you have an STL vector which has been resized, is it safe to take the address of element 0 and assume the rest of the vector will follow in memory?
e.g.
vector<char> vc(100);
// do some stuff with vc
vc.resize(200);
char* p = &vc[0];
// do stuff with *p
|
Yes, that is a valid assumption (*).
From the C++03 standard (23.2.4.1):
The elements of a vector are stored
contiguously, meaning that if v is a
vector where T is some
type other than bool, then it obeys
the identity &v[n] == &v[0] + n for
all 0 <= n < v.size().
(*) ... but watch out for the array being reallocated (invalidating any pointers and iterators) after adding elements to it.
|
247,818
| 247,859
|
stl::multimap - how do i get groups of data?
|
Multimap essentially has groups of data sorted by the key. I want a method by which I could access these individual groups and get their aggregate values.
For example, in a std::multimap< string, int > I store
{"Group1", 1},
{"Group1", 2},
{"Group1", 3},
{"Group2", 10},
{"Group2", 11},
{"Group2", 12}
Having stored these values, I should be able to iterate this multimap and get the aggregate values of each "group". Problem is there aren't any functions defined in STL to access MultiMaps in such a way. I could use lower_bound, upper_bound to manually iterate the multimap and total the group's contents, but I am hoping there could be better ways already defined in STL ? Can anyone propose a solution as to how I could get the aggregate values for a group in the above example.
|
pair<Iter, Iter> range = my_multimap.equal_range("Group1");
int total = accumulate(range.first, range.second, 0);
Is one way.
Edit:
If you don't know the group you are looking for, and are just going through each group, getting the next group's range can be done like so:
template <typename Pair>
struct Less : public std::binary_function<Pair, Pair, bool>
{
bool operator()(const Pair &x, const Pair &y) const
{
return x.first < y.first;
}
};
Iter first = mmap.begin();
Iter last = adjacent_find(first, mmap.end(), Less<MultimapType::value_type>());
|
248,104
| 248,119
|
How Do I Use Eclipse to Debug a C++ Program on Linux?
|
I don't use Eclipse as an IDE, and have no interest in doing so. However, I do like its source-level debugging.
Is there any way I can use it to debug a C++ Linux app without going through the ritual of creating a project? (In effect, can I just use it like a frontend to gdb?)
If not, what are the steps I need to follow to create a project that I can use to just debug an existing C++ program that is built using Makefiles or other tools (SCons, CMake, etc.). I don't want to be able to "develop" in Eclipse; all I need to do is debug.
|
Take a look at this question. Create a C/C++-project, use your project's source directory as project directory, select to use the external builder, and change "make" to whatever tool you want.
The tricky part is to get the indexer to work correctly and find all your header files.
EDIT: CMake 2.6.x has support for generating CDT project files, which might be a more straightforward solution.
|
248,134
| 248,153
|
How can I experiment with garbage collection?
|
I'm interested in how garbage collection works. I've read up on how some work such as mark-and-sweep, stop-and-copy, generational GC, etc... I'd like to experiment with implementing some of these and comparing their behaviors. What's a good way to get started experimenting with my own? Ideally something in C, Java or Python (although the last two are themselves garbage-collected so it seems it'd be hard to use them...)
|
Never played with it myself, but the one that always gets mentioned for use with C/C++ is Hans Boehm's.
|
248,182
| 249,476
|
My C++ ActiveMQ client can send messages, but not receive messages
|
I have the ActiveMQ-CPP 2.2.1 Visual Studio 2005 project compiling and running. In the console window, it shows the messages are being sent, though they're not being received. I can both send and receive messages with ActiveMQ-CPP 2.0.1, but not 2.2.1. I'm new to ActiveMQ and don't even know where to begin troubleshooting. Any thoughts/suggestions/good place to start would be a great help.
It if helps, I'm using the ActiveMQ 5.1.0 binary.
Thanks in advance!
|
I'd recommend posting this to the user forum to get the ActiveMQ C++ developers to help. Maybe even raise a JIRA with a test case
|
248,400
| 248,479
|
Finding composite numbers
|
I have a range of random numbers. The range is actually determined by the user but it will be up to 1000 integers. They are placed in this:
vector<int> n
and the values are inserted like this:
srand(1);
for (i = 0; i < n; i++)
v[i] = rand() % n;
I'm creating a separate function to find all the non-prime values. Here is what I have now, but I know it's completely wrong as I get both prime and composite in the series.
void sieve(vector<int> v, int n)
{
int i,j;
for(i = 2; i <= n; i++)
{
cout << i << " % ";
for(j = 0; j <= n; j++)
{
if(i % v[j] == 0)
cout << v[j] << endl;
}
}
}
This method typically worked when I just had a series of numbers from 0-1000, but it doesn't seem to be working now when I have numbers out of order and duplicates. Is there a better method to find non-prime numbers in a vector? I'm tempted to just create another vector, fill it with n numbers and just find the non-primes that way, but would that be inefficient?
Okay, since the range is from 0-1000 I am wondering if it's easier to just create vector with 0-n sorted, and then using a sieve to find the primes, is this getting any closer?
void sieve(vector<int> v, BST<int> t, int n)
{
vector<int> v_nonPrime(n);
int i,j;
for(i = 2; i < n; i++)
v_nonPrime[i] = i;
for(i = 2; i < n; i++)
{
for(j = i + 1; j < n; j++)
{
if(v_nonPrime[i] % j == 0)
cout << v_nonPrime[i] << endl;
}
}
}
|
In this code:
if(i % v[j] == 0)
cout << v[j] << endl;
You are testing your index to see if it is divisible by v[j]. I think you meant to do it the other way around, i.e.:
if(v[j] % i == 0)
Right now, you are printing random divisors of i. You are not printing out random numbers which are known not to be prime. Also, you will have duplicates in your output, perhaps that is ok.
|
248,421
| 251,634
|
Thread safety of Matlab engine API
|
I have discovered through trial and error that the MATLAB engine function is not completely thread safe.
Does anyone know the rules?
Discovered through trial and error:
On Windows, the connection to MATLAB is via COM, so the COM Apartment threading rules apply. All calls must occur in the same thread, but multiple connections can occur in multiple threads as long as each connection is isolated.
From the answers below, it seems that this is not the case on UNIX, where calls can be made from multiple threads as long as the calls are made serially.
|
When I first started using the engine, I didn't run across any documentation on thread safety, so I assumed that it was not thread-safe.
I use a C++ class to synchronize access to an engine instance. For more parallel processing designs, I instantiate multiple instances of the engine class.
(edit) I'm using MATLAB R14 on Solaris. I open the engine using the 'engOpen' call, and close it using 'engClose'. My platform does not crash when the Close is called by a different thread than the one that called Open.
|
248,617
| 248,643
|
c++ adding method to class defined in header file
|
I'm wondering if it is possible to add methods in main program to an existing class defined in header file.
For example:
There is class CFun defined in file CFun.hpp, but in our party.cpp we want to add a method void hello() {cout << "hello" << endl;};without editing CFun.hpp
Obviously (unfortunately) construction:
#include "CFun.hpp"
class CFun
{
public:
void hello() {cout << "hello" << endl;};
};
doesn't work returning an error Multiple declaration for 'CFun'
Is it possible to make it work without class inheritance?
|
No, but you could add a method that takes a reference/pointer to a CFun class - you just won't have access to private data:
void Hello(CFun &fun)
{
cout << "hello" << endl;
}
This is probably the best you'll be able to do. As pointed out by litb - this function has to be in the same namespace as CFun. Fortunately, namespaces, unlike classes, can be added to in multiple places.
|
248,693
| 248,698
|
Double Negation in C++
|
I just came onto a project with a pretty huge code base.
I'm mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic.
if (!!variable && (!!api.lookup("some-string"))) {
do_some_stuff();
}
I know these guys are intelligent programmers, it's obvious they aren't doing this by accident.
I'm no seasoned C++ expert, my only guess at why they are doing this is that they want to make absolutely positive that the value being evaluated is the actual boolean representation. So they negate it, then negate that again to get it back to its actual boolean value.
Is this correct, or am I missing something?
|
It's a trick to convert to bool.
|
249,009
| 249,014
|
Do you use curly braces for additional scoping?
|
I mean other than using it when required for functions, classes, if, while, switch, try-catch.
I didn't know that it could be done like this until I saw this SO question.
In the above link, Eli mentioned that "They use it to fold up their code in logical sections that don't fall into a function, class, loop, etc. that would usually be folded up."
What other uses are there besides those mentioned?
Is it a good idea to use curly braces to limit the scope of your variables and expand the scope only if required (working on a "need-to-access" basis)? Or is it actually silly?
How about using scopes just so that you can use the same variable names in different scopes but in the same bigger scope? Or is it a better practise to reuse the same variable (if you want to use the same variable name) and save on deallocating and allocating (I think some compilers can optimise on this?)? Or is it better to use different variable names altogether?
|
I do if I am using a resource which I want to free at a specific time eg:
void myfunction()
{
{
// Open serial port
SerialPort port("COM1", 9600);
port.doTransfer(data);
} // Serial port gets closed here.
for(int i = 0; i < data.size(); i++)
doProcessData(data[i]);
etc...
}
|
249,062
| 249,131
|
Easy to use SNMP client library for c++?
|
What's an easy to use SNMP client library for c++?
|
Probably the best choice is net-snmp. Note that the library has "C" linkage but will work just fine with C++.
|
249,415
| 249,463
|
Single-threading two processes
|
I have two C++ processes (A and B), executing under Windows, where one launches the other. I would like to effectively single-thread their execution. For example:
Start process A
A creates B
A suspends
B executes some fixed set of operations
B suspends and A is resumed
A executes some fixed set of operations
A suspends and B is resumed
(Repeat 4 - 7)
Which Windows synchronization and IPC services would be best to implement this type of behavior?
|
Events would work in this case:
A creates an event an starts Process B
A waits for the event to be signaled
B also creates an event, does it's first item, then signals A's event (which either has a well-known name or the handle can be passed to B when it starts or using some other mechanism
B waits on its event
when A resumes from waiting on its event, it does its work, signals B's event and waits on its own
so on...
Just be sure you have error handling so each process can resume and do whatever is necessary if the other one hangs or terminates unexpectedly. Timeouts can handle the hang situation, and waiting on the other process's handle (using WaitForMultipleObjects() along with both the process and event handle) can determine if/when the other process terminates.
|
249,500
| 249,525
|
Looking for a better way than virtual inheritance in C++
|
OK, I have a somewhat complicated system in C++. In a nutshell, I need to add a method to a third party abstract base class. The third party also provides a ton of derived classes that also need the new functionality.
I'm using a library that provides a standard Shape interface, as well as some common shapes.
class Shape
{
public:
Shape(position);
virtual ~Shape();
virtual position GetPosition() const;
virtual void SetPosition(position);
virtual double GetPerimeter() const = 0;
private: ...
};
class Square : public Shape
{
public:
Square(position, side_length);
...
};
class Circle, Rectangle, Hexagon, etc
Now, here's my problem. I want the Shape class to also include a GetArea() function. So it seems like I should just do a:
class ImprovedShape : public virtual Shape
{
virtual double GetArea() const = 0;
};
class ImprovedSquare : public Square, public ImprovedShape
{
...
}
And then I go and make an ImprovedSquare that inherits from ImprovedShape and Square. Well, as you can see, I have now created the dreaded diamond inheritance problem. This would easily be fixed if the third party library used virtual inheritance for their Square, Circle, etc. However, getting them to do that isn't a reasonable option.
So, what do you do when you need to add a little functionality to an interface defined in a library? Is there a good answer?
Thanks!
|
We had a very similar problem in a project and we solved it by just NOT deriving ImprovedShape from Shape. If you need Shape functionality in ImprovedShape you can dynamic_cast, knowing that your cast will always work. And the rest is just like in your example.
|
249,581
| 249,981
|
Explain Facade pattern with c++ example?
|
I have checked with the wikipedia article, and it seems like it is missing the c++ version of a code example. I am not able to fully appreciate the Facade pattern without this, can you please help explain it to me using C++?
|
Facade pattern: provides a unified - simplified interface to a complex subsystem or set of interfaces. It provides a higher level interface simultaneously decoupling the client from the complex subsystem.
An example to help you understand .. a cab driver. You tell the cab driver 'Take me to PointX' (unified simplified high-level interface) who then begins on a sequence of actions (turns the key, changes gears, presses the accelerator, etc...) to perform the task. He abstracts away the complexity of underlying subsystems (gearbox, engine, etc.) so that you don't have to worry about them.
The driver also decouples you from the actual vehicle used... you do not directly interface with the car. You could potentially give him a Merc but your interface to the Driver would still be TakeMeTo( X ).. you're not tied down to any specific model/make of the car.
In a real world example, you'll find facades where you interface with third party components or libraries. You don't want your code to depend on a specific vendor, so you introduce a facade interface to decouple. Also you'll simplify this interface, e.g. your facade interface would have a method called SendData( string ) but internally the implementation may call n methods on m sub-packages in a specific order to get the task done. This is what the diagram on the wikipedia page shows.
e.g. Translating an example to C++ and keeping it tiny
sResource = LWCPPSimple::get("http://www.perl.org")
Here the fictitious Library For WWW in C++ is a facade that unifies protocol, network and parsing aspects of the problem so that I can concentrate on my primary focus of fetching the resource. The get method hides/encapsulates/keeps-in-one-place the complexity (and in some cases ugliness) of HTTP, FTP and other varied protocols, request-response, connection management, etc. Also if tomorrow the creators of LWCPPSimple find a way to make get() to be twice as fast, I get the performance benefits for free. My client code doesn't have to change.
|
249,607
| 254,069
|
VC++ linker errors on std::exception::_Raise and std::exception::exception
|
I am using Visual C++ 2005 Express Edition and get the following linker errors:
19>mylib1.lib(mylibsource1.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::exception::_Raise(void)const " (__imp_?_Raise@exception@std@@QBEXXZ) referenced in function "protected: static void __cdecl std::vector<class mytype,class std::allocator<class mytype> >::_Xlen(void)" (?_Xlen@?$vector@Vmytype@@V?$allocator@Vmytype@@@std@@@std@@KAXXZ)
19>mylib2.lib(mylibsource2.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::exception::_Raise(void)const " (__imp_?_Raise@exception@std@@QBEXXZ)
19>mylib1.lib(mylibsource1.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall std::exception::exception(char const *,int)" (__imp_??0exception@std@@QAE@PBDH@Z) referenced in function "public: __thiscall std::logic_error::logic_error(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (??0logic_error@std@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@1@@Z)
19>mylib2.lib(mylibsource2.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: __thiscall std::exception::exception(char const *,int)" (__imp_??0exception@std@@QAE@PBDH@Z)
I turned off exceptions in generated code, and I am using before including the vector header file:
#define _HAS_EXCEPTIONS 0
A few Google results turned up some stuff, but no "aha!" solutions that worked for me.
EDIT:
As noted "_HAS_EXCEPTIONS 0" doesn't turn off exceptions, per se. What it does is, at least in the vector header file, is call _Raise on an exception object instead of calling the C++ "throw". In my case, it can't link to the exception object's _Raise function since I am not including the correct library. What that library is, though, is not obvious.
|
Adding this line:
#define _STATIC_CPPLIB
before including the vector header seems to do the trick.
|
250,096
| 250,745
|
How to read arbitrary number of values using std::copy?
|
I'm trying to code opposite action to this:
std::ostream outs; // properly initialized of course
std::set<int> my_set; // ditto
outs << my_set.size();
std::copy( my_set.begin(), my_set.end(), std::ostream_iterator<int>( outs ) );
it should be something like this:
std::istream ins;
std::set<int>::size_type size;
ins >> size;
std::copy( std::istream_iterator<int>( ins ), std::istream_iterator<int>( ins ) ???, std::inserter( my_set, my_set.end() ) );
But I'm stuck with the 'end' iterator -- input interators can't use std::advance and neither I can use two streams with the same source...
Is there any elegant way how to solve this? Of course I can use for loop, but maybe there's something nicer :)
|
You could derive from the istream_iterator<T>.
Though using Daemin generator method is another option, though I would generate directly into the set rather than use an intermediate vector.
#include <set>
#include <iterator>
#include <algorithm>
#include <iostream>
template<typename T>
struct CountIter: public std::istream_iterator<T>
{
CountIter(size_t c)
:std::istream_iterator<T>()
,count(c)
{}
CountIter(std::istream& str)
:std::istream_iterator<T>(str)
,count(0)
{}
bool operator!=(CountIter const& rhs) const
{
return (count != rhs.count) && (dynamic_cast<std::istream_iterator<T> const&>(*this) != rhs);
}
T operator*()
{
++count;
return std::istream_iterator<T>::operator*();
}
private:
size_t count;
};
int main()
{
std::set<int> x;
//std::copy(std::istream_iterator<int>(std::cin),std::istream_iterator<int>(),std::inserter(x,x.end()));
std::copy(
CountIter<int>(std::cin),
CountIter<int>(5),
std::inserter(x,x.end())
);
}
|
250,394
| 250,701
|
Does anyone know of any C/C++/C# code libraries that do audio synthesizer emulation?
|
I'm trying to write a software synthesizer that recreates the sounds made by classic synthesizers like the Moog and the DX7. Does anyone know of any code resources for something like this? Thanks.
|
There are an awful lot of C/C++ libraries out there, most no longer updated. There's not much for C#, but I have seen a couple. I haven't really used any of them in anger, so I can't give any recommendations.
I would start with Harmony Central and see if you find anything of use there.
Alternatively, a search for analog synthesis on sourceforge.net has plenty of results.
|
251,007
| 251,066
|
How difficult is it to turn a "Java School" programmer into a C or C++ programmer?
|
My company, a C++ house, is always looking to hire recent grads. However due to the Java Schools phenomenon, we typically end up interviewing strong Java programmers with maybe a minute smattering of C++. Often the C++ classes don't really prepare students for working in C++. Nevertheless, often these are bright kids, eager to learn and do their best.
Every interview, I struggle with this fundamental question:
How hard is it to turn a "Java School" programmer into a C or C++ programmer? Has your company had experience turning the stereotypical "Java Schools" programmer into a strong C++ programmer? Is it worth the effort?
One of the reasons I struggle with this is not just due to a C or C++ vs Java language difference, it's the fundamental skills that come with learning C or C++ that I think often get lost at the Java School. These include data structures, computational complexity, manual memory management, really everything Joel Spolsky says here.
Often, as far as I can tell, a student will have some of those fundamental skills (be able to answer a few questions), but I'll still have this large part of my mind that's extremely skeptical with how well someone can learn these skills without getting their hands dirty in some C or C++. Maybe I need to be disabused of this stereotype. Am I just being unfair?
Anyway whats your experience with turning the "Java School" programmer into a C or C++ programmer?
|
Well, if they don't understand data structures and algorithmic complexity, they aren't going to be much good at serious Java programming, so I don't see that the language is an issue here.
They won't understand pointers, but good C++ programming typically doesn't use pointers in complicated ways. (There are exceptions, but since I don't know what your company does I can't tell whether they'd apply.) After all, you probably don't want your developers writing their own linked lists rather than using std::list.
They won't understand manual memory management, but that's a lot easier in C++ than it used to be. In modern C++, doing your own memory management has become harder, due to the potential of exceptions, so you want to practice RAII with pretty much everything (using auto_ptr, boost::shared_ptr, whatever).
If I were running things, I'd hire them if they looked good. I'd be aware that there might be problems (C++ is a more demanding language than Java, after all), and have some sort of idea how to deal with them.
There's no reason to avoid hiring people out of college just because they don't have the exact skills you want. The smart ones will learn, and you probably don't want to hire the ones who aren't smart.
|
251,159
| 251,223
|
What is the use of const overloading in C++?
|
In C++, a function's signature depends partly on whether or not it's const. This means that a class can have two member functions with identical signatures except that one is const and the other is not. If you have a class like this, then the compiler will decide which function to call based on the object you call it on: if it's a const instance of the class, the const version of the function will be called; if the object isn't const, the other version will be called.
In what circumstances might you want to take advantage of this feature?
|
This really only makes sense when the member function returns a pointer or a reference to a data member of your class (or a member of a member, or a member of a member of a member, ... etc.). Generally returning non-const pointers or references to data members is frowned upon, but sometimes it is reasonable, or simply very convenient (e.g. [] operator). In such cases, you provide a const and a non-const versions of the getter. This way the decision on whether or not the object can be modified rests with the function using it, which has a choice of declaring it const or non-const.
|
251,248
| 251,267
|
How can I get the SID of the current Windows account?
|
I am looking for an easy way to get the SID for the current Windows user account. I know I can do it through WMI, but I don't want to go that route.
Apologies to everybody that answered in C# for not specifying it's C++. :-)
|
In Win32, call GetTokenInformation, passing a token handle and the TokenUser constant. It will fill in a TOKEN_USER structure for you. One of the elements in there is the user's SID. It's a BLOB (binary), but you can turn it into a string by using ConvertSidToStringSid.
To get hold of the current token handle, use OpenThreadToken or OpenProcessToken.
If you prefer ATL, it has the CAccessToken class, which has all sorts of interesting things in it.
.NET has the Thread.CurrentPrinciple property, which returns an IPrincipal reference. You can get the SID:
IPrincipal principal = Thread.CurrentPrincipal;
WindowsIdentity identity = principal.Identity as WindowsIdentity;
if (identity != null)
Console.WriteLine(identity.User);
Also in .NET, you can use WindowsIdentity.GetCurrent(), which returns the current user ID:
WindowsIdentity identity = WindowsIdentity.GetCurrent();
if (identity != null)
Console.WriteLine(identity.User);
|
251,325
| 251,335
|
Passing a Class Object to a function (probably by pointer not reference) C++
|
So let's say I have two different functions. One is a part of the BST class, one is just a helper function that will call on that Class function. I will list them out here.
sieve(BST<T>* t, int n);
this function is called like this: sieve(t,n) the object is called BST t;
I'm going to be using the class remove function within the sieve function to remove specific objects. I'm not sure what my prototype for this basic function should look like? Doing this:
sieve(BST<int> t, int n)
What happens here is everything compiles just fine, but when t.remove function is called I see no actual results. I'm assuming because it's just creating a copy or a whole other t object instead of passing the one from my main() function.
If I call the remove function (t.remove(value)) in my main function where the original object was created it removes everything properly. Once I start doing it through my sieve function I see no change when I re print it out from my main function. So my main function looks something like this:
int main ()
{
int n,
i,
len;
BST<int> t;
cin >> n;
vector<int> v(n);
srand(1);
for (i = 0; i < n; i++)
v[i] = rand() % n;
for (i = 0; i < n; i++)
t.insert(v[i]);
print_stat(t);
t.inOrder(print_data);
sieve(v,t,n);
print_stat(t);
t.inOrder(print_data);
return 0;
}
So my results end up being the same, even though my debug statements within the functions show it's actually deleting something. I'm guessing where I'm going wrong is how I am passing the t object onto the function.
|
sieve(BST<int>& t, int n)
The & specifies passing by reference rather than value. :-)
|
251,403
| 252,106
|
how do you make a heterogeneous boost::map?
|
I want to have a map that has a homogeneous key type but heterogeneous data types.
I want to be able to do something like (pseudo-code):
boost::map<std::string, magic_goes_here> m;
m.add<int>("a", 2);
m.add<std::string>("b", "black sheep");
int i = m.get<int>("a");
int j = m.get<int>("b"); // error!
I could have a pointer to a base class as the data type but would rather not.
I've never used boost before but have looked at the fusion library but can't figure out what I need to do.
Thanks for your help.
|
#include <map>
#include <string>
#include <iostream>
#include <boost/any.hpp>
int main()
{
try
{
std::map<std::string, boost::any> m;
m["a"] = 2;
m["b"] = static_cast<char const *>("black sheep");
int i = boost::any_cast<int>(m["a"]);
std::cout << "I(" << i << ")\n";
int j = boost::any_cast<int>(m["b"]); // throws exception
std::cout << "J(" << j << ")\n";
}
catch(...)
{
std::cout << "Exception\n";
}
}
|
251,432
| 251,446
|
typedefs for templated classes?
|
Is it possible to typedef long types that use templates? For example:
template <typename myfloat_t>
class LongClassName
{
// ...
};
template <typename myfloat_t>
typedef std::vector< boost::shared_ptr< LongClassName<myfloat_t> > > LongCollection;
LongCollection<float> m_foo;
This doesn't work, but is there a way to achieve a similar effect? I just want to avoid having to type and read a type definition that covers almost the full width of my editor window.
|
No, that isn't possible currently. It will be made possible in C++0X AFAIK.
The best I can think of is
template<typename T> struct LongCollection {
typedef std::vector< boost::shared_ptr< LongClassName<T> > > type;
};
LongCollection<float>::type m_foo;
|
252,297
| 252,302
|
Why is RegOpenKeyEx() returning error code 2 on Vista 64bit?
|
I was making the following call:
result = RegOpenKeyEx(key, s, 0, KEY_READ, &key);
(C++, Visual Studio 5, Vista 64bit).
It is failing with error code 2 ("File not found") even though "regedit" shows that the key exists. This code has always worked on 32bit XP. Why is it "file not found" when it clearly is there?
|
I discovered that I could solve my problem using the flag: KEY_WOW64_64KEY , as in:
result = RegOpenKeyEx(key, s, 0, KEY_READ|KEY_WOW64_64KEY, &key);
For a full explanation: 32-bit and 64-bit Application Data in the Registry
|
252,492
| 252,516
|
What's the latest version of Boost compatible with VC++6?
|
What is the latest version of the Boost library that is compatible with Microsoft Visual C++ 6? And can you provide a link to download it directly?
The Downloads link at http://www.boost.org only gives a download for version 1.36.0, and the documentation for that version lists Visual C++ 7.1 as the lowest version of Microsoft compiler tested. Do they purge out downloads for older versions?
|
Boost 1.34.1 has been tested with vc6. The old versions are still available.
|
252,515
| 252,518
|
Why do we even need the "delete[]" operator?
|
This is a question that's been nagging me for some time. I always thought that C++ should have been designed so that the delete operator (without brackets) works even with the new[] operator.
In my opinion, writing this:
int* p = new int;
should be equivalent to allocating an array of 1 element:
int* p = new int[1];
If this was true, the delete operator could always be deleting arrays, and we wouldn't need the delete[] operator.
Is there any reason why the delete[] operator was introduced in C++? The only reason I can think of is that allocating arrays has a small memory footprint (you have to store the array size somewhere), so that distinguishing delete vs delete[] was a small memory optimization.
|
It's so that the destructors of the individual elements will be called. Yes, for arrays of PODs, there isn't much of a difference, but in C++, you can have arrays of objects with non-trivial destructors.
Now, your question is, why not make new and delete behave like new[] and delete[] and get rid of new[] and delete[]? I would go back Stroustrup's "Design and Evolution" book where he said that if you don't use C++ features, you shouldn't have to pay for them (at run time at least). The way it stands now, a new or delete will behave as efficiently as malloc and free. If delete had the delete[] meaning, there would be some extra overhead at run time (as James Curran pointed out).
|
252,671
| 252,678
|
Is auto ever useful in C/C++?
|
Has anyone ever seen the storage class auto explicitly used in C/C++? If so, in what situation?
|
auto is never useful in current C/C++ because all variables are implicitly auto. It is useful in C++0x, where it can replace the type declaration entirely - if you have a variable with an initial assignment, 'auto' will just make it the type of that assignment value, as in the comments.
|
252,819
| 253,009
|
C++ : how to link against libA.so and not libA-X.Y.Z.so
|
I have a library A, that I develop. When I deploy it on a machine, the corresponding libA.so and libA-X.Y.Z.so are put in /usr/lib (X.Y.Z being the version number).
Now I develop a library B, which uses A. When I link B, I use the flag -lA. Then "ldd libB.so" gives me :
(...)
libA-X.Y.Z.so => /usr/lib/libA-X.Y.Z.so
(...)
My problem is that when I release a new version of A (X.Y.ZZ), I also have to release a new version of B. Otherwise, someone installing the latest A won't be able to install B which will be looking for the version X.Y.Z which doesn't exist.
How do I solve this problem ? How can I tell B to look for libA.so and not libA-X.Y.Z.so ? Or is it wrong to do so ? even unsafe ?
Update 1 : library A (that I inherited from someone else) uses autotools.
Update 2 : when I build library A, I can see : "-Wl,-soname -Wl,libA-0.6.1.so". If I understand properly that means that we are forcing the soname to be libA-0.6.1.so. Is that right ? Now my problem is that I have no clue how to modify this behaviour in a project which uses autotools. I googled for a while but can't find any useful information. Should I modify configure.in or a Makefile.am ?
|
When you create libA.so, pass the -soname option to the linker (if you linking through gcc, use -Wl,-soname). Then, when B gets linked, the linker refers to A through its soname, not through its filename. On the target system, make sure you have a link from the soname to the real file. See
http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html
|
252,951
| 252,996
|
Finding invocations of a certain function in a c++ file using python
|
I need to find all occurrences of a function call in a C++ file using python, and extract the arguments for each call.
I'm playing with the pygccxml package, and extracting the arguments given a string with the function call is extremely easy:
from pygccxml.declarations import call_invocation
def test_is_call_invocation(call):
if call_invocation.is_call_invocation(call):
print call_invocation.name(call)
for arg in call_invocation.args(call):
print " ",arg
else:
print "not a function invocation"
What I couldn't find is a way of getting the calls parsing a file:
from pygccxml import parser
from pygccxml import declarations
decls = parser.parse( ['main.cpp'] )
# ...
Is there a way to find the calls to a certain function using the pygccxml package?
Or maybe that package is an overkill for what I'm trying to do :) and there's a much simpler way? Finding the function calls with a regular expression is, I'm afraid, much trickier than it might look at a first sight...
|
XML-GCC can't do that, because it only reports the data types (and function signatures). It ignores the function bodies. To see that, create a.cc:
void foo()
{}
void bar()
{
foo();
}
and then run gccxml a.cc -fxml=a.xml. Look at the generated a.xml, to see that the only mentioning of foo (or its id) is in the declaration of foo.
An alternative might be available in codeviz (http://www.csn.ul.ie/~mel/projects/codeviz/). It consists of a patch to gcc 3.4.6 that generates call dependency information - plus some perl scripts that generate graphviz input; the latter you can safely ignore.
As yet another alternative (which doesn't need gcc modifications) you could copy the approach from egypt (http://www.gson.org/egypt/); this parses GCC RTL dumps. It should work with any recent GCC, however, it might be that you don't get calls to inline functions.
In any case, with these approaches, you won't get "calls" to macros, but that might be actually the better choice.
|
252,962
| 253,128
|
Read 64 bit integer string from file
|
We have a file that has a 64 bit integer as a string in it. How do we scanf() or otherwise parse this numeric string into an unsigned 64 bit integer type in C++ ?
We are aware of things like %lld etc., but a lot of ways to do this parse seem to break compiles under different compilers and stdlibs. The code should compile under gcc and the Microsoft C++ compiler (of course full compliance with standards would be a plus)
|
GCC has long long, as will compilers for C++0x. MSVC++ doesn't (yet), but does have its __int64 you can use.
#if (__cplusplus > 199711L) || defined(__GNUG__)
typedef unsigned long long uint_64_t;
#elif defined(_MSC_VER) || defined(__BORLANDC__)
typedef unsigned __int64 uint_64_t;
#else
#error "Please define uint_64_t"
#endif
uint_64_t foo;
std::fstream fstm( "file.txt" );
fstm >> foo;
|
253,099
| 2,123,260
|
How do I print the elements of a C++ vector in GDB?
|
I want to examine the contents of a std::vector in GDB, how do I do it? Let's say it's a std::vector<int> for the sake of simplicity.
|
To view vector std::vector myVector contents, just type in GDB:
(gdb) print myVector
This will produce an output similar to:
$1 = std::vector of length 3, capacity 4 = {10, 20, 30}
To achieve above, you need to have gdb 7 (I tested it on gdb 7.01) and some python pretty-printer. Installation process of these is described on gdb wiki.
What is more, after installing above, this works well with Eclipse C++ debugger GUI (and any other IDE using GDB, as I think).
|
253,157
| 253,173
|
How to downsize std::vector?
|
Is there a way to resize a std::vector to lower capacity when I no longer need previously reserved space?
|
Effective STL, by Scott Meyers, Item 17: Use the swap trick to trim excess capacity.
vector<Person>(persons).swap(persons);
After that, persons is "shrunk to fit".
This relies on the fact that vector's copy constructor allocates only as much as memory as needed for the elements being copied.
|
253,212
| 253,223
|
What are assertions? and why would you use them?
|
How are assertions done in c++? Example code is appreciated.
|
Asserts are a way of explicitly checking the assumptions that your code makes, which helps you track down lots of bugs by narrowing down what the possible problems could be. They are typically only evaluated in a special "debug" build of your application, so they won't slow down the final release version.
Let's say you wrote a function that took a pointer as an argument. There's a good chance that your code will assume that the pointer is non-NULL, so why not explicitly check that with an assertion? Here's how:
#include <assert.h>
void function(int* pointer_arg)
{
assert(pointer_arg != NULL);
...
}
An important thing to note is that the expressions you assert must never have side effects, since they won't be present in the release build. So never do something like this:
assert(a++ == 5);
Some people also like to add little messages into their assertions to help give them meaning. Since a string always evaulates to true, you could write this:
assert((a == 5) && "a has the wrong value!!");
|
253,284
| 253,318
|
How do you inherit from a class in a different header file?
|
I am having dependency troubles. I have two classes: Graphic and Image. Each one has its own .cpp and .h files. I am declaring them as the following:
Graphic.h:
#include "Image.h"
class Image;
class Graphic {
...
};
Image.h:
#include "Graphic.h"
class Graphic;
class Image : public Graphic {
...
};
When I try to compile, I get the following error:
Image.h:12: error: expected class-name before ‘{’ token
If I remove the forward declaration of Graphic from Image.h I get the following error:
Image.h:13: error: invalid use of incomplete type ‘struct Graphic’
Image.h:10: error: forward declaration of ‘struct Graphic’
|
This worked for me:
Image.h:
#ifndef IMAGE_H
#define IMAGE_H
#include "Graphic.h"
class Image : public Graphic {
};
#endif
Graphic.h:
#ifndef GRAPHIC_H
#define GRAPHIC_H
#include "Image.h"
class Graphic {
};
#endif
The following code compiles with no error:
#include "Graphic.h"
int main()
{
return 0;
}
|
253,469
| 505,535
|
How do I display a tooltip for a CMFCRibbonButton in the status bar?
|
I have a CMFCRibbonStatusBar in my mainframe to which I add a CMFCRibbonButtonsGroup which again has a CMFCRibbonButton. This button has the same ID as a menu entry.
Creating the button is done as follows:
CMFCRibbonButtonsGroup* pBGroup = new CMFCRibbonButtonsGroup();
CMFCToolBarImages images;
images.SetImageSize(CSize(32, 16)); // Non-square bitmaps
if(images.Load(IDB_STATUSBAR_IMAGES))
{
pBGroup->SetImages(&images, NULL, NULL);
}
m_pStatusButton = new CMFCRibbonButton(ID_STATUS_SHOWSTATUS,
_T(""),
IMAGEINDEX_DEFAULTSTATUS);
pBGroup->AddButton(m_pStatusButton);
m_wndStatusBar.AddExtendedElement(pBGroup, _T(""));
I want to use this button as a status indicator.
I want to display a tool tip in the following two cases:
when the status changes and
when the user moves the mouse over the button.
I have no idea how to start in the first place. I have looked at the ToolTipDemo and DlgToolTips sample projects but couldn't figure out how to do it since all they do is display tooltips for the toolbar items or dialog buttons (CWnd-derived instead of CMFCRibbonButton).
If you are familiar with the ToolTipDemo sample project: Since there seem to be several ways of doing things, I would prefer the tooltip to look like the "Extended Visual Manager-based" tool tip as shown in this screenshot.
Thanks!
|
I don't think it's possible to show the tooltip without the mouse cursor being over the control. That's all done automatically.
However if you want to have a nice looking tooltip like in your screenshot, you need to call SetToolTipText and SetDescription, like this:
CMFCRibbonButton* pBtn = new CMFCRibbonButton(12345, _T(""), 1);
pBtn->SetToolTipText("This is the bold Title");
pBtn->SetDescription("This is the not-so-bold Description");
pGroup->AddButton(pBtn);
|
253,475
| 253,519
|
Why doesn't anyone upgrade their C compiler with advanced features?
|
struct elem
{
int i;
char k;
};
elem user; // compile error!
struct elem user; // this is correct
In the above piece of code we are getting an error for the first declaration. But this error doesn't occur with a C++ compiler. In C++ we don't need to use the keyword struct again and again.
So why doesn't anyone update their C compiler, so that we can use structure without the keyword as in C++ ?
Why doesn't the C compiler developer remove some of the glitches of C, like the one above, and update with some advanced features without damaging the original concept of C?
Why it is the same old compiler not updated from 1970's ?
Look at visual studio etc.. It is frequently updated with new releases and for every new release we have to learn some new function usage (even though it is a problem we can cope up with it). We will also get updated with the new compiler if there is any.
Don't take this as a silly question. Why it is not possible? It could be developed without any incompatibility issues (without affecting the code that was developed on the present / old compiler)
Ok, lets develop the new C language, C+, which is in between C and C++ which removes all glitches of C and adds some advanced features from C++ while keeping it useful for specific applications like system level applications, embedded systems etc.
|
Because it takes years for a new Standard to evolve.
They are working on a new C++ Standard (C++0x), and also on a new C standard (C1x), but if you remember that it usually takes between 5 and 10 years for each iteration, i don't expect to see it before 2010 or so.
Also, just like in any democracy, there are compromises in a Standard. You got the hardliners who say "If you want all that fancy syntactic sugar, go for a toy language like Java or C# that takes you by the hand and even buys you a lollipop", whereas others say "The language needs to be easier and less error-prone to survive in these days or rapidly reducing development cycles".
Both sides are partially right, so standardization is a very long battle that takes years and will lead to many compromises. That applies to everything where multiple big parties are involved, it's not just limited to C/C++.
|
253,720
| 253,750
|
Weird #include problem
|
I have a problem with a simple included file.
The file being included is in two MFC programs - one of which is a dll, and it also compiles itself into a non-mfc dll.
Recently I was using the larger dll which wraps around the source of the smaller dll when I wanted access to some of the features of the original code that isn't exposed by the larger dll.
Since this was a test I simply added the source to my project and called the functions. I got this error: syntax error : missing ')' before ';'
The file is correctly included, and I have both the .cpp and the .h in the source folder, and within the project but it wouldn't compile.
I eventually created a very small test project, main.cpp, spooler.cpp and spooler.h (the spooler is a wrapper around the comms) and tried to compile that. Same issue.
So I ripped out all the dll related stuff just in case there is a weird issue going on with that and it still won't compile.
I can't think of the life of me what is wrong. Does anyone else have any ideas?
p.s. Jeff you really need to add the ability to attach files because the source would fill up too many screens with data.
|
This doesn't have anything to do with the way you include files, it's a syntax error that you get because you didn't nest ( and ) correctly.
|
253,768
| 257,369
|
Porting C++ code from Windows to the Mac
|
I'm a long time Windows developer, and it looks like I'm going to be involved in porting a Windows app to the Mac.
We've decided to use Flex/Air for the gui for both sides, which looks really slick BTW.
My Windows application has a C++ DLL that controls network adapters (wired and wireless). This is written using the standard library and Boost, so most of it should work cross platform.
On the Mac, what IDE/complier do most folks use if they want to write C++? Also, can someone provide a pointer to whatever APIs the Mac has that can control WiFi adapters (associate, scan, disconnect, etc)?
|
Xcode is the IDE for Mac OS X, you can download the latest version by joining the Apple Developer Connection with a free Online membership.
I don't believe there are any supported APIs for controlling wireless networking adaptors. The closest thing would be the System Configuration framework, but I don't know if it will let you do everything you want.
Also, I would strongly recommend against trying to use Flex/Air for your application's user experience. It may look slick to you on Windows as a Windows developer, but when it comes to providing a full Macintosh user experience such technologies aren't always a great choice.
For one example, I think Air applications don't support the full range of Mac OS X text editing keystrokes. While not all Mac users will use all keystrokes, for those people used to them trying to type in a text field that doesn't handle (say) control-A and control-E to go to the beginning and end of field is like swimming through syrup.
For a new application that needs to be cross-platform, I'd strongly consider building the core logic in C++ while using Cocoa on the Mac and WPF on Windows to get the best user experience on each platform. Both Mac OS X and Windows have modern native user experience technologies that their respective users are getting used to, and also have good ways for C++ code to interoperate with these technologies.
|
254,132
| 255,663
|
Automake : what are the valid values for *_la_LDFLAGS in Makefile.am?
|
I am wondering what are the possible value for *_la_LDFLAGS in Makefile.am ?
If I ask this question, it is because I would like the following :
Actual shared library : libA.so (or with the version number I don't care)
Symbolic links : libA-X.Y.Z.so, libA-X.so, libA.so
soname : libA-X.so
However here is what I get by using the -release flag :
Actual shared library : libA-X.Y.Z.so
Symbolic links : libA.so
soname : libA-X.Y.Z.so !!! this is not what I want
I also tried with no flags at all and got
Actual shared library : libA-0.0.0.so !!! 0.0.0 and not the real version
Symbolic links : libA.so, libA-0.so
soname : libA-0.so !!! 0.0.0 and not the real version
How should I do ? which flag should I use ?
Thanks in advance
|
You should use the -version-info option of Libtool to specify the interface version of the library, but be sure to read
how versioning works (or here for the official manual.)
You can additionally play with -release to make the version number of your package more apparent, but I doubt you will ever get the exact naming you'd like. Libtool has its own set of rules to define how to name the file and what symlinks to create depending on the system: these should really be regarded as implementation details of how a shared library is installed.
|
254,229
| 254,361
|
Crossplatform Bidirectional IPC
|
I have a project that I thought was going to be relatively easy, but is turning out to be more of a pain that I had hoped. First, most of the code I'm interacting with is legacy code that I don't have control over, so I can't do big paradigm changes.
Here's a simplified explanation of what I need to do: Say I have a large number of simple programs that read from stdin and write to stdout. (These I can't touch). Basically, input to stdin is a command like "Set temperature to 100" or something like that. And the output is an event "Temperature has been set to 100" or "Temperature has fallen below setpoint".
What I'd like to do is write an application that can start a bunch of these simple programs, watch for events and then send commands to them as necessary. My initial plan was to something like popen, but I need a bidrectional popen to get both read and write pipes. I hacked something together that I call popen2 where I pass it the command to run and two FILE* that get filled with the read and write stream. Then all I need to do is write a simple loop that reads from each of the stdouts from each of the processes, does the logic that it needs and then writes commands back to the proper process.
Here's some pseudocode
FILE *p1read, *p1write;
FILE *p2read, *p2write;
FILE *p3read, *p3write;
//start each command, attach to stdin and stdout
popen2("process1",&p1read,&p1write);
popen2("process2",&p2read,&p2write);
popen2("process3",&p3read,&p3write);
while (1)
{
//read status from each process
char status1[1024];
char status2[1024];
char status3[1024];
fread(status1,1024,p1read);
fread(status2,1024,p2read);
fread(status3,1024,p3read);
char command1[1024];
char command2[1024];
char command3[1024];
//do some logic here
//write command back to each process
fwrite(command1,p1write);
fwrite(command2,p2write);
fwrite(command3,p3write);
}
The real program is more complicated where it peeks in the stream to see if anything is waiting, if not, it will skip that process, likewise if it doesn't need to send a command to a certain process it doesn't. But this code gives the basic idea.
Now this works great on my UNIX box and even pretty good on a Windows XP box with cygwin. However, now I need to get it to work on Win32 natively.
The hard part is that my popen2 uses fork() and execl() to start the process and assign the streams to stdin and stdout of the child processes. Is there a clean way I can do this in windows? Basically, I'd like to create a popen2 that works in windows the same way as my unix version. This way the only windows specific code would be in that function and I could get away with everything else working the same way.
Any Ideas?
Thanks!
|
On Windows, you invoke CreatePipe first (similar to pipe(2)), then CreateProcess. The trick here is that CreateProcess has a parameter where you can pass stdin, stdout, stderr of the newly-created process.
Notice that when you use stdio, you need to do fdopen to create the file object afterwards, which expects file numbers. In the Microsoft CRT, file numbers are different from OS file handles. So to return the other end of CreatePipe to the caller, you first need _open_osfhandle to get a CRT file number, and then fdopen on that.
If you want to see working code, check out _PyPopen in
http://svn.python.org/view/python/trunk/Modules/posixmodule.c?view=markup
|
254,526
| 254,599
|
What does a GCC compiled static library contain?
|
My application links against libsamplerate.a. I am doing this to make distributing the final binary easier.
I am worried that perhaps the code inside the .a file depends on some other libraries I also will need to distribute.
But if it doesn't I am worried I am bloating up my application too much by including multiple copies of eg. libc.
What exactly will be inside libsamplerate.a? Just libsamperate's bytecode? Or more?
|
A static library is just a collection of object files. When you compile a program against a static library, the object code for the functions used by your program is copied from the library into your executable. Linking against a static library will not cause any functions outside that library to be included in your code.
|
254,673
| 254,713
|
Multiple Inheritance from two derived classes
|
I have an abstract base class which acts as an interface.
I have two "sets" of derived classes, which implement half of the abstract class. ( one "set" defines the abstract virtual methods related to initialization, the other "set" defines those related to the actual "work". )
I then have derived classes which use multiple inheritance to construct fully defined classes ( and does not add anything itself ).
So: ( bad pseudocode )
class AbsBase {
virtual void init() = 0;
virtual void work() = 0;
}
class AbsInit : public AbsBase {
void init() { do_this(); }
// work() still abs
}
class AbsWork : public AbsBase {
void work() { do_this(); }
// init() still abs
}
class NotAbsTotal : public AbsInit, public AbsWork {
// Nothing, both should be defined
}
First of all, can I do this? Can I inherit from two classes which are both derived from the same Base? (I hope so).
Here is the "real problem", though (I lied a bit above to simplify the example).
What I have really gone and done is add non abstract accessors methods to the base class:
class AbsBase {
public:
void init() { init_impl(); }
void work() { work_impl(); }
private:
virtual void init_impl() = 0;
virtual void work_impl() = 0;
}
Because, a common idiom is to make all virtual methods private.
Unfortunately, now both AbsInit, and AbsWork inherit these methods, and so NotAbsTotal inherits "two of each" ( I realize I may be butchering what is really happening at compile time ).
Anyway, g++ complains that: "request for member init() is ambiguous" when trying to use the class.
I assume that, had I used my AbsBase class as a pure interface, this would have been avoided ( assuming that the top example is valid ).
So:
- Am I way off with my implementation?
- Is this a limitation of the idiom of making virtual methods private?
- How do I refactor my code to do what I want? ( Provide one common interface, but allow a way to swap out implementations for "sets" of member functions )
Edit:
Seems I am not the first one:
http://en.wikipedia.org/wiki/Diamond_problem
Seems Virtual Inheritance is the solution here. I have heard of virtual inheritance before, but I have not wrapped my head around it. I am still open to suggestions.
|
It looks like you want to do virtual inheritance. Whether that turns out to actually be a good idea is another question, but here's how you do it:
class AbsBase {...};
class AbsInit: public virtual AbsBase {...};
class AbsWork: public virtual AbsBase {...};
class NotAbsTotal: public AbsInit, public AbsWork {...};
Basically, the default, non-virtual multiple inheritance will include a copy of each base class in the derived class, and includes all their methods. This is why you have two copies of AbsBase -- and the reason your method use is ambiguous is both sets of methods are loaded, so C++ has no way to know which copy to access!
Virtual inheritance condenses all references to a virtual base class into one datastructure. This should make the methods from the base class unambiguous again. However, note: if there is additional data in the two intermediate classes, there may be some small additional runtime overhead, to enable the code to find the shared virtual base class.
|
254,985
| 339,306
|
choosing a SOAP library to integrate with ISAPI webapp
|
The company I work for has a large webapp written in C++ as an ISAPI extension (not a filter). We're currently enhancing our system to integrate with several 3rd party tools that have SOAP interfaces. Rather than roll our own, I think it would probably be best if we used some SOAP library. Ideally, it would be free and open source, but have a license compatible with closed-source commercial software. We also need to support SSL for both incoming and outgoing SOAP messages.
One of the biggest concerns I have is that every SOAP library that I've looked at seems to have 2 modes of operation: standalone server and server module (either Apache module or ISAPI filter). Obviously, we can't use the standalone server. It seems to me that if it is running as a module, it won't be part of my app -- it won't have access to the rest of my code, so it won't be able to share data structures, etc. Is that a correct assumption? Each HTTP request processed by our app is handled by a separate thread (we manage our own thread pool), but we have lots of persistent data that is shared between those threads. I think the type of integration I'm looking for is to add some code to my app that looks at the request URL, sees that it is trying to access a SOAP service, and calls some function like soapService.handleRequest(). I'm not aware of anything that offers this sort of integration. We must be able to utilize data structures from our main app in the SOAP handler functions.
In addition to handling incoming SOAP requests, we're also going to be generating them (bi-directional communication with the 3rd parties). I assume pretty much any SOAP library will fulfill that purpose, right?
Can anyone suggest a SOAP library that is capable of this, or offer a suggestion on how to use a different paradigm? I've already looked at Apache Axis2, gSOAP and AlchemySOAP, but perhaps there's some feature of these that I overlooked. Thanks.
|
GSoap is a great open source cross platfrom soap stack.
It is FAST.
Great interop.
Many open source soap libraries don't have great interop with java/c#/python/whatever.
It parses HUGE payloads while using very little memory.
It is open source!
Since you are using an IIS extension, you would need to add the gsoap to your app, recompile your extension dll with this: http://aberger.at/SOAP/iis_index.html
and you should be ready to roll.
gSoap
http://www.cs.fsu.edu/~engelen/soap.html
|
255,068
| 259,598
|
Referencing existing SWIG wrappers when creating new ones
|
I have an existing library (JPhysX) that is a Java wrapper for a native C++ library (PhysX). The Java library makes use of types generated by SWIG, for example, com.jphysx.SWIGTYPE_p_NxStream, which represents a pointer to an NxStream object in the C++ code. Now I want to create my own C++ class that inherits from the C++ type NxStream, and have the Java wrapper for my class also inherit from the wrapper com.jphysx.SWIGTYPE_p_NxStream.
The problem is that when I call SWIG to generate the wrapper for my class, it also creates a new wrapper called SWIGTYPE_p_NxStream, which is functionally identical to the one in com.jphysx, but still a different type as far as Java is concerned.
How can I convince SWIG to reuse this existing wrapper from com.jphysx and make the wrapper of my class inherit from com.jphysx.SWIGTYPE_p_NxStream instead?
|
Making the wrapper class explicitly inherit from the desired type did the trick in this case:
%typemap(javabase) UserStream "com.jphysx.SWIGTYPE_p_NxStream";
There were some methods in the wrapper class with which I had similar problems, but I simply removed them from the SWIG interface file because they aren't going to be called from the Java code anyway.
Edit: this does not work. Since the wrapper type inherits from another wrapper type, it suddenly has two swigCPtr fields. The one in the subtype is initialized, the one in the supertype remains 0... but this is the one that gets used when you use the supertype somewhere.
Edit 2: I finally solved the problem, by adding a method to the Java wrapper class to convert the UserStream object to a SWIGTYPE_p_NxStream object:
%typemap(javacode) UserStream %{
public native com.JPhysX.SWIGTYPE_p_NxStream toNxStreamPtr();
%}
This JNI method was hand-written outside SWIG's stuff:
JNIEXPORT jobject JNICALL Java_physics_UserStream_toNxStreamPtr(JNIEnv *env, jobject userStreamObject) {
jclass userStreamClass = env->GetObjectClass(userStreamObject);
jmethodID getCPtrMethodID = env->GetStaticMethodID(userStreamClass, "getCPtr", "(Lphysics/UserStream;)J");
jlong cPtr = env->CallStaticLongMethod(userStreamClass, getCPtrMethodID, userStreamObject);
jboolean futureUse = false;
jclass nxStreamPtrClass = env->FindClass("com/JPhysX/SWIGTYPE_p_NxStream");
jmethodID nxStreamPtrConstructor = env->GetMethodID(nxStreamPtrClass, "<init>", "(JZ)V");
jobject nxStreamPtrObject = env->NewObject(nxStreamPtrClass, nxStreamPtrConstructor, cPtr, futureUse);
return nxStreamPtrObject;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.