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 |
|---|---|---|---|---|
1,520,734 | 1,520,824 | What libraries are available for parsing c++ to extract type information | I'm looking for a way to parse c++ code to retrieve some basic information about classes. I don't actually need much information from the code itself, but I do need it to handle things like macros and templates. In short, I want to extract the "structure" of the code, what you would show in a UML diagram.
For each class/struct/union/enum/typedef in the code base, all I need (after templates & macros have been handled) is:
Their name
The namespace in which they live
The fields contained within (name of type, name of field and access restrictions, such as private/mutable/etc)
Functions contained within (return type, name, parameters)
The declaring file
Line/column numbers (or byte offset in file) where the definition of this data begins
The actual instructions in the code are irrelevant for my purposes.
I'm anticipating a lot of people saying I should just use a regex for this (or even Flex & Bison), but these aren't really valid, as I do need the preprocessor and template stuff handled properly.
| Sounds like a job for gcc-xml in combination with the c++ xml-library or xml-friendly scripting language of your choice.
|
1,520,983 | 1,521,129 | Generating and saving code from Macro | I am analyzing a legacy code which heavily using macro, I am lost in understanding how macro are expanding in code.
Could any one suggest me some tool or technique so that I can study actual code generated from macro expansion.
Platform : Windows XP
Language : C++
Compiler : VC6
| With visual studio you can use the Generate Preprocessed File option.
In the properties for your project select
C/C++/Preprocessor/
In that tab there is an option to:
generate a preprocessed file.
Select Yes, with numbers.
|
1,520,986 | 1,526,167 | Open file in TagLib with Unicode chars in filename | I am quite new to the C++ 'area' so I hope this will not be just another silly 'C++ strings' question.
Here is my problem. I want to integrate TagLib (1.5, 1.6 as soon as I manage to build it for Windows) into an existing Windows MFC VS2005 project. I need it to read audio files metadata (not write).
The problem is that the program stores the input file names using CString(), and it has the Unicode option turned on (so the default chars are "wchar_t"). The reason for this (I think, the project was started by someone else) is that some of the 'input' file names could contain Unicode charaters (for example, Japanse or Arabic characters).
For example, the file path is something like "d:\docs\audio_test\stragecharڝhere.mp3", but I get it with:
CString fpath = tmpFile->GetFilePath();
Now.. if I try to do:
TagLib::FileRef f(fpath.GetBuffer(0));
fpath.ReleaseBuffer();
I get something like:
unresolved external symbol
"__declspec(dllimport) public:
__thiscall TagLib::FileName::FileName(wchar_t
const *)"
If I try something like:
TagLib::FileRef f(reinterpret_cast<char*>(fpath.GetBuffer(0)));
fpath.ReleaseBuffer();
I get rid of the compilation errors, but "f" is an invalid pointer/object.. and when I try reading a tag, I receive an assert failed.
So, can anyone give me some pointers on how should I pass that CString, in it's Unicode form, to the TagLib ?
Update: TagLib address: http://developer.kde.org/~wheeler/taglib.html
Thank you,
Alex
| I missed something essential when I first read your post, so here is another, new and improved answer:
The error comes from the linker, not the compiler. It thus seems that TagLib::FileName does have a ctor taking wchar_t const*, but the problem is that you don't link with the library implementing it, or link with a version of the library that does not include it.
IIUC, this library comes from the Linux world (where file names are expressed as char arrays), and was later ported to Windows (where file names are expressed as wchar_t arrays). The FileName ctor taking a wchar_t array is thus probably conditionally compiled on Windows (i.e., inside #ifdef _WIN32 or something similar), and the library you are linking with (if you are linking the library) was not compiled with the same preprocessor defines.
|
1,521,062 | 1,521,171 | Can I do a multidimensional char array in c++? | First off, this is a "homework" question so vector libraries and string libraries are off limits. I'm trying to get to the basics of c++.
My intention with this code is to make and use an array of string arrays. A list of words in other words.
When I run this code I get a bunch of nonsense.
If there is a better way to make a list of words in c++, I would love to hear about it.
const int cart_length = 50;
const int word_length = 50;
int main()
{
char cart_of_names[cart_length][word_length];
float cart_of_costs[cart_length];
char name[word_length];
cout << "enter the name of the first item: ";
cin >> name;
for(int i=0; i<word_length; i++)
{
cart_of_names[0][i] = name[i];
}
cout << endl;
cout << "that is: ";
for(int x=0; x<word_length; x++)
{
cout << cart_of_names[0][x];
}
cout << endl;
return 0;
}
| I don't exactly understand what you are looking for. Following code will help you to read and print a list of 50 words. Hope this would help you.
const int cart_length = 50;
const int word_length = 50;
int main()
{
char cart_of_names[cart_length][word_length];
float cart_of_costs[cart_length];
for(int i=0; i<cart_length; i++)
{
cout << "enter the name of the " << i + 1 << "th item: ";
cin >> cart_of_names[i];
}
cout << "that is: ";
for(int x=0; x < cart_length; x++)
{
cout << cart_of_names[x] << endl;
}
return 0;
}
|
1,521,080 | 1,521,141 | How to convert Text to Wave using SAPI with multithreading? | I am trying to convert text to wave file using following function. It works fine if called from main UI thread. But it fails when calling from another thread. How to call it from a multi-threaded function?
void Pan_Channel::TextToPlaybackFile( CString Text, CString FileName )
{
// Result variable
HRESULT Result = S_OK;
// Voice Object
CComPtr<ISpVoice> cpVoice;
// Create a SAPI Voice
Result = cpVoice.CoCreateInstance( CLSID_SpVoice );
// Audio format
CSpStreamFormat cAudioFmt;
// Set the audio format
if( SUCCEEDED( Result ) )
{
Result = cAudioFmt.AssignFormat( SPSF_8kHz16BitMono );
}
// File Stream
CComPtr<ISpStream> cpStream;
// Call SPBindToFile, a SAPI helper method, to bind the audio stream to the file
if( SUCCEEDED( Result ) )
{
Result = SPBindToFile( FileName, SPFM_CREATE_ALWAYS, &cpStream,
&cAudioFmt.FormatId(), cAudioFmt.WaveFormatExPtr() );
}
// set the output to cpStream so that the output audio data will be stored in cpStream
if( SUCCEEDED( Result ) )
{
Result = cpVoice->SetOutput( cpStream, TRUE );
}
// Speak the text syncronously
if( SUCCEEDED( Result ) )
{
Result = cpVoice->Speak( Text.AllocSysString(), SPF_DEFAULT, NULL );
}
// close the stream
if( SUCCEEDED( Result ) )
{
Result = cpStream->Close();
}
// Release stream
cpStream.Release();
// Release voice object
cpVoice.Release();
}
| Have you CoInitialized the other thread? COM needs to be initialized on each thread using it. Also .. do you use a COM object created in one thread in another thread? Because you need to marshall the interface between threads if you do that ...
|
1,521,281 | 1,521,305 | What are the STL string limits? | What are the string limits for the Standard Template Library in C++?
| #include <iostream>
#include <string>
int main() {
std::cout << std::string().max_size() << std::endl;
return 0;
}
|
1,521,518 | 1,521,642 | Multithreading in wxWidgets GUI apps? | I'm having problem (basically, I'm confused.) while trying to create a worker thread for my wxWidgets GUI application that WILL MODIFY one of the GUI property itself. (In this case, wxTextCtrl::AppendText).
So far, I have 2 source files and 2 header files for the wx program itself (excluding my own libs, MySQL lib, etc), say MainDlg.cpp which contains a derived class of wxFrame called 'MainDlg' and MainForm.cpp which contains a derived class of wxApp called 'MainForm'.
MainForm.cpp
#include "MainHeader.h" // contains multiple header files
IMPLEMENT_APP(MainForm)
bool MainForm::OnInit()
{
MainDlg *Server = new MainDlg(wxT("App Server 1.0"), wxDEFAULT_FRAME_STYLE - wxRESIZE_BORDER - wxMAXIMIZE_BOX);
Editor->Show();
return true;
}
MainDlg.cpp:
#include "MainHeader.h"
BEGIN_EVENT_TABLE(MainDlg, wxFrame)
EVT_BUTTON(6, MainDlg::StartServer)
EVT_BUTTON(7, MainDlg::StopServer)
END_EVENT_TABLE()
CNETServerConnection *cnServCon;
std::string ServerIP, DBHost, DBUser, DBName, DBPass;
int UserCapacity, DBPort, ServerPort;
MYSQL *sqlhnd;
MainDlg::MainDlg(const wxString &title, long style) : wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(301, 230), style)
{
cnServCon = new CNETServerConnection(100);
this->InitializeComponent();
}
void MainDlg::InitializeComponent()
{
this->SetTitle(wxT("App Server 1.0"));
this->SetSize(396, 260);
this->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE));
this->Centre();
statBox = new wxTextCtrl(this, 4, wxT("Welcome to AppServer 1.0\n\n"), wxPoint(10, 10), wxSize(371, 141), wxTE_MULTILINE | wxTE_READONLY);
//.................................
}
void MainDlg::StartServer(wxCommandEvent &event)
{
this->startBtn->Enable(false);
this->AppendStatus(wxT("\nLoading server configuration... "));
//.................................
this->AppendStatus(wxT("OK\n\nServer ready!\n\n"));
// When the server is ready, I need to run a thread
// that will update the statBox (through AppendStatus func or wxTextCtrl::AppendText directly)
// regularly without interrupting the GUI itself.
// Because the thread will contain a while-loop
// to make the program keep receiving message from clients.
this->startBtn->Hide();
this->stopBtn->Show();
this->cmdBtn->Enable();
this->cmdBox->Enable();
}
void MainDlg::StopServer(wxCommandEvent &event)
{
//...................................
}
void MainDlg::AppendStatus(const wxString &message)
{
statBox->AppendText(message);
}
// Well, here is the function I'd like to run in a new thread
void MainDlg::ListenForMessages()
{
int MsgSender = 0;
while(1)
{
if(!cnServCon->GetNewMessage())
continue;
if(MsgSender = cnServCon->GetJoiningUser())
this->AppendStatus(wxT("Someone connected to the server."));
}
}
I also found an usage example of wxThread from Simple example of threading in C++:
class MessageThread : public wxThread
{
private:
MessageThread(const MessageThread ©);
public:
MessageThread() : wxThread(wxTHREAD_JOINABLE)
{
}
void *Entry(void)
{
// My works goes here
return;
}
};
wxThread *CreateThread()
{
wxThread *_hThread = new MessageThread();
_hThread->Create();
_hThread->Run();
return _hThread;
}
But I don't know how to associate it with my program and make it able to modify my GUI property (statBox).
Any kind of help would be appreciated! :)
Thanks.
| The easiest is to create an event type id, and use a wxCommandEvent using the type id, set its string member ("evt.SetText"), and send the event to one of your windows (using AddPendingEvent). In the handler of that event, you can then call AppendText on your control using the text you sent (evt.GetText), because you are in the GUI thread by then.
// in header
DECLARE_EVENT_TYPE(wxEVT_MY_EVENT, -1)
// in cpp file
DEFINE_EVENT_TYPE(wxEVT_MY_EVENT)
// the event macro used in the event table. id is the window id you set when creating
// the `wxCommandEvent`. Either use -1 or the id of some control, for example.
EVT_COMMAND(window-id, event-id, handler-function)
Here is an overview how it works: Custom Events.
|
1,521,607 | 1,521,682 | Check double variable if it contains an integer, and not floating point | What I mean is the following:
double d1 =555;
double d2=55.343
I want to be able to tell that d1 is an integer while d2 is not. Is there an easy way to do it in c/c++?
| Use std::modf:
double intpart;
modf(value, &intpart) == 0.0
Don't convert to int! The number 1.0e+300 is an integer too you know.
Edit: As Pete Kirkham points out, passing 0 as the second argument is not guaranteed by the standard to work, requiring the use of a dummy variable and, unfortunately, making the code a lot less elegant.
|
1,521,924 | 1,521,941 | C++ program halts after dynamic memory allocation | I'm having problem with a copying method in a simple C++ program.
Everytime I call copy:
Sudoku::SudokuNode** Sudoku::copy(SudokuNode** sudokuBoard)
{
SudokuNode** tempSudokuBoard = new SudokuNode*[9];
for(int i = 0; i<9; i++)
{
tempSudokuBoard[i] = new SudokuNode[9];
for(int j = 0; j<9; j++)
{
tempSudokuBoard[i][j].currentInteger = sudokuBoard[i][j].currentInteger;
for(vector<int>::iterator iter = sudokuBoard[i][j].possibleIntegers.begin(); iter!= sudokuBoard[i][j].possibleIntegers.end();)
{
tempSudokuBoard[i][j].possibleIntegers.push_back(*iter);
}
}
}
return tempSudokuBoard;
}
The program seems to completely halt, not returning a a visible error.
If I try to debug the program, the debugger works fine until I arrive at the copy method. Then the debugger displays a dialog box saying:
There is no source code available for the current location.
Any idea what is wrong?
| for(vector<int>::iterator iter = sudokuBoard[i][j].possibleIntegers.begin(); iter!= sudokuBoard[i][j].possibleIntegers.end();)
You don't seem to be advancing the iterator in that loop, so it will never end. Add ++iter to the counting expression (after the last ; in the for loop).
As to why your debugger can't find source for that location, that's platform dependent. What debugger are you using?
|
1,522,107 | 1,522,123 | How can I communicate between two C++ MFC plugins? | I have a plugin for a c++ MFC app. I'm working with the developer of another plugin for the same app, that's trying to get notifications of events in my code. Both plugins are in the form of c++ dlls.
How can I pass messages from my plugin to his plugin? The solution needs to be robust to mismatched versions of our two plugins, as well as the host app. The notifications are during control point movement, so several times a second.
I could set up a callback mechanism, where upon load his plugin calls a function in my plugin with a function pointer. We're not guaranteed any loading order, but we could probably just check periodically.
I know Win32 has a messaging system, but I'm not sure how it works, really. We could add a hook, and I could send messages, but I'm a bit fuzzy on how we'd synchronize what the message id is, or any details other than what I said, really.
Any other ideas on how to do this?
| Take a look at this article here, it shows the available IPC mechanisms in windows. I might try COM, Mailslots, Pipes or Shared Memory (file mapping) in your case, in addition to windows messages which you already mentioned.
|
1,522,141 | 1,522,156 | Is there any advantage in using a reference argument in this function? | I have defined the following class:
class Action
{
public:
Action(){ _bAllDone = false; }
void AddMove( Move & m );
private:
std::deque<Move> _todo;
bool _bAllDone;
};
The member AddMove is defined as follows:
void Action::AddMove( Move & m )
{
_todo.push_back( m );
}
I noted that without the reference argument to this function the Copy Constructor was called twice, whereeas with a reference argument it was called only once. Is calling a Copy Constructor only once instead of twice a good reason to use a reference argument?
| The deque class in STL is supposed to maintain a copy of the element you pass to its push_back method. That is where one copy constructor comes from.
If you get rid of the reference in addMove(), you will first get a copy of the parameter (and thus one invocation of the copy constructor), and then when you push back, you will get a second copy.
The dual invocation of the copy constructor is wasteful so the reference is preferable. However, you should declare the parameter of addMove() as a const reference, to indicate to the caller that the element will not be modified. Under such an assurance (assuming you don't break it), it is safe to pass the object by reference without worrying and without paying the penalty of an object copy.
|
1,522,149 | 1,522,175 | c++ vectors - Using find(begin, end, term) | Ok, i'm doing this and it works fine.
end = std::find(arToken.begin() + nStart, arToken.end(), ".");
I want to extend the . to include ! and ? so it finds periods(.), exclamation mark(!), and question mark(?).
Should i use regex in the term?
TIA
| you should use std::find_first_of:
std::string m(".!?");
end = std::find_first_of(arToken.begin() + nStart, arToken.end(), m.begin(),m.end());
|
1,522,373 | 1,522,389 | Header class file to be used by others | I would like to know if there is a way to put only protected and public stuff on the header file .h, and all private stuff in the compile unit .cpp
I need this because the library is going to be used by others, and I wouldn't like to have to copy and edit all .h files to remove private declarations and implementations.
I tried but got the duplicate declaration error
another question is about private static stuff
can I declare them on the header file and implement them on the .cpp unit?
a private variable and a public get method
I tried but couldn't implement the method on the unit, it only worked with the declaration and implementation on the header
[]s,
Joe
| The proper way to deal with this is to implement the pimpl idiom: Create a class or struct for all private data and put a pointer to such an object in the header file, together with a forward declaration. Now nothing of the private data and methods is visible from the header file.
|
1,522,555 | 1,522,583 | c++ winsock2, how to tell when a connection closes | I have a c++ program using winsock2. I would like to know how to tell when someone's connection to my program closes.
| Use select to wait for reading on the socket; when the socket is closed winsock should report it as readable. Receiving from the socket will then give you 0 bytes, telling you that the socket was closed.
|
1,522,728 | 1,522,766 | Is it possible to force a string to be a specific size when defining a struct? | I am marshalling data between a C# and C++ application. In the C# application, I force the size of a string to be some size (say, 256 bytes). I would like to read in that exact same amount in C++ (I will be recreating the structs with reinterpret_cast) so that the data will remain formatted as it was in the C# application. Unfortunately, I'm pretty rusty with C++ and I'm not sure how to force a string's size in a struct in C++.
As requested, an example. I have a struct in C# that looks like this:
[StructLayout(LayoutKind.Sequential)]
public struct DataLocater
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string filename;
[MarshalAs(UnmanagedType.I4)]
public Int32 sizeOfData;
public Int32 startLocation;
public Int32 encrypted;
}
Which I am marshalling several of (along with other data) to a data file. The C++ file is then reading this file in and I will be parsing it back into struct in C++ with the same structure. My first attempt at this struct looked like:
struct DataLocater
{
std::string filename;
int sizeOfData;
int startLocation;
int encrypted;
};
But there is no way for the compiler to know that I want that std::string to be 256 bytes.
edit: adding full header file for example.
#pragma once
#include "CoreArea/Singleton.h"
class FileReader : public Singleton<FileReader>
{
friend class Singleton<FileReader>;
public:
void* GetFileData(std::wstring fileName, int &size);
private:
FileReader();
~FileReader();
struct Header
{
std::string somestring;
int numOfFiles;
};
struct DataLocater
{
char[256] filename;
int sizeOfData;
int startLocation;
int encrypted;
};
};
| In general you're taking the wrong approach here. Mixing non-data only C++ types and PInvoke will lead you to a lot of pain. Types like std::string should not be used in this scenario because the marshaller cannot correctly create them at runtime.
Instead you need to use more primitive types. In this particular scenario, based on the managed signature, the appropriate C struct is the following
struct DataLocater
{
char filename[256];
int sizeOfData;
int startLocation;
int encrypted;
};
|
1,522,789 | 1,522,802 | Can I make a bitwise copy of a C++ object? | Can C++ objects be copied using bitwise copy? I mean using memcopy_s? Is there a scenario in which that can go wrong?
| If they're Plain Old Data (POD) types, then this should work. Any class that has instances of other classes inside it will potentially fail, since you're copying them without invoking their copy constructors. The most likely way it will fail is one of their destructors will free some memory, but you've duplicated pointers that point to it, so you then try to use it from one of your copied objects and get a segfault. In short, don't do it unless it's a POD and you're sure it will always be a POD.
|
1,522,828 | 1,522,836 | traversing a singly linked list in C++ | I was wondering if it is possible to traverse a linked list like this:
currentNode = randomNode;//where randomNode may or may not = firstNode
prevNode = firstNode;
while(prevNode != currentNode && prevNode->link != currentNode)
{
prevNode = prevNode->link;
}
Is it possible to do this in C++ when I am trying to find the node before currentNode in a singly linked list?
I trying to implement something like this in a console app for a school assignment so assume that I can't use anything fancy like the boost libraries/list/anything that makes life easier, etc. So basically, I have only fairly primitive datatypes and libraries at my disposal.
| You might want to make sure that prevNode->link is not a null reference either, in case currentNode is not actually linked.
|
1,522,853 | 1,522,878 | Creating your own HRESULT? | I already have a project that uses a lot of COM, and HRESULTS. Anyways I was wondering if it's possible to define your own HRESULT, AND be able to use the FormatMessage() for our own HRESULT?
I dug around and can't find anything. Any ideas?
EDIT
Basically I want to define a set of my own HRESULTs instead of just returning E_FAIL. Or one of the other generic ones. Like E_FAIL is fine. But let's say I want to point out that for example the Geoprocessing subsystem crashed or the file is an invalid Raster Image. The application already uses COM throughout it.
| Yes of course. Typically you create a .mc file and include that in your project. Instruct the mc compiler to build it - this creates a header file and a .rc file. The HRESULTS are defined in the header file. You include the .rc file in your project as normal for the resource compiler to compile - this puts the message definitions into your final module. Then you can use the normal FormatMessage functions to format the messages using the HRESULTS and generate error info and the other stuff.
I have this as the command line for one of my .mc files:
mc -h "../include" -r "../include" "..\include\errors.mc"
This creates errors.rc and errors.h in the include directory. Then I did:
#include "errors.rc"
in my main .rc file for the project.
The .mc file looks a bit like this:
LanguageNames=(English=0x409:MSG00409)
MessageId=0x1
SymbolicName=SOME_CATEGORY
Language=English
Some Category
.
MessageID=
Severity=Error
SymbolicName=ERROR_INVALID_PROP_INDEX
Language=English
Invalid property index %1
.
with lots of error numbers defined.
|
1,522,912 | 1,523,011 | Reference in lhs and rhs difference in C++ | I am learning C++ and I found that when a reference is on the right hand side, there can be two cases. Suppose I have a method:
int& GetMe(int& i) { return i; }
And I have:
(1) int j; GetMe(j) = GetMe(i);
and
(2) int& k = GetMe(i);
The consequences of (1) and (2) are different. In (1), the semantic is to copy the value of i into j. The addresses of i and j are remained the same. Changing i doesn't affect j at all. Actually this is the case when you overload the index operator[] and use the index operator for assignment. In (2), the semantic is to create a referent of i as k. k has the same address as i and changing i affects k.
So why do we have the differences? I think, in C++, a reference's address is determined once and only once. Once a reference's address is determined, it can never be changed later. In (1), the reference of j is determined before, so the action is to copy value from i to j. In (2), the reference of k is being declared and initialized so it is done using reference of i. So the action is reference initialization.
I didn't find material explicitly saying above things so I want confirmation. Anyone knows reference well in C++ must can help me or point me to clear material. Thank you very much in advanced.
| What you are missing here is that type of variable is different and it is all that matters. In first example you have int j and in second - int &k.
References in functions prototypes exists in different grounds, they looks the same, underneath they are pretty much the same but they used differently because they exists only when method is executing.
Actually, your code is dong exactly following
int j;
int & j1 = j;
int & i1 = i;
j1 = i1;
versus
int & i1 = i;
int & k = i1;
It's easy to see that in first case two references actually reference different variables i.e. different parts in memory but in second case they all reference the exact same variable. Hence the difference.
|
1,522,994 | 1,523,082 | Store an int in a char array? | I want to store a 4-byte int in a char array... such that the first 4 locations of the char array are the 4 bytes of the int.
Then, I want to pull the int back out of the array...
Also, bonus points if someone can give me code for doing this in a loop... IE writing like 8 ints into a 32 byte array.
int har = 0x01010101;
char a[4];
int har2;
// write har into char such that:
// a[0] == 0x01, a[1] == 0x01, a[2] == 0x01, a[3] == 0x01 etc.....
// then, pull the bytes out of the array such that:
// har2 == har
Thanks guys!
EDIT: Assume int are 4 bytes...
EDIT2: Please don't care about endianness... I will be worrying about endianness. I just want different ways to acheive the above in C/C++. Thanks
EDIT3: If you can't tell, I'm trying to write a serialization class on the low level... so I'm looking for different strategies to serialize some common data types.
| Not the most optimal way, but is endian safe.
int har = 0x01010101;
char a[4];
a[0] = har & 0xff;
a[1] = (har>>8) & 0xff;
a[2] = (har>>16) & 0xff;
a[3] = (har>>24) & 0xff;
|
1,523,142 | 1,523,149 | Boost equivalent of memcpy? | Is there a boost equivalent for memcpy? Thanks!
EDIT: Sorry, I didn't realize memcpy was in the standard library :)
I thought it was an OS call :(
| Does there need to be one? What's wrong with memcpy? Although it comes from C, it's a perfectly valid C++ function. If you want something that's aware of C++ objects and their assignment operators, then use std::copy. You might also want to take a look at std::uninitialized_copy.
|
1,523,186 | 1,523,195 | What is the proper method of reading and parsing data files in C++? | What is an efficient, proper way of reading in a data file with mixed characters? For example, I have a data file that contains a mixture of data loaded from other files, 32-bit integers, characters and strings. Currently, I am using an fstream object, but it gets stopped once it hits an int32 or the end of a string. if i add random data onto the end of the string in the data file, it seems to follow through with the rest of the file. This leads me to believe that the null-termination added onto strings is messing it up. Here's an example of loading in the file:
void main()
{
fstream fin("C://mark.dat", ios::in|ios::binary|ios::ate);
char *mymemory = 0;
int size;
size = 0;
if (fin.is_open())
{
size = static_cast<int>(fin.tellg());
mymemory = new char[static_cast<int>(size+1)];
memset(mymemory, 0, static_cast<int>(size + 1));
fin.seekg(0, ios::beg);
fin.read(mymemory, size);
fin.close();
printf(mymemory);
std::string hithere;
hithere = cin.get();
}
}
Why might this code stop after reading in an integer or a string? How might one get around this? Is this the wrong approach when dealing with these types of files? Should I be using fstream at all?
| Have you ever considered that the file reading is working perfectly and it is printf(mymemory) that is stopping at the first null?
Have a look with the debugger and see if I am right.
Also, if you want to print someone else's buffer, use puts(mymemory) or printf("%s", mymemory). Don't accept someone else's input for the format string, it could crash your program.
Try
for (int i = 0; i < size ; ++i)
{
// 0 - pad with 0s
// 2 - to two zeros max
// X - a Hex value with capital A-F (0A, 1B, etc)
printf("%02X ", (int)mymemory[i]);
if (i % 32 == 0)
printf("\n"); //New line every 32 bytes
}
as a way to dump your data file back out as hex.
|
1,523,386 | 1,860,001 | Sharing code between projects without svn:externals | In order to simplify the build process, I've been trying to reorganize my version control repository.
I am developing a simple client-server application. Following Rob Williams' advice, I have separated the client and the server into separate projects each with their own lifecycle. The problem though, is that client and server share some communication code. More specifically the client sends message objects that the server receives. Both projects are being developed in C++, and the message object headers are required for the client and server to compile.
How should I go about sharing the message object headers between the two projects without using a version-control feature such as svn:externals?
| Why don't you put your common code into a third repository. Then use a convention for naming your working copies, so that you can use relative include paths like ../shared/someheader.h
|
1,523,483 | 1,523,497 | Does GCC support long long int? | Does GCC support:
long long int
which would be a 64-bit integer?
Also, is long long int part of the standard?
| Yes GCC does support long long int, which is a part of C99 standard.
The standard does not mandate its size in bits, but required values of LLONG_MIN and LLONG_MAX in <limits.h> imply it's at least 64-bit (exact 64-bit wide integer types are int64_t/uint64_t from <stdint.h>).
LLONG_MIN must be at most -9223372036854775807
LLONG_MAX must be at least 9223372036854775807
|
1,523,732 | 1,523,870 | Where hardcoded values are stored? | For an investigation i need to know where hard-coded values are stored.
Question : A function having hard-coded values inside it , and this function is called by many threads at same time , is there any chance that that hard-coded value will be corrupted.
For example : myFunc is called by many thread at same time .
can literal "Unhandled exception:" be corrupted
void myFunc()
{
EXCEPTION_RECORD ExceptRec
bool retValue=doSomething(ExceptRec);
if(!retValue)
{
log ("Unhandled exception:"<< " code = " << hex << ExceptRec.ExceptionCode
<< " flags = " << ExceptRec.ExceptionFlags
<< " address = " << ExceptRec.ExceptionAddress)
// log is macro which will insert content into ostrstream
}
}
Function doSomething looks like :
bool doSomething(EXCEPTION_RECORD &ExceptRec)
{
__try
{
// some code here
}
__except (ExceptRec = *(GetExceptionInformation())->ExceptionRecord,
EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
return true;
}
| Literal strings are stored in the .data section of your program image when they are compiled. The .data section is usually mapped into read only memory so it cannot be corrupted just like the .code section. You can view the .data section of a windows exe/dll by using dumpbin.exe that comes with visual studio.
There is no easy way to corrupt this literal, it can be done if you modify the permisions of the memory page it is stored in, but you would have to explicitly do that by using an OS api, not a c++ api. The address hard coded into the machine code at compile time is a relative offset (if memory serves me it is to the data section base). This offset is added to the base address supplied by the operating system loader.
If your stack is corrupt you can end up with situation where the base address is invalid so when the offset is added, the literal looks corrupt.
|
1,523,802 | 1,525,470 | How to place 90X90 icon | i am creating .cab file installer for windows mobile application,
problem is i need to keep the 90X90 .png image as icon for application.
as per the link
i tried to load the icon,step am following are
1) writing the icon path to registry
2) then loading the icon...
i followed the step mentioned above link,
but the problem is i need to restart my device or emulator to get the 90X90 png icon..
i dont no what is the reason... every time i need to restart..
please let me know, how to fix this probme.. and let me know the reson why its appearing.
| The Windows Mobile shell caches the icon. On your first install on a clean device, your icon will be used. After that, the icon will remain in the cache until the device is reset, so if you want to change an icon with an already-installed app, you have to soft reset to force the shell to reload the cache.
Again, this is only a problem when changing the icon for an already-installed app. It's not going to affect your users when they are installing it on a clean device (and therefore probably is not an issue for you at all).
|
1,523,822 | 1,524,277 | Win32Api - Window Name Property | Is there any way to get a control's name through win32api? (c++)
I'm talking about the property that in C# is 'Name', like 'frmMain', or 'btnNext'.
Is there any way to retrieve this data through the win32API?
I've tried GetWindowInfo() and stuff but I think I'm not heading in the right direction..
thanks
edit: I'm iterating with EnumChildWindows() and I got the correct HWND.. not sure if I can use it to print it's name.. (im a c++/win32 absolute noob)
Added 7/10/09
By the way I found this really good tool to operate win32 apps.
http://www.autoitscript.com/autoit3/
Check it out looks good and looks like it's freeware? :)
| I seriously doubt that this information is even in the executable code, I would think that from the c# compilers point of view these symbols get reduced to object pointers or window identifiers values (the IDC_ mentioned above).
Having been faced with this type of problem before I chose to create hidden static text controls with identifying text on each window to provide this named window capability to an external process. Not very elegant but solved my problem at the time.
|
1,523,888 | 1,523,893 | which namespace does toupper belong to | when I'm reading some c++ sample code for beginner , I'm puzzled at the usage of toupper in the following line :
std::transform(data.begin(), data.end(), data.begin(), ::toupper);
from the above line, I know that "transform" is from namespace std , but I don't know which namespace does toupper come from . maybe there is a default namespace for c++ but
that is just my guess. so could you explain the usage of toupper here to me ?
| If you include
<cctype>
then toupper() is in namespace std. If you include
<ctype.h>
then toupper() is in the global namespace. (The one everything ends up in if not defined in a specific namespace. The one you refer to with a leading :: when you're in a specific namespace.)
The same rule applies to <cstring> vs. <string.h>, <cstdlib> vs. <stdlib.h> etc.
|
1,523,916 | 1,523,976 | How to handle same socket in different threads? | I am trying to handle socket in different threads creating runtime failure. See following code.
void MySocket::Lock()
{
m_LockCount++;
if( m_LockCount )
{
CSocket::Create( 8080 );
}
}
void MySocket::Unlock()
{
m_LockCount--;
if( !m_LockCount )
{
CSocket::Close();
}
}
I am calling Lock() from one thread and Unlock() from other. When it executes CSocket::Close() it gives an exception.
I googled for this bug and got some reasons.
This happens because; a CSocket object should be used only in the context of a single thread because the SOCKET handle encapsulated by a CAsyncSocket object is stored in a per-thread handle map. They are also suggesting a solution by sharing SOCKET handles between threads (http://support.microsoft.com/kb/175668). But this is not possible in my case since I am excepting some notification callback which will not work with above solution. Can anybody suggest a mechanism to share CSocket among threads without effecting notification callbacks?
| If, as you say, "a CSocket object should be used only in the context of a single thread," then there is no "mechanism to share CSocket among threads".
In other words, one of the threads needs to own the CSocket, and the others can't mess with it.
In such cases, the solution is to use an inter-thread messaging system. That way, one of the other threads can send a message to the owner saying, "Hey, buddy, close your socket!"
The details of how you would do that messaging depend entirely on the context of your program.
|
1,523,981 | 1,524,006 | API for Giving Notification when a file is added or deleted in a folder | is there any windows API or shell API which will give a notification on when a file is added or deleted in a folder
| These API's can help you. and you can find a nice tutorial here
FindFirstChangeNotification
FindCloseChangeNotification
FindNextChangeNotification
|
1,524,139 | 1,524,387 | ANSI C functions namespace in ISO C++ | Consider the following small program:
#include <cstdio>
int main() {
printf("%d\n", 1);
std::printf("%d\n", 2);
return 0;
}
What does C++ standard say about importing C library functions into global namespace by default? Can you point me to the relevant C++ standard section?
What is the reason ANSI C functions are in std namespace in the first place, since they are by default imported into global namespace?
| 7.4.1.2/4:
Except as noted in clauses 18 through 27, the contents of each header cname shall be the same as that of the corresponding header name.h, as specified in ISO/IEC 9899:1990 Programming Languages C (Clause 7), or ISO/IEC:1990 Programming Languages—C AMENDMENT 1: C Integrity, (Clause 7), as appropriate, as if by inclusion. In the C + + Standard Library, however, the declarations and definitions (except for names which are defined as macros in C) are within namespace scope (3.3.5) of the namespace std.
D.5/2:
Every C header, each of which has a name of the form name.h, behaves as if each name placed in the Standard library namespace by the corresponding cname header is also placed within the namespace scope of the namespace std and is followed by an explicit using-declaration (7.3.3).
In practice, however, name.h includes the names in the global namespace and cname in both the global and std namespace (i.e. the other way around than the standard specifies).
|
1,524,312 | 1,524,317 | Why am I able to make a function call using an invalid class pointer | In below code snippet, although pointer is not initialized the call is still made successfully
temp *ptr;
ptr->func2();
Is it due to C++ language property, or it is VC++6 compiler which is foul playing?
class temp {
public:
temp():a(9){}
int& func1()
{
return a;
}
bool func2(int arg)
{
if(arg%2==0)
return true;
return false;
}
int a;
};
int main(int argc, char **argv)
{
temp *ptr;
int a;
cin>>a;
if(ptr->func2(a))
{
cout<<"Good poniner"<<endl;
}
ptr->func1(); // Does not crash here
int crashere=ptr->func1();// But does crash here
return 0;
}
| The C++ compiler doesn't prevent you from using uninitialised pointers, and although the results are undefined, it's normal for compilers in the real world to generate code that ignores the fact that the pointer is uninitialised.
It's one of the reasons why C++ is both fast and (comparatively) dangerous relative to some other languages.
The reason your call to func2 succeeds is that it doesn't touch its this pointer. The pointer value is never used, so it can't cause a problem. In func1 you do use the this pointer (to access a member variable), which is why that one crashes.
|
1,524,356 | 1,524,510 | C++ deprecated conversion from string constant to 'char*' | I have a class with a private char str[256];
and for it I have an explicit constructor:
explicit myClass(const char *func)
{
strcpy(str,func);
}
I call it as:
myClass obj("example");
When I compile this I get the following warning:
deprecated conversion from string constant to 'char*'
Why is this happening?
| This is an error message you see whenever you have a situation like the following:
char* pointer_to_nonconst = "string literal";
Why? Well, C and C++ differ in the type of the string literal. In C the type is array of char and in C++ it is constant array of char. In any case, you are not allowed to change the characters of the string literal, so the const in C++ is not really a restriction but more of a type safety thing. A conversion from const char* to char* is generally not possible without an explicit cast for safety reasons. But for backwards compatibility with C the language C++ still allows assigning a string literal to a char* and gives you a warning about this conversion being deprecated.
So, somewhere you are missing one or more consts in your program for const correctness. But the code you showed to us is not the problem as it does not do this kind of deprecated conversion. The warning must have come from some other place.
|
1,524,730 | 1,524,753 | C++ - when are non-pointers class member destroyed? | Suppose I have this code...
class GraphFactory : public QObject
{
private:
QMap<QString, IGraphCreator*> factory_;
public:
virtual ~GraphFactory();
};
GraphFactory::~GraphFactory()
{
// Free up the graph creators
QMap<QString, IGraphCreator*>::iterator itr;
for (itr = factory_.begin(); itr != factory_.end(); itr++)
{
IGraphCreator * creator = itr.value();
delete creator;
creator = NULL;
}
}
When is the QMap factory_ destroyed? Before the call to the destructor, or during the destructor? (I understand that the destructor will be called when an instance of GraphFactory goes out of scope. But when are the non-pointers member destroyed?)
Edit: I am getting invalid values for the factory_ map when it reaches the destructor. A break point shows that the value wouldn't have tampered with the value stored inside the QMap.
| It'll be destructed after the destructor code gets executed
The idea is to have access to your members in the destructor code so they get destroyed after it gets executed.
|
1,524,905 | 1,526,930 | Linux ioctl -> how to tell if current IP was obtained by dhcp | I'm fiddling with the sockets ioctl's to get the current interfaces setup and I can already get the IP, interface name, netmask and check if the interface is up or down, (I just do IOCTl to SIOCGIFCONF, SIOCGIFNETMASK and SIOCGIFFLAGS).
I am looking for a way to tell if my current IP address was obtained through dhcp or if it was static.
I can check /etc/network/interfaces for everything I want, but I'm looking for a way to do it programmaticly (does this word exist?).
Does anyone have any insight into this?
One more thing, I'm working on Linux (for now).
Cheers
| With the wide variety of DHCP clients on Linux -- pump, dhcpcd, dhclient, udhcpc, and quite possibly others that I do not know of -- this isn't possible in a general sense.
However, if you are targeting a specific distribution -- say, "default install of Ubuntu" -- then you can investigate solutions such as Stefan's. Note that all four of the DHCP clients listed here can be installed on Ubuntu and can replace the default DHCP client, dhclient.
|
1,524,946 | 1,526,272 | UDP multicast using winsock API differences between XP and Vista | It seems to be that the implementation required to set up a UDP multicast socket has changed between windows XP and windows vista. Specifically:
Under windows XP, you must call bind() before you can reference any multicast-specific socket options.
However, under windows vista, you must not call bind() when dealing with multicast sockets.
Failing either of these two points results in a socket error at runtime.
Am I going crazy, or have other people seen this as well? Is there a better solution than conditional compilation of the bind() call?
| What error are you getting from the setsockopt() call that you make to apply IP_ADD_MEMBERSHIP and join the multicast group?
I've just run some tests here with my server framework and I note that I DO call bind() on Windows 7 (I don't have a Vista box to hand) and I can then also join a multicast group as expected as long as both the binding address and the multicast address are valid.
However I cannot call bind() with INADDR_ANY, as that causes the joining of the multicast group to fail with error 10022 (WSAEINVAL) and if the multicast group address isn't a valid multicast address the call fails with error 10049 (WSAEADDRNOTAVAIL). Which all seems fair enough.
I'm booting an XP box now...
[Edited after testing on XP]
On XP it's legal to bind() to INADDR_ANY and it's legal to use invalid multicast addresses. So, I expect, you're doing one of those and it therefore works on XP and not on Vista/Win7.
So, what error are you getting and what address are you binding to?
|
1,524,989 | 1,525,058 | separating compilation for to avoid recompilation when I add some debugging to .h file | I have a .h file which is used almost throughout the source code (in my case, it is just one directory with. .cc and .h files). Basically, I keep two versions of .h file: one with some debugging info for code analysis and the regular one. The debugging version has only one extra macro and extern function declaration. I switch pretty regularly between two versions. However, this causes a 20 minute recompilation.
How would you recommend to avoid this issue of recompilation? Perhaps to set some flags, create different tree? what are the common solutions and how to embed them?
The new .h file contains:
extern void (foo)(/*some params*/);
/***extra stuff****/
#define foo(...) ( /*call_some_function*/) , foo())
/*some_functions*_for_debugging/
As, you can see that will ensue a recompilation. I build with gcc on Linux AS 3
Thanks
| To avoid the issue with an external function , you could leave the prototype in both versions, it doesn't harm being there, if not used. But with the macro no chance, you can forget it, it needs recompilation for code replacements.
I would make intensive use of precompiled headers to fasten recompilation (as it cannot be avoided). GCC and Precompiled-Headers. For other compilers use your favorite search engine. Any modern compiler should support this feature, for large scale projects it's inevitable you have to use it otherwise you'll be really unproductive.
Beside this, if you have enough disk space, I would check out two working copies. Each of them compiled with different settings. You would have to commit and update each time to transfer changes to the other working copy but it'll take for sure less than 20mins ;-)
|
1,525,187 | 1,525,195 | How do we explain the result of the expression (++x)+(++x)+(++x)? | x = 1;
std::cout << ((++x)+(++x)+(++x));
I expect the output to be 11, but it's actually 12. Why?
| We explain it by expecting undefined behaviour rather than any particular result. As the expression attempts to modify x multiple times without an intervening sequence point its behaviour is undefined.
|
1,525,246 | 1,525,297 | How to set fixed axis intervals with Qt/QwtPlot? | I want to have a plotting widget in my Qt application. Qwt provides such a widget with QwtPlot. However, I can't find any way to only display a certain part of the complete range of my data.
Specifically, I want to display spectrums with a frequency range from 0 to 2^14. For the GUI however, only the audible range from ~20-20k Hz is of significance, so I only want to display that part.
Do you know of any way of telling QwtPlot to do that?
Thank you for your answers.
| Simple answer: Use QwtPlot::setAxisScale().
sorry for answering my own question.
|
1,525,284 | 5,795,889 | Mpeg 7 Descriptors in C++ | I need some descriptors of MPEG7 in C/C++. The descriptors are dominant color, color layout, color structure, scalable color, edge histogram and homogeneous texture. Do you know where can I find C/C++ source code for some of these these descriptors?
Thanks
| You can find the MPEG-7 feature extraction library and source code with OpenCV (2.2) at http://www.cs.bilkent.edu.tr/~bilmdg/bilvideo-7/Software.html
|
1,525,326 | 1,525,369 | Initializing temporary aggregate object using curly braces | Let's say I have a class:
class Aggregate {
public:
int x;
int y;
};
I know how to initialize an object using curly braces:
Aggregate a1 = { 1500, 2900 };
But I can't find a proper syntax to create temporary object and pass it as an argument to some method, for example:
void frobnicate(const Aggregate& arg) {
// do something
}
//...
frobnicate(Aggregate {1500, 2900}); // what should this line look like?
The easiest way would be to add the constructor to Aggregate class, but let's assume I don't have an access to the Aggregate header. Another idea would be to write some kind of factory method, i.e.
Aggregate makeAggregate(int x, int y).
I can also create an object and then pass it as an argument, etc. etc.
There are many solutions, but I'm just curious if it's possible to achieve this goal using curly braces initialization.
| What you want is possible with C++0x initializer lists.
class Aggregate {
public:
int x, y;
};
void frobnicate(const Aggregate& arg) {
}
int main() {
frobnicate({1, 2});
return 0;
}
GCC 4.4 already supports this with -std=c++0x flag. Possibly VS2010 CTP supports this too (correct me if I'm wrong).
With C++98/C++03 you will have to write and invoke a constructor.
|
1,525,452 | 1,525,965 | Does anyone have experience with Clipsmm? | I have been looking at using CLIPS as an expert system for a simulator i am working on, and so i had a look at clipsmm. The only problem is that their sourceforge page has broken links and private forums.
I was just curious if anyone has had experience with clipsmm (i have learnt how to use CLIPS as a stand alone already), and i just need a little help getting the c++ wrapper working.
Any help that someone could give me would be great.
Thanks
-Craig
(sorry can't make custom tags for this so had to use generic ones)
| Well, I don't have direct experience, but I happen to have been the original author of a very similar set of wrappers for Ada.
I developed what I needed for a school project, and released it to the Public Domain in hopes that somebody else could build on it or find it useful. Some folks have used it, but not enough to support a full-fledged project. It looks like the userbase in the C++ realm isn't a lot better.
My suggestion to you would be to accquaint yourself with how your C++ compiler handles C bindings, download what code you can find, and dive right into it. You aren't likely to find a lot of very experienced help in a small niche like this.
If I'm wrong, I'm happy for you.
|
1,525,456 | 1,525,642 | Converting Unicode to Multibyte | I have smalll problem i want to convert unicode into Multi byte is there any way
| std::string NarrowString(const std::wstring& str, const char* localeName = "C")
{
std::string result;
result.resize(str.size());
std::locale loc(localeName);
std::use_facet<std::ctype<wchar_t> >(loc).narrow(
str.c_str(), str.c_str() + str.size(), '?', &*result.begin());
return result;
}
It should use the current locale to convert the unicode string. For the caracters that do not belong in the codepage the '?' caracter is being used. Tested with Visual C++ 2005/2008.
|
1,525,535 | 1,525,546 | Delete all items from a c++ std::vector | I'm trying to delete everything from a std::vector by using the following code
vector.erase( vector.begin(), vector.end() );
but it doesn't work.
Update: Doesn't clear destruct the elements held by the vector? I don't want that, as I'm still using the objects, I just want to empty the container
| I think you should use std::vector::clear:
vec.clear();
EDIT:
Doesn't clear destruct the elements
held by the vector?
Yes it does. It calls the destructor of every element in the vector before returning the memory. That depends on what "elements" you are storing in the vector. In the following example, I am storing the objects them selves inside the vector:
class myclass
{
public:
~myclass()
{
}
...
};
std::vector<myclass> myvector;
...
myvector.clear(); // calling clear will do the following:
// 1) invoke the deconstrutor for every myclass
// 2) size == 0 (the vector contained the actual objects).
If you want to share objects between different containers for example, you could store pointers to them. In this case, when clear is called, only pointers memory is released, the actual objects are not touched:
std::vector<myclass*> myvector;
...
myvector.clear(); // calling clear will do:
// 1) ---------------
// 2) size == 0 (the vector contained "pointers" not the actual objects).
For the question in the comment, I think getVector() is defined like this:
std::vector<myclass> getVector();
Maybe you want to return a reference:
// vector.getVector().clear() clears m_vector in this case
std::vector<myclass>& getVector();
|
1,525,580 | 1,525,698 | Is there a BinaryReader in C++ to read data written from a BinaryWriter in C#? | I've written several ints, char[]s and the such to a data file with BinaryWriter in C#. Reading the file back in (in C#) with BinaryReader, I can recreate all of the pieces of the file perfectly.
However, attempting to read them back in with C++ yields some scary results. I was using fstream to attempt to read back the data and the data was not reading in correctly. In C++, I set up an fstream with ios::in|ios::binary|ios::ate and used seekg to target my location. I then read the next four bytes, which were written as the integer "16" (and reads correctly into C#). This reads as 1244780 in C++ (not the memory address, I checked). Why would this be? Is there an equivalent to BinaryReader in C++? I noticed it mentioned on msdn, but that's Visual C++ and intellisense doesn't even look like c++, to me.
Example code for writing the file (C#):
public static void OpenFile(string filename)
{
fs = new FileStream(filename, FileMode.Create);
w = new BinaryWriter(fs);
}
public static void WriteHeader()
{
w.Write('A');
w.Write('B');
}
public static byte[] RawSerialize(object structure)
{
Int32 size = Marshal.SizeOf(structure);
IntPtr buffer = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(structure, buffer, true);
byte[] data = new byte[size];
Marshal.Copy(buffer, data, 0, size);
Marshal.FreeHGlobal(buffer);
return data;
}
public static void WriteToFile(Structures.SomeData data)
{
byte[] buffer = Serializer.RawSerialize(data);
w.Write(buffer);
}
I'm not sure how I could show you the data file.
Example of reading the data back (C#):
BinaryReader reader = new BinaryReader(new FileStream("C://chris.dat", FileMode.Open));
char[] a = new char[2];
a = reader.ReadChars(2);
Int32 numberoffiles;
numberoffiles = reader.ReadInt32();
Console.Write("Reading: ");
Console.WriteLine(a);
Console.Write("NumberOfFiles: ");
Console.WriteLine(numberoffiles);
This I want to perform in c++. Initial attempt (fails at first integer):
fstream fin("C://datafile.dat", ios::in|ios::binary|ios::ate);
char *memblock = 0;
int size;
size = 0;
if (fin.is_open())
{
size = static_cast<int>(fin.tellg());
memblock = new char[static_cast<int>(size+1)];
memset(memblock, 0, static_cast<int>(size + 1));
fin.seekg(0, ios::beg);
fin.read(memblock, size);
fin.close();
if(!strncmp("AB", memblock, 2)){
printf("test. This works.");
}
fin.seekg(2); //read the stream starting from after the second byte.
int i;
fin >> i;
Edit: It seems that no matter what location I use "seekg" to, I receive the exact same value.
| You realize that a char is 16 bits in C# rather than the 8 it usually is in C. This is because a char in C# is designed to handle Unicode text rather than raw data. Therefore, writing chars using the BinaryWriter will result in Unicode being written rather than raw bytes.
This may have lead you to calculate the offset of the integer incorrectly. I recommend you take a look at the file in a hex editor, and if you cannot work out the issue post the file and the code here.
EDIT1
Regarding your C++ code, do not use the >> operator to read from a binary stream. Use read() with the address of the int that you want to read to.
int i;
fin.read((char*)&i, sizeof(int));
EDIT2
Reading from a closed stream is also going to result in undefined behavior. You cannot call fin.close() and then still expect to be able to read from it.
|
1,525,658 | 1,525,803 | Decryption with AES and CryptoAPI? When you know the KEY/SALT | Okay so i have a packed a proprietary binary format. That is basically a loose packing of several different raster datasets. Anyways in the past just reading this and unpacking was an easy task. But now in the next version the raster xml data is now to be encrypted using AES-256(Not my choice nor do we have a choice).
Now we basically were sent the AES Key along with the SALT they are using so we can modify our unpackager.
NOTE THESE ARE NOT THE KEYS JUST AN EXAMPLE:
They are each 63 byte long ASCII characters:
Key: "QS;x||COdn'YQ@vs-`X\/xf}6T7Fe)[qnr^U*HkLv(yF~n~E23DwA5^#-YK|]v."
Salt: "|$-3C]IWo%g6,!K~FvL0Fy`1s&N<|1fg24Eg#{)lO=o;xXY6o%ux42AvB][j#/&"
We basically want to use the C++ CryptoAPI to decrypt this(I also am the only programmer here this week, and this is going live tomorrow. Not our fault). I've looked around for a simple tutorial of implementing this. Unfortunately i cannot even find a tutorial where they have both the salt and key separately. Basically all i have really right now is a small function that takes in an array of BYTE. Along with its length. How can i do this?
I've spent most of the morning trying to make heads/tails of the cryptoAPI. But its not going well period :(
EDIT
So i asked for how they encrypt it. They use C#, and use RijndaelManaged, which from my knowledge is not equivalent to AES.
EDIT2
Okay finally got exactly what was going on, and they sent us the wrong keys.
They are doing the following:
Padding = PKCS7
CipherMode = CBC
The Key is defined as a set of 32 Bytes in hex.
The IV is defined as a set of 32 bytes in hex too.
They took away the salt when i asked them.
How hard is it to set these things in CryptoAPI using the wincrypt.h header file.?
| AES-256 uses 256 bit keys. Ideally, each key in your system should be equally likely. A 63 byte string would be 504 bits. You first need to figure out how the string of 63 characters needs to be converted to 256 bits (The sample ones you gave are not base64 encoded). Next, "salt" isn't an intrinsic part of AES. You might be referring to either an initialization vector (IV) in Cipher-Block-Chaining mode or you could be referring to somehow updating the key.
If I were to guess, I'm assuming that by "SALT" you mean IV and specifically CBC mode.
You will need to know all of this when using CAPI functions (e.g. decrypt).
If all of this sounds confusing, then it might be best to change your design so that you don't have to worry about getting all of this right. Crypto is hard. One bad step could invalidate all the security. Consider looking at this comment on my Stick Figure Guide to AES.
UPDATE: You can look at this for a rough starting point for C++ CAPI. You'll need a 64 character hex string to get 256 bits ( 256 bits / (4 bits / char) == 64 chars). You can convert the chars to bits yourself.
Again, I must caution that playing fast and loose with IV's and keys can have disastrous consequences. I've studied AES/Rijndael in depth down to the math and gate level and have even written my own implementation. However, in my production code, I stick to using a well-tested TLS implementation if at all possible for data in transit. Even for data at rest, it'd be better to use a higher level library.
|
1,525,764 | 16,634,045 | How to release pointer from boost::shared_ptr? | Can boost::shared_ptr release the stored pointer without deleting it?
I can see no release function exists in the documentation, also in the FAQ is explained why it does not provide release function, something like that the release can not be done on pointers that are not unique. My pointers are unique. How can I release my pointers ?
Or which boost smart pointer class to use that will allow me releasing of the pointer ?
I hope that you won't say use auto_ptr :)
| You need to use a deleter that you can request not to delete the underlying pointer.
See this answer (which has been marked as a duplicate of this question) for more information.
|
1,525,996 | 1,527,681 | How to Convert unicode version of ReadDirectoryChangesW | I need to convert Unicode version of ReadDirectoryChangesW to support multibyte is that possible
| You can cast a multi byte string into a unicode string by using this simple method
#include <string>
#include <sstream>
template <typename inputtype>
std::wstring toUTF16String(const inputtype& input)
{
std::wstringstream ss;
ss << input;
return ss.str();
}
You can then use this acquired value in the unicode function.
|
1,526,053 | 1,527,321 | Constructing a C++ object (the MFC CRecordset) thread-safely | We're trying to build a class that provides the MFC CRecordset (or, really, the CODBCRecordset class) thread safety. Everything actually seem to work out pretty well for the various functions like opening and moving through the recordset (we enclose these calls with critical sections), however, one problem remains, a problem that seems to introduce deadlocks in practice.
The problem seems to lie in our constructor, like this:
CThreadSafeRecordset::CThreadSafeRecordset(void) : CODBCRecordset(g_db)
{ // <-- Deadlock!
}
The other thread might be one having ended up in CThreadSafeRecordset::Close() despite us guarding the enclosed Close call, but that doesn't really matter since the constructor is threading unaware. I assume the original CRecordset class is the culprit, doing bad things at construction time. I've looked around for programming techniques to work around this problem, but I'm unsure what could be the best solution? Since we have no code and can't control other code in our constructor, we can't wrap anything special in a critical section...?
Update: Thanks for the input; I've marked what I ended up with as the answer to my question. That, in combination with returning a shared_ptr as the returned instance for ease of updating the existing thread-unaware code.
| You can make the CThreadSafeRecordset constructor private, then provide a public factory method that participates in your locking and returns an instance.
|
1,526,074 | 1,526,552 | How do I use C++ to acquire image from frame grabber? | I would like to know how is it possible to use a free C++ program to acquire image from a matrix vision frame grabber. Thanks.
| See http://www.matrix-vision.com/support/hardwareinfo.php?lang=en
|
1,526,531 | 1,526,915 | Wildcard search inside a Boost.MultiIndex data structure? | I'm trying to optimize my application by reducing round-trips to my database. As part of that effort, I've been moving some of the tables into memory, storing them as Boost.MultiIndex containers.
As a side-effect of this process, I've lost the ability to do wild-card matching on my strings. For example, when the table was stored in MySQL, I could do this:
SELECT * FROM m_table WHERE myString LIKE "foo%"
However, since I'm now using a Boost.MultiIndex container with a key of myString, it seems I've lost that ability.
Obviously, I can use the equal_range() function in order to find all entries that match a specific string exactly:
std::pair< typename T::template index<by_name>::type::iterator,
typename T::template index<by_name>::type::iterator > p
= m_table.get<by_name>().equal_range(myString);
while (p.first != p.second )
{
// do something with the EXACT matching entry
++p.first;
}
But it seems like the only way to do a wild-card match is to walk the entire structure and compare each key to a boost::regex with boost::regex_match().
std::pair< typename T::template index<by_name>::type::iterator,
typename T::template index<by_name>::type::iterator > p
= std::make_pair(m_table.get<by_name>().begin(),m_table.get<by_name>().end());
while (p.first != p.second )
{
boost::regex e(myRegex);
if ( boost::regex_match(p.first->myString, e ) )
{
// Do something with the REGEX matching entry
}
++p.first;
}
Is there a better way?
| Well, first you don't actually have to use a boost::regex, if the wildcard is simple enough, you can get away by rolling you own unary operator. I would note that Boost.Regex is one of the few part of the library which actually requires to be linked (not header-only).
As for the problem of walking the whole structure, I am sorry but there is not much one can do you here... if you don't know the searches in advances.
If you know the parameters that you would be looking for in advance, then you can create a special view of the Multi-Index container suited to perform this task with a dedicated comparator/hasher (for example, one that only takes into account the first 3 characters).
If you were hoping for more, please provide more information regarding the kind of wildcards you want to use and the circumstances.
|
1,526,539 | 1,775,982 | VXL: Run-Time Check Failure #2 | With the VXL library:
I'm using vnl_conjugate_gradient with VC8 (visual studio 2005) and
occasionally I see this error in debug mode:
Run-Time Check Failure #2 - Stack around the variable 'z__' was corrupted.
This is happening while leaving the function cg_ in the file cg.c
This function is literally packed with "goto" btw, could that be the culprit??
Any idea?
PS: Callstack:
vision.dll!v3p_netlib_cg_(double * x=0x01d6b040, double *
e=0x0012f1d4, long * it=0x0012f1c8, double * step=0x01d698b8, double *
t=0x0012f1b8, long * limit=0x01d69868, long * n=0x0012f19c, long *
m=0x0012f19c, double (double *, void ) value=0x00f2a9e0, void
(double *, double *, void ) grad=0x00f2aae0, void (double *, double
*, double *, void ) both=0x00f2abf0, void (double *, double *, void
) pre=0x00f2ad00, double * h__=0x01d6b080, void *
userdata=0x01d69858, long * error_code=0x0012f190) Line 1128 + 0xf
bytes C
vision.dll!vnl_conjugate_gradient::minimize(vnl_vector & x={...}) Line 171 + 0x50 bytes C++
| That was due to the cost function returning NAN.
|
1,526,546 | 1,526,566 | C++ using list with count() function | I have a list L which needs to count how many 1s it has in it.
list<int> L;
L.push_back(14); L.push_back(5); L.push_back(22);
L.push_back(1); L.push_back(1); L.push_back(-7);
the function that i have been given is :
assert ( count(...,...,...) == 2);
i need to know what would replace the ...'s.
i have tried L.begin(), L.end(), 1 to replace the ...'s but it keeps giving me an error saying that is not allowed. So i need to replace the ...'s without adding any extra code.
this is the error that i have been getting:
error C2782:
'iterator_traits<_Iter>::difference_type
std::count(_InIt,_InIt,const _Ty &)' :
template parameter '_InIt' is
ambiguous
Here is the exact code & error.
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <cassert>
using namespace std;
int main()
{
int A1[6] = {15,8,10,9,12,13};
vector<int> V(A1, A1+6);
list<int> L;
L.push_back(14); L.push_back(5); L.push_back(22);
L.push_back(1); L.push_back(1); L.push_back(-7);
count(L.begin(), L.end(), 1);
}
error C2782:
'iterator_traits<_Iter>::difference_type
std::count(_InIt,_InIt,const _Ty &)' :
template parameter '_InIt' is
ambiguous
c:\program files\microsoft visual
studio 9.0\vc\include\algorithm(160) :
see declaration of 'std::count' 1>
could be 'unsigned int'
| it should be std::count(L.begin(), L.end(), 1) so if this doesn't work all I can say is make sure you #include <algorithm>.
This code compiles for me in VS2008:
#include <list>
#include <algorithm>
#include <cassert>
using namespace std;
int main()
{
list<int> L;
L.push_back(14); L.push_back(5); L.push_back(22);
L.push_back(1); L.push_back(1); L.push_back(-7);
assert( count(L.begin(), L.end(), 1) == 2);
}
|
1,526,625 | 1,526,674 | Storing a list of classes and specialising a function by sub-classing in C++? | I'm trying to subclass a class with a specialisation of how I want a particular function to be performed. However, C++ implicitly converts my class to its base class when I store it in a list. Clearly the list could store any subclass of the class, so this is acceptable, but how would I go about storing the class so I can access this particular function.
The only way I can think of doing this is to use templates, are there any other options?
Here is an example:
class A
{
A() {}
virtual void function()
{
}
}
class B : public A
{
B() {}
void function()
{
}
}
boost::shared_ptr<B> b = boost::shared_ptr<B>(new b);
std::list<boost::shared_ptr<A> > objects;
objects.push_back(b);
// pull t out of objects
t.function();
Edit: Oversimplified this, so I've fixed a few things...
| This is a phenomenon called slicing. The answer is to store a container of pointers instead, such as std::list<A*>. Just remember to delete everything when you're done.
If you can use the Boost libraries, there is a great library called Pointer Container which helps with this procedure.
|
1,526,792 | 1,526,820 | Help combining two functions in C++ | I need to combine these two functions.
and need help in so:
int Triangle(GzRender *render, int numParts, GzToken *nameList,GzPointer *valueList)
{
if (on_screen)
{
return Position(render, pos);
}
}
int Position(GzRender *render, GzCoord vertexList[3])
{
GzCoord *pv[3];
int i,j;
pv[0] = &vertexList[0];
pv[1] = &vertexList[1];
pv[2] = &vertexList[2];
//more function code in here
}
Can anyone help me with this.
Regards
| Normally, separating out functions is a better, more common practice (and one of the main tasks during refactoring). That being said, you can "combine" these simply by doing:
int Triangle(GzRender *render, int numParts, GzToken *nameList,GzPointer *valueList)
{
if (on_screen)
{
//function code in here, working on "pos" instead of vertexList
// return value
}
// return some other value here?
}
|
1,526,912 | 1,526,972 | Impossibly Fast C++ Delegates and different translation units | According to Sergey Ryazanov, his Impossibly Fast C++ Delegates are not comparable:
My delegates cannot be compared. Comparison operators are not defined because a delegate doesn't contain a pointer to method. Pointer to a stub function can be different in various compilation units.
To which one the readers have replied:
"Pointer to a stub function can be different in various compilation units."
AFAIK, this is not true. Compilers are required to re-use template functions generated in different compilation units (this I am sure of - but I think Borland once violated this rule). I think it is because classes (ones not in 'nameless' namespaces) use external linkage and the way you use the stub functions will always prevent them from being inlined (although this shouldn't be an issue either as taking the address of the function will force a non-inline version to be generated and 'external linkage' performed by the linker will eliminate all but one similarly named function (they are assumed and required to be identical by the standard))...
If you define a template function one translation unit (cpp file) and then define the same function differently in another translation unit, only one of the two versions will make it into the final executable. (This actually violates the "One Definition Rule", but works on GCC, at least... not sure about MSVC.) The point is: the address [of the stub] will be the same in different units.
I would urge you to update the article (including comparison capability) if you find this to be true for MSVC - if MSVC is standards conferment, in this regard.
Now the article is four years old and the author hasn't replied to any of the comments during the past three years or so, so I'm wondering if there's any merit to the above comment and whether this specific implementation can indeed be changed to support comparisons.
Does the C++ standard specifically prohibit such usage and if so, are any of the recent compilers actually standard-compliant in that regard?
| The code is both standard compliant, and fine. I don't see any place where he violates ODR, and it is true that all instantiations of a function template with the same template parameters should have "the same address" (in a sense that pointers to functions should all be equal) - how this is achieved is not important. ISO C++03 14.5.5.1[temp.over.link] describes the rules in more detail.
So, a comparison could well be defined there in a conformant and portable way.
|
1,526,982 | 1,527,164 | AIR(Flex) local socket connection | When connecting from a local AIR/Flex application to a local application (c++) using sockets do you still need a socket policy file? If you do, is there an easy way to load the policy file without sending the policy from the local application you are trying to connect to? side note: I am writing both applications.
| When connecting to another application on the localhost using sockets, you do not need to use a socket policy.
|
1,527,039 | 1,527,579 | How to write directly to linux framebuffer? | How to write directly to linux framebuffer?
| look at FBIOPUT_VSCREENINFO, ioctl and mmap
(I have the code but not at this pc, sorry)
edit: this should get you started
//open file descriptor and get info
inf fdScreen = open( "devicename", O_RDWR );
fb_var_screeninfo varInfo;
ioctl( fdScreen, FBIOGET_VSCREENINFO, &varInfo );
//set resolution/dpi/color depth/.. in varInfo, then write it back
ioctl( fdScreen, FBIOPUT_VSCREENINFO, &varInfo );
//get writable screen memory; unsigned short here for 16bit color
unsigned short* display = mmap( 0, nScreenSize,
PROT_READ | PROT_WRITE, MAP_SHARED, fdScreen, 0 );
|
1,527,227 | 1,527,270 | C++ writing a modify_if function | I have a hw question which confuses me on what i have to do. The question is below:
The idea is to design a generic function called Modify_If that will take an input x (passed by reference), and two functors f1 and f2. The function Modify_If will use functor f1 to determine whether x obeys a certain condition. If it does, Modify_if will change the value of x, by applying functor f2 to it.
The prototype for Modify_If is as follows:
template <class C, class Tester, class Transform>
void Modify_If(C & a, Tester f, Transform g)
I have to write the Modify_If function but I have no idea where to start so if anyone can help me out I would appreciate it.
| template <class C, class Tester, class Transform>
void Modify_If(C& a, Tester f1, Transform f2) {
if (f1(a)) // Apply f1 to a - Check whether result is true
a = f2(a); // Transform with f2; save
}
|
1,527,367 | 1,527,401 | Redirect cout to a file vs writing to a file directly in linux | For C++/linux programs, how does writing to cout (when cout has been redirected to a file during program launch) compare against writing to the target file directly? (via say fstream)
Does the system do the appropriate magic at the start of the program to make these two cases exactly equivalent or is the later gonig to be better than the first?
Thanks!
| They are basically equivalent. In both cases, the underlying stream buffer will end up calling the write() system call, for the same effect.
Note however that by default, cout is synchronized to stdio, for backwards compatibility (so you can use C-style standard output as well as cout, and have it work as expected). This additional synchronization can slow down C++ output. If this is important, then you can use std::ios_base::sync_with_stdio(false) to unlink them. Then, a file-redirected cout and an fstream should have essentially identical performance and function.
|
1,527,383 | 1,527,756 | A way to destroy "thread" class | Here is a skeleton of my thread class:
class MyThread {
public:
virutal ~MyThread();
// will start thread with svc() as thread entry point
void start() = 0;
// derive class will specialize what the thread should do
virtual void svc() = 0;
};
Somewhere in code I create an instance of MyThread and later I want to destroy it.
In this case MyThread~MyThread() is called. MyThread:svc() is still running and using the object's data members. So I need a way politely inform MyThread:svc() to stop spinning, before proceeding with the destructor.
What is the acceptable way to destroy the thread object?
Note: I'm looking for platform agnostic solution.
UPD: It's clear that the root of problem is that there's no relationship between C++ object representing thread and OS thread. So the question is: in context of object destuction, is there an acceptable way to make thread object behave like an ordinary C++ object or should it be treated as an unusual one (e.g. should we call join() before destoying it?
| Considering your additional requirements posted as comment to Checkers' reply (which is the
most straightforward way to do that):
I agree that join in DTor is problematic for various reasons. But from that the lifetime of your thread object is unrelated to the lifetime of the OS thread object.
First, you need to separate the data the thread uses from the thread object itself. They are distinct entities with distinct lifetime requirements.
One approach is to make the data refcounted, and have any thread that wants to access it hold a strong reference to the data. This way, no thread will suddenly grab into the void, but the data will be destroyed as soon as noone touches it anymore.
Second, about the thread object being destroyed when the thread joins:
I am not sure if this is a good idea. The thread object is normally a way to query the state of a thread - but with a thread object that dies as soon as the thread finishes, noone can tell you wether the thread finished.
Generally, I'd completely decouple the lifetime of the thread object from the lifetime of the OS thread: Destroying your thread object should not affect the thread itself. I see two basic approaches to this:
Thread Handle Object - reference counted again, returned by thread creator, can be released as early as one likes without affecting the OS thread. It would expose methods such as Join, IsFinished, and can give access to the thread shared data.
(If the thread object holds relevant execution state, the threafFunc itself could hold a reference to it, thereby ensuring the instance won't be released before the thread ends)
Thin Wrapper - You simply create a temporary around an OS thread handle. You could not hold additional state for the thread easily, but it might be just enough to make it work: At any place, you can turn an OS thread handle into an thread object. The majority of communication - e.g. telling the thread to terminate - would be via the shared data.
For your code example, this means: separate the start() from the svc()
You'd roughly work with this API (XxxxPtr could be e.g. boost::shared_ptr):
class Thread
{
public:
bool IsFinished();
void Join();
bool TryJoin(long timeout);
WorkerPtr GetWorker();
static ThreadPtr Start(WorkerPtr worker); // creates the thread
};
class Worker
{
private:
virtual void Svc() = 0;
friend class Thread; // so thread can run Svc()
}
Worker could contain a ThreadPtr itself, giving you a guarantee that the thread object exists during execution of Svc(). If multiple threads are allowed to work on the same data, this would have to be a thread list. Otherwise, Thread::Start would have to reject Workers that are already associated with a thread.
Motivation: What to do with rogue threads that block?
Assuming a thread fails to terminate within time for one reason or another, even though you told it to. You simply have three choices:
Deadlock, your applicaiton hangs. That usually happens if you join in the destructor.
Violently terminate the thread. That's potentially a violent termination of the app.
Let the thread run to completion on it's own data - you can notify the user, who can safely save & exit. Or you simply let the rogue thread dance on it's own copy of the data (not reference by the main thread anymore) until it completes.
|
1,527,496 | 1,527,504 | Header file without source file | I have written the body of the function in the header file and so do not have a source file. when I tried running my project in visual studio .. I got an
error: Cannot open source file: No such file or directory.
How do I make visual studio understand that the definitions of the function are within the header itself?
| You need to create a dummy source.cpp file just containing #include "source.h"
edit - I just tried this - Visual studio will let you do.
test.cpp
#include "test.h"
where test.h
#include "stdio.h"
int main()
{
printf("hello world");
return 0;
}
Interesting - but pointless !
|
1,527,680 | 4,564,433 | Determining maximum possible alignment in C++ | Is there any portable way to determine what the maximum possible alignment for any type is?
For example on x86, SSE instructions require 16-byte alignment, but as far as I'm aware, no instructions require more than that, so any type can be safely stored into a 16-byte aligned buffer.
I need to create a buffer (such as a char array) where I can write objects of arbitrary types, and so I need to be able to rely on the beginning of the buffer to be aligned.
If all else fails, I know that allocating a char array with new is guaranteed to have maximum alignment, but with the TR1/C++0x templates alignment_of and aligned_storage, I am wondering if it would be possible to create the buffer in-place in my buffer class, rather than requiring the extra pointer indirection of a dynamically allocated array.
Ideas?
I realize there are plenty of options for determining the max alignment for a bounded set of types: A union, or just alignment_of from TR1, but my problem is that the set of types is unbounded. I don't know in advance which objects must be stored into the buffer.
| In C++0x, the Align template parameter of std::aligned_storage<Len, Align> has a default argument of "default-alignment," which is defined as (N3225 §20.7.6.6 Table 56):
The value of default-alignment shall be the most stringent alignment requirement for any C++ object type whose size is no greater than Len.
It isn't clear whether SSE types would be considered "C++ object types."
The default argument wasn't part of the TR1 aligned_storage; it was added for C++0x.
|
1,527,849 | 1,527,910 | How do you understand dependent names in C++ | I come across this term "dependent names" typically in the context of templates. However, I rarely touch the latter. Thus naturally would like to know more about the concept of dependent names.
How do you understand it in the context of templates and outside of them? example are critically encouraged!
| A dependent name is essentially a name that depends on a template argument.
When using templates there is a distinction between the point of definition of the template and the point of instantiation i.e. where you actually use the template. Names that depend on a template don't get bound until the point of instantiation whereas names that don't get bound at the point of definition.
A simple example would be:
template< class T > int addInt( T x )
{
return i + x.toInt();
}
where a declaration or definition of i would need to appear before the definition given above since i does not depend on the template argument T and is therefore bound at the point of definition. The definition of the toInt member of the as-yet-unknown-type x variable only has to appear before the addInt function is actually used somewhere as it is a dependent name ( technically the point of instantiation is taken as the nearest enclosing global or namespace scope just before the point of use and so it has to be available before that ).
|
1,527,969 | 1,527,985 | File echo loop with extra final iteration | Why do I get an extra iteration (extra line printed) when this code completes? Does there need to be an extra newline at the EOF? I would prefer not having to add extra/special characters to mark the EOF.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ifstream infile("dictionary.txt"); // one word per line
string text;
while(infile){
infile >> text;
cout << text << endl;
}
infile.close();
return 0;
}
| try
while(infile>>text) cout << text << endl;
instead.
|
1,528,144 | 1,528,432 | OpenGL 3.2 Programming Guide? | Most resources available online are very outdated. Specifically, they are all about OpenGL 2 which matches to DirectX 9.
The current specification is 3.2 which is equivalent (or, well, very close) to DirectX 10 (11). But the specification itself is very hard to read. In contrast, DirectX SDK is a wonderful piece of documentation, samples, and tools.
Where I can get the programming guide for OpenGL, that is not outdated? Where can I get the samples? And so on.
| The OpenGL Technical Wiki is a starting point. It also contains some OpenGL 3.2 tutorials. Don't expect anything like the DirectX SDK, but afaik there's no better resource. OpenGL learning seems to be more like a trial and error process, where the developer forum is especially helpful.
|
1,528,292 | 1,528,356 | C++: Casting for user defined types | How can I get the same handeling of casting for user-defined types as built in, eg:
float a = 5.4;
std::string s = a;//error, no conversion avaible
int x = a;//warning, possible data loss
int y = (int)a;//fine
int z = static_cast<int>a;//fine
float b = c;//warning, possible data loss
Now say I have my own Int and Float class, how do I go about getting the same errors and warnings?
class Int
{
public:
int value;
Int(int v);
...
};
class Float
{
public:
float value;
Float(float v);
...
};
Int c = 10;
Float a = 5.5;
std::string s = a;
Int x = a;
Int y = (Int)a;
Int z = static_cast<Int>a;
Float b = c;
I'm aware of creating overloaded cast operators, and using constructors, however I don't know how to make this work correctly for implicit and explicit casts, eg consider. If I dont add explicit casts within those methods, then I get a warning when there compiled but not when their call, and if I do, then I don't get an error within the classes code, but I still don't get a warning when there used either.
I'm guessing there is some way as to mark the cast operator as explicit, so that a warning is generated if it tries to cast implicitly, but not with explicit (either C-Style or static_cast) casts)
EDIT:
Ok I think I get it for cases like this where all types in question are fully, known, but what about times when one or both are templates, and that neither types map onto a built-in type?
template<typename T> class Vector2
{
public:
T x, y;
Vector2():x(0),y(0){}
Vector2(T x, T y):x(x),y(y){}
//Works as expected, warning if adding T and T2 is unsafe, or error if
//incompatible*/
template<typename T2>Vector2<T>& operator += (const Vector2<T2> &v);
//Also works as desired
Vector2<T>& operator *= (T s);
//allows the conversion, but always generates warnings if
//T and T2 would, even if this constructor is used by an explicit
//case. How can I suppress the warnings for the explicit cast, but
//not for implicit casts?
template<typename T2>Vector2(const Vector2<T2> &v);//uses implicit conversion form T2 to T
};
An implicit cast from say Vector2 to Vector2 works as expected, but the cast from say Vector2 to Vector2 always causes (2, one for x and one for y) warnings, even if a explicit C-Style or static_cast was used. I want to keep the warnings for the implicit cast, but not the explicit casts.
I know I could hack around this be creating a special T vector_cast(T2) type method that uses explicit casts for each element internally, but Id rather be able to use the C-Style and static_casts
| I don't think there's a way, either. The best I could achieve is so that the line that you want to generate a warning doesn't compile at all.
class Int
{
public:
int value;
Int(int v);
};
class Float
{
public:
float value;
Float(float v);
operator int() { return static_cast<int>(value); }
};
int main()
{
Float a = 5.5;
//Int x = a; //no warning, simply doesn't compile
Int y = (int)a;
Int z = static_cast<int>(a);
}
Edit: regarding your question about Vector2
One thing to do might be to disable all implicit conversions between different Vector2 types. As a short-cut you might provide a vector_cast to allow explicit conversions:
template <class T, class S>
Vector2<T> vector_cast(const Vector2<S>& s)
{
return Vector2<T>(static_cast<T>(s.x), static_cast<T>(s.y));
}
Another thing might be to bring in some template metaprogramming, to enable conversion constructor for safe conversions.
It seems to me that boost doesn't contain such a type_trait, hence I rolled my own.
It is somewhat simplified: Target must be at least as large as Source, and Target must not be integral if Source is floating point. However, it disregards issues of signedness, and the question whether a floating-point type can represent the full range of an integer type (e.g float cannot store all 32-bit ints precisely, but double can).
#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>
template <class S, class T>
struct is_safe_conversion:
boost::integral_constant<
bool,
(sizeof(S) <= sizeof(T)) && !(boost::is_floating_point<S>::value && boost::is_integral<T>::value)
>
{
};
template<typename T> class Vector2
{
public:
T x, y;
Vector2():x(0),y(0){}
Vector2(T x, T y):x(x),y(y){}
template <class U>
Vector2(const Vector2<U>& other, typename boost::enable_if<is_safe_conversion<U, T> >::type* = 0):
x(other.x), y(other.y) {}
};
template <class T, class S>
Vector2<T> vector_cast(const Vector2<S>& s)
{
return Vector2<T>(static_cast<T>(s.x), static_cast<T>(s.y));
}
int main()
{
Vector2<double> vd, vd2;
Vector2<int> vi, vi2;
Vector2<float> vf, vf2;
vd = vd2;
vd = vi;
vd = vf;
//vi = vd; //error
vi = vector_cast<int>(vd);
vi = vi2;
//vi = vf; //error
vi = vector_cast<int>(vf); //explicit
//vf = vd; //error
vf = vector_cast<float>(vd);
//following compiles, but produces a warning (float cannot represent all integers)
//TODO: enhance is_safe_conversion!
vf = vi;
vf = vf2;
}
|
1,528,298 | 1,528,493 | Get path of executable | I know this question has been asked before but I still haven't seen a satisfactory answer, or a definitive "no, this cannot be done", so I'll ask again!
All I want to do is get the path to the currently running executable, either as an absolute path or relative to where the executable is invoked from, in a platform-independent fashion. I though boost::filesystem::initial_path was the answer to my troubles but that seems to only handle the 'platform-independent' part of the question - it still returns the path from which the application was invoked.
For a bit of background, this is a game using Ogre, which I'm trying to profile using Very Sleepy, which runs the target executable from its own directory, so of course on load the game finds no configuration files etc. and promptly crashes. I want to be able to pass it an absolute path to the configuration files, which I know will always live alongside the executable. The same goes for debugging in Visual Studio - I'd like to be able to run $(TargetPath) without having to set the working directory.
| There is no cross platform way that I know.
For Linux: pass "/proc/self/exe" to std::filesystem::canonical or readlink.
Windows: pass NULL as the module handle to GetModuleFileName.
|
1,528,359 | 1,542,559 | Floating point stack handling with floating-point exceptions turned on | I'm running into an issue with floating point exceptions turned on in Visual Studio 2005. If I have code like this:
double d = 0.0;
double d2 = 3.0;
double d3 = d2/d;
and if I register an SEH handler routine, then I can easily turn the div-by-zero into a C++ exception and catch it. So far so good.
However, when I do this, the first operand (0.0 in the example above) is left on the FPU register stack. If I do it eight times, then I'll start getting a floating point stack check exception with EVERY floating point operation from then on.
I can deal with this using an __asm block to execute a FSTP, thus popping the stray value off the stack, and everything is fine.
However, this worries me, because I haven't seen this discussed anywhere. How can I be certain about the number of values that I should pop? Is it safe to just pop everything that's on the stack at the time of the exception? Are there any recommended best practices in this area?
Thanks!
| While I can't find anything either, I can give some explanation as to the likely answer:
The ABI defines that upon a function call the stack should be empty, and it should be empty again on exit unless the return is a floating point value, where it would be the only item on the stack.
Since the exception handler must be able to return to any place, some criteria must hold on those locations. The question here is, does the stack unwinder have any knowledge of the FPU stack of the function having the catch()? Most likely, the answer is no because it is easier and faster to create a suitable return point with fixed properties than to include the full FPU stack in the unwinding.
Which leads to your problem - normally raising an exception has the compiler take care of the FPU being empty, but in an SEH handler, the compiler has no clue it caused an entry into another function, and thus can't take care of things just in case. (other than it being again hideously slow)
Which means that most likely, the FPU stack should be in its "consistent" state upon return, which means you probably want an equivalent of an EMMS instruction.
Why EMMS? Well, unless it is not supported it does the following:
clear the stack (which fixes all leftover floating point arguments)
clears the stack tags (which fixes an unusable stack when exiting from an MMX-enabled function)
If you want to support Pentium 1 or worse, you may of course if() around the EMMS and use something else instead.
No guarantees of course, but I hope I explained the why of the likely answer sufficiently.
|
1,528,374 | 1,528,436 | How can I extend a lexical cast to support enumerated types? | I have the following function that will convert a string into a numeric data type:
template <typename T>
bool ConvertString(const std::string& theString, T& theResult)
{
std::istringstream iss(theString);
return !(iss >> theResult).fail();
}
This does not work for enumerated types, however, so I have done something like this:
template <typename T>
bool ConvertStringToEnum(const std::string& theString, T& theResult)
{
std::istringstream iss(theString);
unsigned int temp;
const bool isValid = !(iss >> temp).fail();
theResult = static_cast<T>(temp);
return isValid;
}
(I'm making the assumption that theString has a valid value for the enumerated type; I'm using this mainly for simple serialization)
Is there a way to create a single function that combines both of these?
I've played a bit with the template arguments but haven't come up with anything; it'd just be nice not to have to call one function for enumerated types and another for everything else.
Thank you
| You have to do two steps. Finding an integral type large enough to store the values. You could use unsigned long, but the values could be negative. Then you could use long but the values could extend into the range of unsigned long. So there is not really a fit-it-all type.
There is a trick though, by using overload resolution. Here is it
template<typename T>
struct id { typedef T type; };
id<char[1]>::type &find_etype(int);
id<char[2]>::type &find_etype(unsigned int);
id<char[3]>::type &find_etype(long);
id<char[4]>::type &find_etype(unsigned long);
You can change it appropriately to cover also long long or unsigned long long if your implementation has support for that. Now, passing an enum type will prefer one of these over all the other ones - that's a type that can store all values of it. You just need to pass sizeof of the return type to some template.
template<int> struct get_etype;
template<> struct get_etype<1> { typedef int type; };
template<> struct get_etype<2> { typedef unsigned int type; };
template<> struct get_etype<3> { typedef long type; };
template<> struct get_etype<4> { typedef unsigned long type; };
Now, you can get a right type. All you need now is to see whether some type is an enumeration. How to do this is described in the book "C++ Templates - The complete Guide", and unfortunately is a whole lot of code. So i would use boost's is_enum. Putting it together, it could look like
template <typename T>
typename boost::disable_if< boost::is_enum<T>, bool>::type
ConvertString(const std::string& theString, T& theResult)
{
std::istringstream iss(theString);
return !(iss >> theResult).fail();
}
template <typename T>
typename boost::enable_if< boost::is_enum<T>, bool>::type
ConvertString(const std::string& theString, T& theResult)
{
typedef typename get_etype<sizeof find_etype(theResult)>::type
safe_type;
std::istringstream iss(theString);
safe_type temp;
const bool isValid = !(iss >> temp).fail();
theResult = static_cast<T>(temp);
return isValid;
}
Hope this helps.
|
1,528,419 | 1,528,511 | Templates and headers question | The compiler says it can't find the reference for the function when I do this:
// link.h
template <class T>
T *Link(T *&, T *(*)())
// link.cpp
template <class T>
T c:Link(T *&ChildNodeReference, T *(*ObjectCreator)()){
}
If I implement inside the class on the header it goes smoothly.
Please, I will work on the header until someone enlightens me about this.
There are somethings in C++ that are weirdly annoying. I know, there is a reason for this and etc. Even so, can't the compilers help you out about it -_-"
| Programming non-template code or non-inlined functions in headers is a Bad Thing™. The reason you have cpp files is to prevent redefinition of the same function code more than once, amongst other things.
The difference with templates is that the compiler practically doesn't touch them until your code instantiates a specialisation of that template which is why they need to have their source inside the header.
When the compiler finds an instantiation of a template specialisation (say List<int>), it goes back to the included template code and compiles it with that specialisation, which is why you don't have issues with redefinition of function code.
What you don't seem to understand is that this doesn't apply to non-templated code. All non-template code is compiled as normal and thus CPP files are needed to only define the code once then link it all together.
If you define functions inside a header, your linker will not link the compiled translation units because they have defined the same function more than once.
|
1,528,567 | 1,528,635 | C++ templated functors | I was wondering if anyone can help me with functors. I dont really understand what functors are and how they work I have tried googling it but i still dont get it. how do functors work and how do they work with templates
| A functor is basically a "function object". It's a single function which you have wrapped in a class or struct, and which you can pass to other functions.
They work by creating your own class or struct which overloads the function call operator (called operator() ). Typically, you create an instance of it by simply constructing it in-place as an argument to your function which takes a functor.
Suppose you have the following:
std::vector<int> counts;
Now, you want to increment all the counts that are contained in that vector. You could loop through them manually to increment them, or you could use a functor. A suitable functor, in this case, would look like this:
struct IncrementFunctor
{
int operator() (int i)
{
return i + 1;
}
}
IncrementFunctor is now a functor which takes any integer and increments it. To apply it to counts, you can use the std::transform function, which takes a functor as an argument.
std::transform(
counts.begin(), // the start of the input range
counts.end(), // the end of the input range
counts.begin(), // the place where transform should place new values.
// in this case, we put it right back into the original list.
IncrementFunctor()); // an instance of your functor
The syntax IncrementFunctor() creates an instance of that functor which is then passed directly to std::transform. You could, of course, create an instance as a local variable and pass it on, but this is much more convenient.
Now, onto templates. The type of the functor in std::transform is a template argument. This is because std::transform does not know (or care!) of which type your functor is. All it cares about is that it has a fitting operator() defined, for which it can do something like
newValue = functor(oldValue);
The compiler is pretty smart about templates, and can often figure out on its own what the template arguments are. In this case, the compiler realizes automatically that you're passing in a parameter of type IncrementFunctor, which is defined as a template type in std::transform. It does the same for the list, too, so the compiler automatically recognizes that the actual call would look like this:
std::transform<std::vector<int>::iterator, // type of the input iterator
std::vector<int>::iterator, // type of the output iterator
IncrementFunctor>( // type of your functor
counts.begin(), // the start of the input range
counts.end(), // the end of the input range
counts.begin(), // the place where transform should place new values.
// in this case, we put it right back into the original list.
IncrementFunctor()); // an instance of your functor
It saves you quite a bit of typing. ;)
|
1,528,685 | 1,532,179 | Qt QPlainTextEdit background | I want to change the background color of a QPlainTextEdit, how do I do this?
| Modify the palette of your plain text edit. Sample program:
#include <QApplication>
#include <QPlainTextEdit>
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QPlainTextEdit edit;
QPalette p = edit.palette();
p.setColor(QPalette::Active, QPalette::Base, Qt::red);
p.setColor(QPalette::Inactive, QPalette::Base, Qt::red);
edit.setPalette(p);
edit.show();
return app.exec();
}
Substitute whatever color you want, of course.
|
1,528,691 | 8,508,658 | Idiomatic way to do list/dict in Cython? | My problem: I've found that processing large data sets with raw C++ using the STL map and vector can often be considerably faster (and with lower memory footprint) than using Cython.
I figure that part of this speed penalty is due to using Python lists and dicts, and that there might be some tricks to use less encumbered data structures in Cython. For example, this page (http://wiki.cython.org/tutorials/numpy) shows how to make numpy arrays very fast in Cython by predefining the size and types of the ND array.
Question: Is there any way to do something similar with lists/dicts, e.g. by stating roughly how many elements or (key,value) pairs you expect to have in them? That is, is there an idiomatic way to convert lists/dicts to (fast) data structures in Cython?
If not I guess I'll just have to write it in C++ and wrap in a Cython import.
| Cython now has template support, and comes with declarations for some of the STL containers.
See http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html#standard-library
Here's the example they give:
from libcpp.vector cimport vector
cdef vector[int] vect
cdef int i
for i in range(10):
vect.push_back(i)
for i in range(10):
print vect[i]
|
1,528,917 | 1,529,010 | Decrypting data files with wincrypt. Having trouble. Example shows CBase64Utils? | I need to decrypt some data files with wincrypt and examples are few and far between online. The most solid example I've found is here. However, this is using all sorts of types I cannot seem to find information about (CBase64Utils, CString, etc).
I am reading the final solution, trying to understand the process, and have come to this:
// 5. Determine the LENGTH of the BUFFER to hold the corresponding cyphertext.
CBase64Utils bu;
int ipszSourceLen = strlen(pszSource);
char *pszSource2 = bu.Decode(pszSource, &ipszSourceLen);
DWORD dwSourceLen = strlen(pszSource2); // Get the length of the input string.
DWORD dwDataLen = dwSourceLen;
BYTE* pTarget = NULL;
DWORD dwCryptDataLen = dwDataLen;
CryptEncrypt(hKey, 0, TRUE, 0, NULL, &dwCryptDataLen, dwDataLen);
This is pure chinese to me. Can anybody make sense of it and hopefully clear some muddy waters? Thanks
| The code you linked is horrible. It appears the fellow wrote his encrypt method, and then subsequently wrote his decrypt method simply by copying and pasting the first method and making a few changes (yet leaving a ton of code left over from the encryption process). I wouldn't be surprised if it works, it's just that it wastes time and space doing useless work left over from encryption (plus the comments are all backwards).
As wincrypt is a Microsoft library, there are plenty of examples over at the MSDN. As MSDN samples are (usually) well-written and well-commented, they should be much easier to understand, so I would recommend you look at them instead.
|
1,528,981 | 1,529,048 | Garbage values when C++ Operator Overloading | Im just getting garbage values. And it is wierd the debugger shows the correct values. But its printing weird stuff insted...
this frist part is fine. Essentially, It just takes me to my problem. I have what I need to print inside that h.hashtable[hashIndex] array.
ostream& operator<<(ostream& out, const hashmap& h)
{
const char *getSymbol = NULL;
for ( int hashIndex = 0; hashIndex < maxSize; hashIndex++ )
{
getSymbol = h.hashTable[hashIndex].getSymbol();
if ( getSymbol ) // Find the one I added.
{
h.hashTable->display(out);
return out << h.hashTable[hashIndex];
}
}
return out;
}
| Make sure the stream is set to print in decimal
out << dec << s.m_sharePrice;
(m_sharePrice is a non-pointer type, right?)
|
1,529,051 | 1,529,199 | can someone break this line apart gcc -E -dM - </dev/null | Just came across this guy that left me stunned:
gcc -E -dM - </dev/null
This part is confusing to me:
- </dev/null
| The "</dev/null" bit is at the shell level and not specific to gcc
< defines input file
> defines ouput file for std out,
>> defines a output for std out that will be appended to,
| sends std out output to another process on it's std in
I forget the syntax but you can also specify std err aswell like &2>
The name after the brackets is the name of a file, where /dev/null is an empty file
man sh should get you to the right sort of help for these questions.
Don't have access to gcc at the moment, assuming from other comment that - is reading from std in, then and equivelant statement is
gcc -E -dM /dev/null
|
1,529,095 | 1,529,188 | String comparisons. How can you compare string with std::wstring? WRT strcmp | I am trying to compare two formats that I expected would be somewhat compatible, since they are both generally strings. I have tried to perform strcmp with a string and std::wstring, and as I'm sure C++ gurus know, this will simply not compile. Is it possible to compare these two types? Is there an easy conversion here?
| You need to convert your char* string - "multibyte" in ISO C parlance - to a wchar_t* string - "wide character" in ISO C parlance. The standard function that does that is called mbstowcs ("Multi-Byte String To Wide Character String")
NOTE: as Steve pointed out in comments, this is a C99 function and thus is not ISO C++ conformant, but may be supported by C++ implementations as an extension. MSVC and g++ both support it.
It is used thus:
const char* input = ...;
std::size_t output_size = std::mbstowcs(NULL, input, 0); // get length
std::vector<wchar_t> output_buffer(output_size);
// output_size is guaranteed to be >0 because of \0 at end
std::mbstowcs(&output_buffer[0], input, output_size);
std::wstring output(&output_buffer[0]);
Once you have two wstrings, just compare as usual. Note that this will use the current system locale for conversion (i.e. on Windows this will be the current "ANSI" codepage) - normally this is just what you want, but occasionally you'll need to deal with a specific encoding, in which case the above won't do, and you'll need to use something like iconv.
EDIT
All other answers seem to go for direct codepoint translation (i.e. the equivalent of (wchar_t)c for every char c in the string). This may not work for all locales, but it will work if e.g. your char are all ASCII or Latin-1, and your wchar_t are Unicode. If you're sure that's what you really want, the fastest way is actually to avoid conversion altogether, and to use std::lexicographical_compare:
#include <algorithm>
const char* s = ...;
std::wstring ws = ...;
const char* s_end = s + strlen(s);
bool is_ws_less_than_s = std::lexicographical_compare(ws.begin, ws.end(),
s, s_end());
bool is_s_less_than_ws = std::lexicographical_compare(s, s_end(),
ws.begin(), ws.end());
bool is_s_equal_to_ws = !is_ws_less_than_s && !is_s_less_than_ws;
If you specifically need to test for equality, use std::equal with a length check:
#include <algorithm>
const char* s = ...;
std::wstring ws = ...;
std::size_t s_len = strlen(s);
bool are_equal =
ws.length() == s_len &&
std::equal(ws.begin(), ws.end(), s);
|
1,529,208 | 1,529,290 | Invalid Algorithm Specified CryptoAPI | I am trying to decrypt something using 128BIT AES Decryption. When i attempt to calling CryptDecrypt i get an Error stating "Invalid Algorithm Specified". I get the same problem when using the library posted here: http://www.codeproject.com/KB/security/WinAES.aspx
What can cause this error?
I am using CryptoAPI along on vista64bit with visual studio 2008. I checked in the registry and the AES library is there...
EDIT
BYTE*& encryptedData /* get data length */
HCRYPTPROV cryptoHandle = NULL;
HCRYPTKEY aesKeyHandle = NULL;
hr = InitWinCrypt(cryptoHandle);
if(FAILED(hr))
{
return hr;
}
AesKeyOffering aesKey = { {PLAINTEXTKEYBLOB, CUR_BLOB_VERSION, 0, CALG_AES_128}, 16, { 0xFF, 0x00, 0xFF, 0x1C, 0x1D, 0x1E, 0x03, 0x04, 0x05, 0x0F, 0x20, 0x21, 0xAD, 0xAF, 0xA4, 0x04 }};
if(CryptImportKey(cryptoHandle, (CONST BYTE*)&aesKey, sizeof(AesKeyOffering), NULL, 0, &aesKeyHandle) == FALSE)
{
// DO error
return HRESULT_FROM_WIN32(GetLastError());
}
if(CryptSetKeyParam(aesKeyHandle, KP_IV, { 0xFF, 0x00, 0xFF, 0x1C, 0x1D, 0x1E, 0x03, 0x04, 0x05, 0x0F, 0x20, 0x21, 0xAD, 0xAF, 0xA4, 0x04 } , 0) == FALSE)
{
return HRESULT_FROM_WIN32(GetLastError());
}
BYTE blah2 = CRYPT_MODE_CBC;
// set block mode
if(CryptSetKeyParam(aesKeyHandle, KP_MODE, &blah2, 0) == FALSE)
{
//
return HRESULT_FROM_WIN32(GetLastError());
}
DWORD lol = dataLength / 16 + 1;
DWORD lol2 = lol * 16;
if(CryptDecrypt(aesKeyHandle, 0, TRUE, 0, encryptedData, &lol2) == FALSE)
{
return HRESULT_FROM_WIN32(GetLastError());
}
InitWinCrypt function
if(!CryptAcquireContextW(&cryptoHandle, NULL, L"Microsoft Enhanced RSA and AES Cryptographic Provider", PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
if(!CryptAcquireContextW(&cryptoHandle, NULL, L"Microsoft Enhanced RSA and AES Cryptographic Provider", PROV_RSA_AES, 0))
{
return HRESULT_FROM_WIN32(GetLastError());
}
else
{
return S_OK;
}
}
return S_OK;
AesOffering struct:
struct AesKeyOffering
{
BLOBHEADER m_Header;
DWORD m_KeyLength;
BYTE Key[16];
};
EDIT2
After rebooting my computer, and remvoing the CBC chunk. I am now getting Bad Data Errors. The data decrypts fine in C#. But i need to do this using wincrypt.
| Are you passing cryptoHandle by reference to InitWithCrypt? If not, your code
if(!CryptAcquireContextW(&cryptoHandle, ...
would only modify InitWinCrypt's copy of cryptoHandle.
EDIT: Given that it does, try getting rid of the CryptSetKeyParam call which sets CRYPT_MODE_CBC
|
1,529,269 | 1,529,274 | Illegal Argument Execv() Unix C++ | So I basically have a vector args with 1 argument per array that I'm trying to pass to an execv() call in unix.
Execv accepts two parameters like so: int execv(const char *path, char *const argv[]);
What's the best way to convert my vector of strings to an array of pointers ? Right now I'm doing the following but when I run it with say, ps -a -f, ps yells at me saying illegal argument. Any help is appreciated.
vector<string> args = tokenize(cmd);
char * arg[args.size()];
for(int j=0; j<args.size();j++)
{
arg[j] = (char*)args[j].c_str();
}
retval = execv(args[0].c_str(), arg);
.
>ps
PID TTY TIME CMD
635 ttys000 0:00.18 -bash
16106 ttys000 0:00.00 ./test cpp
12590 ttys001 0:00.02 -bash
>ps -a
ps: illegal argument: ?????
| I think your problem may be that you are neglecting to put a NULL at the end of the array. Try this:
char * arg[args.size()+1];
arg[args.size()] = NULL;
for (int j=0; [...]
|
1,529,447 | 1,529,454 | Does return statement copy values | I am wondering about this because of scope issues. For example, consider the code
typedef struct {
int x1;/*top*/
int x2;/*bottom*/
int id;
} subline_t;
subline_t subline(int x1, int x2, int id) {
subline_t t = { x1, x2, id };
return t;
}
int main(){
subline_t line = subline(0,0,0); //is line garbage or isn't it? the reference
//to subline_t t goes out of scope, so the only way this wouldn't be garbage
//is if return copies
}
So my question is, will the return statement always copy? In this case it seems to work, so I am led to believe that return does copy. If it does copy, will it copy in every case?
| Yes, in that case there will be a copy made. If you change the function declaration like this:
subline_t &subline(int x1, int x2, int id) {
then no copy will be made. However, in your specific case it would not be valid to return a reference to an object allocated on the stack. The problem is that the object would be destructed and invalidated before the caller had a chance to use it.
This is related to the common Return Value Optimization for C++ that can avoid doing an actual copy operation in the case you have described. The end result is (or should be) the same as if a copy were done, but you should be aware of the optimization. The presence of this optimization can, in some cases, change the observable behaviour of the program.
|
1,529,679 | 1,529,693 | How do you program safely outside of a managed code environment? | If you are someone who programs in C or C++, without the managed-language benefits of memory management, type checking or buffer overrun protection, using pointer arithmetic, how do you make sure that your programs are safe? Do you use a lot of unit tests, or are you just a cautious coder? Do you have other methods?
| All of the above. I use:
A lot of caution
Smart Pointers as much as possible
Data structures which have been tested, a lot of standard library
Unit tests all the time
Memory validation tools like MemValidator and AppVerifier
Pray every night it doesn't crash on customer site.
Actually, I am just exaggerating. Its not too bad and its actually not too hard to keep control of resources if you structure your code properly.
Interesting note. I have a large application which uses DCOM and has managed and unmanaged modules. The unmanaged modules generally are harder to debug during development, but perform very well at the customer site because of the many tests run on it. The managed modules sometimes suffer from bad code because the garbage collector is so flexible, programmers get lazy in checking resource usage.
|
1,529,717 | 1,529,735 | Variable parameter lists in C++ and C | I'm working on rewriting a C program in C++ to take advantage of OO aspects so it can easily support multiple devices, and one part of the program is an expression evaluator. Expressions can have function calls, and here's the structure for functions.
typedef struct {
char *name;
int argc;
void (*func) ();
} FUNCTION;
Somehow func can have a variable number of arguments passed through it.
RESULT *param[10];
if (Root->Function->argc < 0) {
/* Function with variable argument list: */
/* pass number of arguments as first parameter */
Root->Function->func(Root->Result, argc, ¶m);
} else {
Root->Function->func(Root->Result, param[0], param[1], param[2], param[3], param[4], param[5], param[6],
param[7], param[8], param[9]);
}
I'm not even sure how this can be done in C to be honest. An explanation would be excellent. Can it be done in C++?
| The var args are what you are looking for. It works both in C and C++. This is what is used for printf() for example :).
You can find more information by googling va_arg (one of the function used for variable number of arguments)
var ags on cpppreference.com
var ags on cplusplus.com
|
1,529,942 | 1,529,960 | Explicit Linking DLL and Program Hangs | I've the following piece of code in my program which dynamically links wtsapi32.dll file for session notifications like WTS_SESSION_LOCK and WTS_SESSION_UNLOCK and runs in background. After the first lock/unlock the program hangs and not responding.
Is this a right way of doing explicit linking ?
void RegisterSession(HWND hwnd)
{
typedef DWORD (WINAPI *tWTSRegisterSessionNotification)( HWND,DWORD );
tWTSRegisterSessionNotification pWTSRegisterSessionNotification=0;
HINSTANCE handle = ::LoadLibrary("wtsapi32.dll");
pWTSRegisterSessionNotification = (tWTSRegisterSessionNotification) :: GetProcAddress(handle,"WTSRegisterSessionNotification");
if (pWTSRegisterSessionNotification)
{
pWTSRegisterSessionNotification(hwnd,NOTIFY_FOR_THIS_SESSION);
}
::FreeLibrary(handle);
handle = NULL;
}
Edited:
I have another method UnRegisterSession() function which calls WTSUnRegisterSessionNotification, I am calling the RegisterSession() in WinMain method ( removed FreeLibrary as suggested by 1800) and calling UnRegisterSession() in WM_DESTROY of CALLBACK WindowProcedure function. But still the application hangs.
| I'd say you probably cannot safely call FreeLibrary like that - you will be unloading the code you want to have call you. You should probably ensure not to free the dll until after you are finished getting notifications.
|
1,530,019 | 1,530,074 | Monitor the data in a table | How to write a shell script/process which runs like a daemon on Unix and continuously monitors a field in the table and sleeps for 30 sec's. The field value will regularly increase to a maximum value and my process/script which is monitoring will provide a simple select query output to a log file. any approach is preferred.
| Write a trigger on the table; on the value you care about, log it to another table; select from the other table at your leisure.
|
1,530,245 | 1,530,262 | I heard that Python has automated "garbage collection" , but C++ does not. What does that mean? | I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?
| That means that python user doesn't need to clean his dynamic created objects, like you're obligated to do it in C/C++.
Example in C++:
char *ch = new char[100];
ch[0]='a';
ch[1]='b';
//....
// somewhere else in your program you need to release the alocated memory.
delete [] ch;
// use *delete ch;* if you've initialized *ch with new char;
in python:
def fun():
a=[1, 2] #dynamic allocation
a.append(3)
return a[0]
python takes care about "a" object by itself.
|
1,530,330 | 1,530,469 | Why/how does this compile? | C++ in MS Visual Studio 2008. Warning level 4 plus a load of extra warnings enabled as well. I'd expect this to give a warning at least, but more likely a compiler error?
Function declaration is as follows:
int printfLikeFunction(
const int bufferLength,
char * const buffer,
const char * const format,
... );
Code usage - there's a typo: although the ARRAY_SIZE of outputBuffer is passed in, outputBuffer itself isn't - surely this should not compile:
printfLikeFunction( ARRAY_SIZE( outputBuffer ), "Format: %s, %s", arg1, arg2 );
Clearly this is wrong and a mistake has been made. However the compiler should have caught it! The buffer parameter should be a char-pointer, and it's being passed a string literal which is a const char-pointer. This must be an error. (arg1 and arg2 are (possibly const) char pointers as well, so coincidentally the declaration is matched even without outputBuffer being in the correct place).
At run time, this code crashes as it attempts to write into the string literal. No surprise there, I just don't understand how it was allowed to compile.
(Though, incidentally, this is presumably why sprintf_s has the buffer and size parameters in a different order to this function - it makes such errors unequivocally fail).
| C++ has a special loophole for string literals for compatibility with pre-const C-style code. Although string literals are arrays of const char, they can be converted to a pointer to non-const char.
Paraphrasing 4.2/2 [conv.array]: a 'narrow' string literal can be converted to an rvalue of type pointer to non-const char. The conversion is only considered when there is an explicit target type (e.g. a function parameter) and not when a general lvalue to rvalue conversion is required.
This conversion is deprecated, but still available. Note that while the conversion allows the literal to be converted to a pointer to non-const char type, it would still invoke undefined behaviour to try to modify any of the characters in the string literal through this pointer.
|
1,530,531 | 1,530,542 | C++ returning queue pointer from function error | I have a function
queue< pair<int,int> > * factorize(int n) {
...}
It shows this compile error.
generatePrimes.cpp:20: error: expected constructor, destructor, or type conversion before '<' token
generatePrimes.cpp:20: error: expected `,' or `;' before '<' token
What's wrong?
| Either you don't include necessary header files (queue and utility), or don't have using namespace std or both.
To overcome the first problem include the headers. To overcome the second one either add using or provide fully qualified names (std::queue and std::pair).
|
1,530,561 | 1,530,749 | Set location of MessageBox? | I want to print out a message using MessageBox (or similar). I would also like control over where exactly on the screen the box appears but can find nothing in the description of MessageBox that allows you control over the location. Did I miss something? If MessageBox can not be used, then is there an alternative?
For reasons too complex to go into here, I would prefer an answer which didn't involve making my own window and passing the address of a callback function.
| Step 1: Create a CBT hook to trap the creation of the message box:
// global hook procedure
HHOOK hhookCBTProc = 0;
LRESULT CALLBACK pfnCBTMsgBoxHook(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode == HCBT_CREATEWND)
{
CREATESTRUCT *pcs = ((CBT_CREATEWND *)lParam)->lpcs;
if (pcs->style & WS_DLGFRAME || pcs->style & WS_POPUP)
{
HWND hwnd = (HWND)wParam;
// At this point you have the hwnd of the newly created
// message box that so you can position it at will
SetWindowPos(hwnd, ...);
}
}
return CallNextHookEx(hhookCBTProc, nCode, wParam, lParam);
}
Step 2: Install/remove the hook before and after showing the message box:
// set hook to center the message box that follows
hhookCBTProc = SetWindowsHookEx(WH_CBT,
pfnCBTMsgBoxHook,
0, GetCurrentThreadId());
int sResult = MessageBox(hwndParent, pszMsg, pszTitle, usStyle);
// remove the hook
UnhookWindowsHookEx(hhookCBTProc);
|
1,530,579 | 1,530,633 | C++ specialization, type_of or just typeid | I would like to know what is better to use in my situation and why. First of all I heard that using RTTI (typeid) is bad. Anyone could explain why? If I know exactly types what is wrong to compare them in a runtime? Furthermore is there any example how to use boost::type_of? I have found none searching through the mighty google :) Other solution for me is specialization, but I would neet to specialize at least 9 types of new method. Here is an example what I need:
I have this class
template<typename A, typename B, typename C>
class CFoo
{
void foo()
{
// Some chunk of code depends on old A type
}
}
So I need to rather check in typeid(what is I heard is BAD) and make these 3 realizations in example like:
void foo()
{
if (typeid(A) == typeid(CSomeClass)
// Do this chunk of code related to A type
else
if (typeid(B) == typeid(CSomeClass)
// Do this chunk of code related to B type
else
if (typeid(C) == typeid(CSomeClass)
// Do this chunk of code related to C type
}
So what is the best solution? I don't want to specialize for all A,B,C, because every type is has 3 specializations so I will get 9 methods or just this typeid check.
| It's bad because
A, B and C are known at compile-time but you're using a runtime mechanism. If you invoke typeid the compiler will make sure to include metadata into the object files.
If you replace "Do this chunk of code related to A type" with actual code that makes use of CSomeClass's interface you'll see you won't be able to compile the code in case A!=CSomeClass and A having an incompatible interface. The compiler still tries to translate the code even though it is never run. (see example below)
What you normally do is factoring out the code into separate function templates or static member functions of classes that can be specialized.
Bad:
template<typename T>
void foo(T x) {
if (typeid(T)==typeid(int*)) {
*x = 23; // instantiation error: an int can't be dereferenced
} else {
cout << "haha\n";
}
}
int main() {
foo(42); // T=int --> instantiation error
}
Better:
template<typename T>
void foo(T x) {
cout << "haha\n";
}
void foo(int* x) {
*x = 23;
}
int main() {
foo(42); // fine, invokes foo<int>(int)
}
Cheers, s
|
1,530,654 | 1,530,664 | What is the output of this program? | when i tried to run compile and execute this statement in a simple c file:
main(){ printf("%d");}
on HP it's is giving me 64 and on AIX its giving me 804359524.
Could anyone tell me what is this behavior.
| I assume you mean:
int main()
{
printf("%d");
}
That being the case, printf() is reading an int (as directed by the format specifier %d) from the stack. Since you've not specified one, it's just reading whatever is on the stack and using that. Hence, your seeing pseudo-random output.
Instead, try:
int main()
{
printf("%d", 10101);
}
HTH
|
1,530,752 | 1,530,781 | What does the C++ error message "<near match>" mean? | When compiling my code with the GNU C++ compiler I get something like
bla.cxx: In function `int main(int, const char**)':
bla.cxx:110: error: no matching function for call to `func(const classA*&, const classB<classC>*&) const'
someheader.h:321: note: candidates are: bool func(const classA*, const T*&, const std::string&, std::string&) [with T = classB<classC>] <near match>
What does <near match> indicate and how do I fix this error?
(I simplified the error message as much as possible without (hopefully) removing necessary information. Actually, I'd rather not put an explicit example here, but encourage general replies to the question!)
| I normally see <near match> when a possible method matches except for const. Maybe the strings are optional arguments in this case? In that case the problem is that you have a const object, and are trying to call a non-const method.
NB: I haven't ever looked at the compiler code, merely looked at error messages gcc has generated.
EDIT:
From your comment, the strings at the end are optional, so aren't the problem. Assuming that is the method you want to call, then the problem is that you have a const pointer/reference to the object, and are trying to call a non-const method. To fix this, either:
Make the method const, if it doesn't modify the visible state of the object
Or pass around a non-const reference/pointer
If neither of those options is at all possible, and as a last resort and you can't change either of these things you can const_cast the pointer/reference, but then you are leaving a very bad smell in the code.
We do have a few places that do const_casts in our code, but only when calls old C functions, that take a non-const pointer but don't modify it. In straight C++ code that you control you can avoid const_cast.
|
1,530,765 | 1,530,816 | Why use Visual Studio 6 for C++ | I am just wondering why programmers who program in C++ for windows always use Visual Studio 6 instead of Visual Studio 2008?
Isn't the compiler in 2008 much better than the one in VS6?
The reason I ask as I have used many sdk's that are always written in VS6?
Many thanks,
Steve
| Partly it may be because earlier compilers are often (though not always) faster than later, and more feature-rich/standards-compliant, ones. I don't know whether this applies with VC6 vs later, but it may well do.
In the case of VC6 I think the two major factors are that the IDE is much faster to use than any of the painfully slow and greedy Visual Studio 200x IDEs, and that there's a huge amount of legacy code that will not compile with later, and more standards-compliant, VC++ compilers.
|
1,531,023 | 1,531,080 | moving a point in 3d space | I have a point at 0,0,0
I rotate the point 30 deg around the Y axis, then 30 deg around the X axis.
I then want to move the point 10 units forward.
I know how to work out the new X and Y position
MovementX = cos(angle) * MoveDistance;
MovementY = sin(angle) * MoveDistance;
But then I realised that these values will change because of Z, won't they?
How do I work out Z and have I worked out X and Y correctly?
Thanks!
| You should multiply point coordinates to full rotation matrix, which is matRotationTotal = matRotationX * matRotationY * matRotationZ. Check this article for details.
|
1,531,294 | 1,531,332 | Unusual destructor behaviour when copying over stack variables | I wrote a test to check whether destructors were called before an overwriting assignment on a stack variable, and I can't find any rational explanation for the results...
This is my test (in Visual C++ 2008 Release mode):
#include <iostream>
class C {
public:
char* ptr;
C(char p) { ptr = new char[100]; ptr[0] = p;}
~C() { std::cout << ptr[0] << ' '; delete [] ptr; }
};
int _tmain(int argc, _TCHAR* argv[])
{
{
C s('a');
s = C('b');
s = C('c');
s = C('d');
}
std::cin.get();
return 0;
}
I was expecting to get either "a b c d " if my hypothesis was true, or just "d " if false.
Instead I get "b c d x ". The "x " changes depending on how much memory is allocated to ptr indicating that it's reading random heap values.
I believe what is happening (correct me if I'm wrong) is that each constructor call creates a new stack value(lets call them s1, s2, s3, s4), and then the assignments leave s1.ptr overwritten by s4.ptr. s4 is then destroyed immediately after the copy but s1(with a dangling ptr) is destroyed upon leaving the scope, causing a double delete of s4.ptr and no delete of the original s1.ptr.
Is there any way around this unhelpful behavior that doesn't involve using shared_ptrs?
edit: replaced 'delete' with 'delete []'
| Rule of Three
Your application behavior is undefined, since as stated multiple objects will share access to a common pointer and will attempt to read it...
The rule of three states that each time you define one of:
copy constructor
assignment operator
destructor
Then you should define the other, since your object has a specific behavior that the default generated methods don't know about.
EDIT special exception:
sometimes you only define the destructor because you want it virtual, or because it logs something, not because there is some special handling of your attributes ;)
|
1,531,706 | 1,531,816 | Ternary operator on auto_ptr content not working | I initialize an auto_ptr to NULL and later in the game I need to know if it has NULL or not to return it or a new copy.
I've tried this
auto_ptr<RequestContext> ret = (mReqContext.get() != 0) ? mReqContext : new RequestContext();
And several other similar stuff casting and so, but g++ tries to invoke auto_ptrs nonexistent operator? (the ternary operator) instead of using RequestContext* for the ternary comparison.
Even if I cast it it doesn't work.
Any hint?
Edited the equal for non-equal
| I suppose the situation is analogous to the following:
#include <iostream>
#include <memory>
int main()
{
std::auto_ptr<int> a(new int(10));
std::auto_ptr<int> b = a.get() ? a : new int(10);
}
And here's Comeau's very enlightening error message:
"ComeauTest.c", line 7: error: operand types are incompatible ("std::auto_ptr<int>"
and "int *")
std::auto_ptr<int> b = a.get() ? a : new int(10);
^
Ternary operator requires compatible types for both results, you can't have it return user-defined object in one case and a naked pointer in the other. NB! std::auto_ptr takes a pointer in an explicit constructor, which means the ternary operator cannot implicitly convert the second argument to std::auto_ptr
And possible solution:
std::auto_ptr<int> b = a.get() ? a : std::auto_ptr<int>(new int(10));
|
1,532,293 | 1,534,062 | How do I retrieve a process ID for the Win32 Windows Mobile platform? | I would like to retrieve the process ID and handle of a process by querying for it by process name. Is this possible to do on the Win32 Windows Mobile platform?
Thanks in advance.
| Use CreateToolhelp32Snapshot(), following with Process32First() and the related functions, following the general idea in the code sample. The Process32... functions provide PROCESSENTRY32 for each process, which contains the Process ID.
|
1,532,550 | 1,536,688 | Using Boost Graph to search through a DAG Graph? | I need to search through a DAG graph, but I don't want to advance past a node before I have seen all of the other nodes that have directed links pointing to it.
Is there an existing algorithm to handle this particular situation, the depth first search and breath first search don't work for this order of traversal.
Ie:
A -> B
B -> C
C -> D
A -> C
I don't want to ever reach D before having seen both B and C.
| So my latest thoughts are to do a topological sort over the entire graph whenever an edge is added or removed and store the order of immediate child nodes to be traversed for each node (which may be a bit of a tricky algorithm to write).
Then I do a modified breadth first search (as suggested by chaos), and in the following bfs pseudo-code, modify the line:
for each vertex v in Adj[u]
to be:
for each vertex v in OrderedAdj[u]
pseudocode:
BFS(G, s)
for each vertex u in V[G]
color[u] := WHITE
d[u] := infinity
p[u] := u
end for
color[s] := GRAY
d[s] := 0
ENQUEUE(Q, s)
while (Q != Ø)
u := DEQUEUE(Q)
for each vertex v in Adj[u]
if (color[v] = WHITE)
color[v] := GRAY
d[v] := d[u] + 1
p[v] := u
ENQUEUE(Q, v)
else
if (color[v] = GRAY)
...
else
...
end for
color[u] := BLACK
end while
return (d, p)
I believe this is the most optimal way of achieving this, but does involve me writing my own bfs traversal algorithm, plus storing the order of nodes on each node (an overhead in memory I was hoping to avoid), and writing my own dfs visitor for finding the order and storing this on the nodes in the caching stage.
I am surprised that there isn't an existing way of doing this though, as it seems to me a fairly common way of navigating a dag graph...
|
1,532,640 | 1,533,222 | Which iomanip manipulators are 'sticky'? | I recently had a problem creating a stringstream due to the fact that I incorrectly assumed std::setw() would affect the stringstream for every insertion, until I changed it explicitly. However, it is always unset after the insertion.
// With timestruct with value of 'Oct 7 9:04 AM'
std::stringstream ss;
ss.fill('0'); ss.setf(ios::right, ios::adjustfield);
ss << setw(2) << timestruct.tm_mday;
ss << timestruct.tm_hour;
ss << timestruct.tm_min;
std::string filingTime = ss.str(); // BAD: '0794'
So, I have a number of questions:
Why is setw() this way?
Are any other manipulators this way?
Is there a difference in behavior between std::ios_base::width() and std::setw()?
Finally is there an online reference that clearly documents this behavior? My vendor documentation (MS Visual Studio 2005) doesn't seem to clearly show this.
| Important notes from the comments below:
By Martin:
@Chareles: Then by this requirement all manipulators are sticky. Except setw which seems to be reset after use.
By Charles:
Exactly! and the only reason that setw appears to behave differently is because there are requirements on formatted output operations to explicitly .width(0) the output stream.
The following is the discussion that lead to the above conclusion:
Looking at the code the following manipulators return an object rather than a stream:
setiosflags
resetiosflags
setbase
setfill
setprecision
setw
This is a common technique to apply an operation to only the next object that is applied to the stream. Unfortunately this does not preclude them from being sticky. Tests indicate that all of them except setw are sticky.
setiosflags: Sticky
resetiosflags:Sticky
setbase: Sticky
setfill: Sticky
setprecision: Sticky
All the other manipulators return a stream object. Thus any state information they change must be recorded in the stream object and is thus permanent (until another manipulator changes the state). Thus the following manipulators must be Sticky manipulators.
[no]boolalpha
[no]showbase
[no]showpoint
[no]showpos
[no]skipws
[no]unitbuf
[no]uppercase
dec/ hex/ oct
fixed/ scientific
internal/ left/ right
These manipulators actually perform an operation on the stream itself rather than the stream object (Though technically the stream is part of the stream objects state). But I do not believe they affect any other part of the stream objects state.
ws/ endl/ ends/ flush
The conclusion is that setw seems to be the only manipulator on my version that is not sticky.
For Charles a simple trick to affect only the next item in the chain:
Here is an Example how an object can be used to temporaily change the state then put it back by the use of an object:
#include <iostream>
#include <iomanip>
// Private object constructed by the format object PutSquareBracket
struct SquareBracktAroundNextItem
{
SquareBracktAroundNextItem(std::ostream& str)
:m_str(str)
{}
std::ostream& m_str;
};
// New Format Object
struct PutSquareBracket
{};
// Format object passed to stream.
// All it does is return an object that can maintain state away from the
// stream object (so that it is not STICKY)
SquareBracktAroundNextItem operator<<(std::ostream& str,PutSquareBracket const& data)
{
return SquareBracktAroundNextItem(str);
}
// The Non Sticky formatting.
// Here we temporariy set formating to fixed with a precision of 10.
// After the next value is printed we return the stream to the original state
// Then return the stream for normal processing.
template<typename T>
std::ostream& operator<<(SquareBracktAroundNextItem const& bracket,T const& data)
{
std::ios_base::fmtflags flags = bracket.m_str.flags();
std::streamsize currentPrecision = bracket.m_str.precision();
bracket.m_str << '[' << std::fixed << std::setprecision(10) << data << std::setprecision(currentPrecision) << ']';
bracket.m_str.flags(flags);
return bracket.m_str;
}
int main()
{
std::cout << 5.34 << "\n" // Before
<< PutSquareBracket() << 5.34 << "\n" // Temp change settings.
<< 5.34 << "\n"; // After
}
> ./a.out
5.34
[5.3400000000]
5.34
|
1,532,665 | 1,532,904 | JNI Pass By Reference, Is it Possible? | I have a Java program that calls a C++ program to authenticate users. I would like the program to return either true or false, and if false, update a pointer to an error message variable that i then can grab from the Java program.
Another explination:
The native method would look something like this:
public native String takeInfo(String nt_domain, String nt_id, String nt_idca, String nt_password, String &error);
I would call that method here:
boolean canLogin = takeInfo(domain, userID, "", userPass, String &error)
Then in my C++ program I would check if the user is authenticated and store it in a boolean, then if false, get the error message and update &error with it. Then return that boolean to my Java program where I could display the error or let the user through.
Any ideas?
Originally I had it so the program would return either "true" or the error message, as a jstring, but my boss would like it as described above.
| There is a common technique to simulate additional out parameter by using object array in parameter.
For example.
public native String takeInfo(String nt_domain, String nt_id, String nt_idca, String nt_password, String[] error);
boolean canLogin = takeInfo(domain, userID, "", userPass, error);
if(!canLogin){
String message = error[0];
}
There is a another way to do by returning a result object
class static TakeInfoResult{
boolean canLogon;
String error;
}
TakeInfoResult object = takeInfo(domain, userID, "", userPass);
In the 2nd case you will need to program more in the JNI layer.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.