I am porting a C++ project to VS2008.
Piece of the code has a variable declared in the for loop statement as below:
for(bmpMapType::const_iterator it = bitmaps.begin(); it != bitmaps.end(); ++it)
{
}
"it" is later used as an index in another for loop statement as below:
for(it = bitmaps.begin(); it != bitmaps.end(); ++it)
{
}
It generates error c2065 in debug build wit hthe below project settings where as release build was successful.
I have set the C\C++ > Language> For Conformance In For loop Scope to No (/Zc:forscope- ) and built the project with release configuration mode.
Code was built succesfully.
The same code with the same settings fail to build in debug mode.
Can anyone help me to resolve the issue.
Any help is appreciated.
Thanks,
Lakshmi
The it variable is declared within the for loop initializer list, which means its scope ends along with the for loop scope. Setting /Zc:forscope- option enables the MS specific extension which keeps the it declaration alive until the end of the enclosing scope in which your for loop is defined (for example, whatever function body your code snippet exists in). IMHO, you shouldn't be using the /Zc:forscope- flag since it compiles non-standard code without errors. To fix your problem you can do one of two things:
bmpMapType::const_iterator it;
//first loop
for( it = bitmaps.begin(); it != bitmaps.end(); ++it ) { ... }
...
//second loop
for( it = bitmaps.begin(); it != bitmaps.end(); ++it ) { ... }
OR
//first loop
for( bmpMapType::const_iterator it = bitmaps.begin(); it != bitmaps.end(); ++it ) { ... }
...
//second loop
for( bmpMapType::const_iterator it = bitmaps.begin(); it != bitmaps.end(); ++it ) { ... }
A simple fix may be just to modify the second loop to match the first - declaring its own copy of it as per
for(bmpMapType::const_iterator it = bitmaps.begin(); it != bitmaps.end(); ++it) {
}
unless there is some place in between the loops where the first it is used. If usage of each is entirely local to their respective loops then just do this and get on with your port.
Related
I work on an electron application, and we would like to support dragging and dropping .msg files from our app into Outlook (or the Windows shell, or wherever, but primarily Outlook). The files will not necessarily be available before the user starts the drag and drop operation, and will need to be downloaded once the user begins the drag and drop. This means we can't use electron's inbuilt startDrag as it requires that the files are already in the filesystem, so I have implemented a node c++ addon to handle it using the OLE Drag and Drop API.
The data extraction (from my app to Outlook) needs to occur asynchronously, otherwise node's event loop will be blocked, halting the download. This means that the data extraction has to occur on another thread so that the event loop can continue actually downloading the data (currently doing the download in c++ is not an option, it has to occur in node). So I have implemented IDataObjectAsyncCapability on my DataObject, to indicate that I support asynchronous data extraction (it would be even nicer to be able to indicate that I don't support synchronous), but Outlook won't even query for the Interface, let alone do the data extraction asynchronously. The Windows shell does however query for the interface, but after the call to GetData, it still performs the extraction synchronously inside DoDragDrop, without even invoking any of the IDataObjectAsyncCapability methods. Is there something lacking in my implementation, or a specific way to encourage the drop target to start up a new thread?
Here is the meat of my DataObject implementation, if there's anything else that could be of use, I can provide.
STDMETHODIMP DataObject::QueryInterface(REFIID iid, LPVOID* ppvObject) {
if (ppvObject == nullptr) {
return E_INVALIDARG;
} else if (iid == IID_IUnknown) {
AddRef();
*ppvObject = reinterpret_cast<LPUNKNOWN>(this);
return S_OK;
} else if (iid == IID_IDataObject) {
AddRef();
*ppvObject = reinterpret_cast<LPDATAOBJECT>(this);
return S_OK;
} else if (iid == IID_IDataObjectAsyncCapability) {
AddRef();
*ppvObject = reinterpret_cast<IDataObjectAsyncCapability*>(this);
return S_OK;
}
*ppvObject = nullptr;
return E_NOINTERFACE;
}
STDMETHODIMP DataObject::GetData(LPFORMATETC queryFormat,
LPSTGMEDIUM outputStorage) {
if (queryFormat->cfFormat == CF_FILEDESCRIPTOR &&
(queryFormat->tymed & TYMED_HGLOBAL) && queryFormat->lindex <= 0 &&
queryFormat->dwAspect == DVASPECT_CONTENT) {
outputStorage->tymed = TYMED_HGLOBAL;
outputStorage->pUnkForRelease = nullptr;
outputStorage->hGlobal =
lockAndDuplicateHGLOBAL(this->groupDescriptorStorage.hGlobal);
return S_OK;
} else if (queryFormat->cfFormat == CF_FILECONTENTS &&
(queryFormat->tymed & TYMED_ISTREAM) &&
queryFormat->dwAspect == DVASPECT_CONTENT &&
queryFormat->lindex >= 0 &&
queryFormat->lindex < this->files.size()) {
// files is vector<pair<FILEDESCRIPTOR, STGMEDIUM>>
// where the STGMEDIUM is set to IStream
// Am I doing something wrong here?
auto file = this->files[queryFormat->lindex].second;
*outputStorage = file;
return S_OK;
}
return DV_E_FORMATETC;
}
STDMETHODIMP DataObject::QueryGetData(LPFORMATETC queryFormat) {
if (queryFormat->cfFormat == CF_FILEDESCRIPTOR ||
(queryFormat->cfFormat == CF_FILECONTENTS &&
(queryFormat->tymed & TYMED_HGLOBAL))) {
return S_OK;
}
return DATA_E_FORMATETC;
}
STDMETHODIMP DataObject::EnumFormatEtc(DWORD dwDirection,
LPENUMFORMATETC* ppEnumFormatEtc) {
if (dwDirection == DATADIR_GET) {
// basic implementation of IEnumFormatEtc (not mine)
return EnumFormat::Create(this->supportedFormats, this->numFormats,
ppEnumFormatEtc);
}
return E_INVALIDARG;
}
// Do the actual drag drop
// files is a list of STGMEDIUMS with IStreams. I'm using data that's readily available while
// implementing this, could that be somehow interfering and causing this problem in the first place?
DWORD dwEffect;
auto dataObject = new DataObject(groupDescriptorStorage, files);
auto dropSource = new DropSource();
// Do these DROPEFFECTS have an effect?
auto result = DoDragDrop(dataObject, dropSource,
DROPEFFECT_COPY | DROPEFFECT_MOVE, &dwEffect);
// By the time we get here, the data extraction would already have occured
// because it's happening inside DoDragDrop. of course, isAsyncOperation will be false
BOOL isInAsyncOperation;
dataObject->InOperation(&isInAsyncOperation);
I've followed the instructions from here as well as various forum posts I've found, but I can't seem to find anything about what to do when the drop target doesn't play ball.
I'm really stuck for ideas as to how to make this work. If the drop target isn't even querying for IDataObjectAsyncCapability then is it hopeless? Should I be returning something other than the file contents when it's first requested?
I am attempting to retrieve a list of COM ports in a windows program using the GetCommPorts() function.
#include<WinBase.h>
void CSoftwareDlg::DynamicComPortMenu()
{
ULONG portNumbers[100];
ULONG portsFound;
ULONG CommPorts = GetCommPorts(portNumbers, 100, &portsFound);
if (CommPorts == ERROR_SUCCESS) {
OutputDebugString("COM Ports retrieved successfully.");
OutputDebugString(("Found" + std::to_string(portsFound) + "ports.").c_str());
for (auto i = 0; i < portsFound; i++) {
OutputDebugString(("\t" + std::to_string(portNumbers[i])).c_str());
}
}
else if (CommPorts == ERROR_MORE_DATA) {
OutputDebugString("Array to small to retrieve all port numbers.");
}
else if (CommPorts == ERROR_FILE_NOT_FOUND) {
OutputDebugString("No COM ports found.");
}
else {
OutputDebugString("CommPorts function not equal to any of the standard error codes...");
}
}
The function call has no compiler error, and I can peek the definition of the function without issue. For other similar issues, I've resolved this issue with the scope resolution operator or the macro definition and scope resolution operator like so:
::GetCommPorts(portNumbers, 100, &portsFound);
_WINBASE_::GetCommPorts(portNumbers, 100, &portsFound);
I thought that it may be in some "hidden" library, so I took a shot in the dark and attempted to use a pragma comment to find a WinBase library like so:
#pragma comment (lib, "Winbase.lib")
What am I missing here? The fact that I'm able to peek the definition of the function is really throwing me off.
Bonus question: Should I always be handling all of the return codes for functions like this(e.g. ERROR_SUCCESS, ERROR_MORE_DATA, and ERROR_FILE_NOT_FOUND)?
I am trying to know if a Pull Request in Github has to execute a pipeline in Jenkins or not (depending of pushing code or documentation). For that I have this function, but I am not able to math patterns this way:
"i" is an array where each element is a modified file
If the file is in doc/ or .github/ folder it is supposed to be documentation and no execution will be built in Jenkins.
I have made a change in .github/PULL_REQUESTS.md but this functions returns me FALSE
// Compares the modified files to see if it is only documentation
def checkPRDoc(String[] prChangeLog) {
def pushing_doc = false
println("Modified files:")
for(int i in prChangeLog) {
println(i);
if ((i ==~ /doc*/) || (i ==~ /README.md/) || (i ==~ /.github*/)) {
pushing_doc = true
}
if (pushing_doc == false) {
break;
}
}
return pushing_doc
}
Any help? Thanks a lot
all, I am using GAlib in my VC++ MFC project and encountered a Unhandled exception when using GA initialize() function:
Unhandled exception at 0x765b2eec in XMLDOMFromVC.exe: Microsoft C++ exception: _com_error at memory location 0x00f9de10..
This is my code, which followed the examples in the GAlib:
void CGATrainingDlg::OnBnClickedGaTrainButton()
{
// TODO: Add your control notification handler code here
GARealAlleleSetArray alleles2a;
for(int i=0; i<m_nAlleleSetArrayLen; i++)
alleles2a.add(0, 1, GAAllele::EXCLUSIVE, GAAllele::INCLUSIVE);
GARealGenome genome2a(alleles2a, ObjectiveTrampoline, this);
genome2a.mutator(GARealIncrementalMutator);
genome2a.crossover(GARealOnePointCrossover);
// Now do a genetic algorithm for each one of the genomes that we created.
GASimpleGA ga(genome2a);
// Now that we have the genomes, create a parameter list that will be used for
// all of the genetic algorithms.
GAParameterList params;
GASimpleGA::registerDefaultParameters(params);
params.set(gaNpCrossover, m_dPCross);
params.set(gaNpMutation, m_dPMut);
if(BST_CHECKED == IsDlgButtonChecked(IDC_GA_CONVERGENCE_RADIO))
{
params.set(gaNpConvergence, m_fPconv);
params.set(gaNnConvergence, m_nConv);
ga.terminator(GAGeneticAlgorithm::TerminateUponConvergence);
}else{
params.set(gaNnGenerations, m_nGAGen);
}
params.set(gaNpopulationSize, m_nGAPopSize);
params.set(gaNscoreFrequency, m_nScoreFreq);
params.set(gaNflushFrequency, m_nFlushFreq);
params.set(gaNselectScores, (int)GAStatistics::AllScores);
if((m_fPconv == 0 || m_nConv == 0) && m_nGAGen == 0)
{
AfxMessageBox(_T("You need to specify parameters for GA Terminator"));
exit(EXIT_FAILURE);
}
ga.parameters(params);
// the following line is where the exception happened
ga.initialize();
/* some other code*/
}
I have been following an example (ex7.C) that use GA initialize(), but do not know what is the cause of this exception, so any idea how to fix this?
cheers
I needed to enumerate running processes and wondered for a while why my code wasn't working:
PROCESSENTRY32 ProcEntry;
ZeroMemory (&ProcEntry, sizeof (PROCESSENTRY32)); //problem
ProcEntry.dwFlags = sizeof(PROCESSENTRY32);
HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Snapshot == INVALID_HANDLE_VALUE)
return false;
if (Process32First(Snapshot, &ProcEntry))
....
Problem was that Process32First always returned FALSE because of ERROR_BAD_LENGTH error.
Once I removed ZeroMemory line, everything started working fine. So the question is, why ZeroMemory caused it? It should just fill memory at the address of X for Z bytes. I use it a lot for winapi pointer-like structures, this time I didnt realise its a local variable but that doesn't explain the problem or does it?
Thanks,
Kra
EDIT: plus I found out code works fine only in Debug version, once I compile it as Release version, its bugged again :/
You should set dwSize, not dwFlags.
ProcEntry.dwFlags = sizeof(PROCESSENTRY32);
should be
ProcEntry.dwSize = sizeof(PROCESSENTRY32);
You cannot zero out the entire PROCESSENTRY32 structure as it is self-describing - you have to set dwSize. From the sample here:
HANDLE hProcessSnap;
HANDLE hProcess;
PROCESSENTRY32 pe32;
DWORD dwPriorityClass;
// Take a snapshot of all processes in the system.
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( hProcessSnap == INVALID_HANDLE_VALUE )
{
printError( TEXT("CreateToolhelp32Snapshot (of processes)") );
return( FALSE );
}
// Set the size of the structure before using it.
pe32.dwSize = sizeof( PROCESSENTRY32 );
// Retrieve information about the first process,
// and exit if unsuccessful
if( !Process32First( hProcessSnap, &pe32 ) )
{
printError( TEXT("Process32First") ); // show cause of failure
CloseHandle( hProcessSnap ); // clean the snapshot object
return( FALSE );
}