Unhandled exception when using GAlib in MFC project - visual-c++

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

Related

IDataObjectAsyncCapability not being handled by Outlook in OLE Drag and Drop

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?

LNK2019: Unresolved External Symbol when attempting to use "GetCommPorts()"

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)?

Starting Microsoft Edge from MFC with web file paramater

If I open up a console prompt I can type this command:
start msedge "d:\HTML\Verticle Alignment.HTM"
It starts Microsoft Edge and opens the web page.
So I tried to do this programmatically in a test program using MFC:
void CMFCApplication8Dlg::OnBnClickedButton1()
{
ExecuteProgram(_T("start"), _T("msedge d:\\HTML\\Verticle Alignment.HTM"));
}
BOOL CMFCApplication8Dlg::ExecuteProgram(CString strProgram, CString strArguments)
{
SHELLEXECUTEINFO se = { 0 };
MSG sMessage;
DWORD dwResult;
se.cbSize = sizeof(se);
se.lpFile = strProgram;
se.lpParameters = strArguments;
se.nShow = SW_SHOWDEFAULT;
se.fMask = SEE_MASK_NOCLOSEPROCESS;
ShellExecuteEx(&se);
if (se.hProcess != nullptr)
{
do
{
dwResult = ::MsgWaitForMultipleObjects(1, &(se.hProcess), FALSE,
INFINITE, QS_ALLINPUT);
if (dwResult != WAIT_OBJECT_0)
{
while (PeekMessage(&sMessage, nullptr, NULL, NULL, PM_REMOVE))
{
TranslateMessage(&sMessage);
DispatchMessage(&sMessage);
}
}
} while ((dwResult != WAIT_OBJECT_0) && (dwResult != WAIT_FAILED));
CloseHandle(se.hProcess);
}
if ((DWORD_PTR)(se.hInstApp) < 33)
{
// Throw error
AfxThrowUserException();
return FALSE;
}
return TRUE;
}
But when I run it I get this error message:
So how can I launch my file in Microsoft Edge? I am using the latest Windows 10 so it is Microsoft Edge Chromium.
I have seen other questions which refer to making Edge the default browser and then just "opening" the data file and it working it all out but this is not OK in this case. In my editor I have a menu flyout which lists all the installed browsers (excluding Edge for now). But i want to add Edge so need to be able to programatically start it with my file to view.
Based on the comments provided to me, and to factor in for spaces in the file name, this works:
ExecuteProgram(_T("msedge"), _T("\"d:/HTML/Verticle Alignment.HTM\""));
The program to execute needs to be msedge and not start.
The parameter needs to be wrapped in " quotes.

segfault on Rcpp function when running with sanitizers (from rhub)

I am writing a package using Rcpp Function, the package compiles, and R CMD Check also works fine. Earlier, the input to package's cvode function was an XPtr, but now the input can be both XPtr or an R or Rcpp function (the implementation was based on a earlier post). Currently, input functions in R, Rcpp and Rcpp::XPtr work in the package.
The package had previously had clang-UBSAN issues, so I am trying to detect them beforehand now using rhub package. On running check_with_sanitizers() command from the rhub package, I am getting the following error:
eval.c:677:21: runtime error: member access within null pointer of type 'struct SEXPREC'
─ *** caught segfault ***
address (nil), cause 'memory not mapped'
Segmentation fault (core dumped)
I have been able to isolate the error to the line ydot1 = rhs_fun(t, y1); in the following piece of code, i.e., commenting/un-commenting the expression above reproduces the error.
My question is - is there a check I should be performing before calling the rhs_fun Function, to avoid the segmentation fault error?
Note - check_with_valgrind() produces no error.
Thanks!
// struct to use if R or Rcpp function is input as RHS function
struct rhs_func{
Function rhs_eqn;
};
int rhs_func(realtype t, N_Vector y, N_Vector ydot, void* user_data){
// convert y to NumericVector y1
int y_len = NV_LENGTH_S(y);
NumericVector y1(y_len); // filled with zeros
realtype *y_ptr = N_VGetArrayPointer(y);
for (int i = 0; i < y_len; i++){
y1[i] = y_ptr[i];
}
// convert ydot to NumericVector ydot1
// int ydot_len = NV_LENGTH_S(ydot);
NumericVector ydot1(y_len); // filled with zeros
// // cast void pointer to pointer to struct and assign rhs to a Function
struct rhs_func *my_rhs_fun = (struct rhs_func*)user_data;
if(my_rhs_fun){
Function rhs_fun = (*my_rhs_fun).rhs_eqn;
// use the function to calculate value of RHS ----
// Uncommenting the line below gives runtime error
// ydot1 = rhs_fun(t, y1);
}
else {
stop("Something went wrong, stopping!");
}
// convert NumericVector ydot1 to N_Vector ydot
realtype *ydot_ptr = N_VGetArrayPointer(ydot);
for (int i = 0; i< y_len; i++){
ydot_ptr[i] = ydot1[i];
}
// everything went smoothly
return(0);
}
An update - based on the comments below, I have added checks. So the check succeeds, but I can see the rhs_fun is NULL as the code goes to the stop message.
if(my_rhs_fun){
Function rhs_fun = (*my_rhs_fun).rhs_eqn;
// use the function to calculate value of RHS ----
if (rhs_fun){
ydot1 = rhs_fun(t, y1);
}
else{
stop("Something went wrong");
}
}
else {
stop("Something went wrong, stopping!");
}
An added check is added to the struct also
if (Rf_isNull(input_function)){
stop("Something is wrong with input function, stopping!");
}
The checks succeed, but I see that rhs_fun is NULL as the else message is printed
Error in cvode(time_vec, IC, ODE_R, reltol, abstol) :
Something went wrong
Execution halted
Not sure why, as the examples I have tried have worked without complaints.
The most likely candidate for a NULL reference is rhs_fun. So it makes sense to test that before executing the function:
if(rhs_fun) {
...
} else {
stop(...)
}
The R API function Rf_isNull would not be appropriate here, since that checks for an SEXP of type NILSXP and segfaults for an actual nullptr.
In addition I would check that you are not inserting a NULL reference into the struct, though I find it unlikely that anything is going wrong there.
Overall this is just a workaround. It would be interesting to know what triggers this behavior.

VC++ error C2065 in debug build

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.

Resources