LNK2019: Unresolved External Symbol when attempting to use "GetCommPorts()" - visual-c++

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

Related

How to QMap()::begin() + int offset

I have function in my filemodel which returns actual file name in specific position.
...
QMap<QString, QFileInfo> fileInfoMap_;
...
QString MFileModel::fileAt(int offset) const
{
return (fileInfoMap_.begin() + offset).key();
}
...
Problem is, that this feature stop working in QT6. How can i repair it? I looking for documentation, without success.
QMap.begin() returns QMap::const_iterator. There is no option to use "+ int".
Build retur error:
...mfilemodel.cpp:276: error: invalid operands to binary expression ('QMap<QString, QFileInfo>::const_iterator' and 'int')
This solved my problem.
Maybe siple way exists. But this works too.
QString MFileModel::fileAt(int offset) const
{
QMap<QString, QFileInfo>::const_iterator ci = fileInfoMap_.begin();
for (int i=0; i<offset; i++)
{
ci = ci.operator++();
}
//return (fileInfoMap_.begin() + offset).key();
return ci.key();
}

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?

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.

Uncaught TypeError: Cannot read property 'copy' of undefined p5.js/node.js/socket.io

I'm having an error when the second client is connected. My code comparing the two clients current position by p5.Vector.dist() and there's an error, here it is.
And the line in p5.Vector.dist(p5.js:25914) is
p5.Vector.prototype.dist = function (v) {
var d = v.copy().sub(this); //This is the exact line where the error says from
return d.mag();
};
This is my code;
Client side;
//I use for loop to see all the contain of otherCircles
for(var x = 0; x < otherCircles.length; x++){
if(otherCircles[x].id != socket.id){ //To make sure i won't compare the client's data to its own because the data of all connected client's is here
console.log(otherCircles[x].radius); //To see if the data is not null
if(circle.eat(otherCircles[x])){
if(circle.radius * 0.95 >= otherCircles[x].radius){
otherCircles.splice(x,1);
console.log('ATE');
} else if(circle.radius <= otherCircles[x].radius * 0.95){
zxc = circle.radius;
asd = zxc;
circle.radius = null;
console.log('EATEN');
}
}
}
}
//Here's the eat function of the circle
function Circle(positionX,positionY,radius){
//The variables of Circle()
this.position = createVector(positionX, positionY);
this.radius = radius;
this.velocity = createVector(0, 0);
//Here's the eat function
this.eat = function(other) {
var distance = p5.Vector.dist(this.position, other.position); //Heres where the error
if (distance < this.radius + (other.radius * 0.25)) { //Compare there distance
return true;
} else {
return false;
}
}
}
The otherCircles[] contains;
And that is also the output of the line console.log(otherCircles[x].radius);.
I don't think the server side would be necessary because it only do is to receive the current position and size of the client and send the other clients position and size to. All there datas stored in otherCircles(). The line console.log(otherCircles[x].radius); result is not null, so I know there's data where being compared to the clients position, why I'm having an error like this.
It's going to be pretty hard to help you without an MCVE, but I'll try to walk you through debugging this.
You've printed otherCircles[x].radius, which is a good start. But if I were you, I'd want to know much more about otherCircles[x]. What variables and functions does it contain? I'd start by googling "JavaScript print function names of object" and try to figure out exactly what's in that object. What is the value of otherCircles[x].position?
From there, I'd also want to make sure that otherCircles[x].position is defined and an instance of p5.Vector. Does it have a copy() function?
I might also step through the code with a debugger- every browser has one, and you should become familiar with using it.
If you still can't get it work, then please post an MCVE that we can run by copy-pasting it. That means no server code, just hard-code your values so we can see the same error. I'd bet you find your problem while trying to narrow it down to a small example. But if not, we'll go from there. Good luck.

Unhandled exception when using GAlib in MFC project

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

Resources