Meaning of a numerical ErrorMessage - c++

I am trying to interface with an OEM library. Everything worked on one computer but I am getting lots of problems on another computer.
I the code is throwing a COM exception but I can't figure out the meaning of a error code that doesn't have a ErrorMessage();
The code
#include "stdafx.h"
#include <afx.h>
#include <iostream>
using namespace std;
#import "MTBApi.tlb" named_guids //raw_interfaces_only
using namespace MTBApi;
void DisplayError(_com_error* e)
{
CString message;
// if it is an application error thrown by .NET
if (e->Error() >= 0x80041000)
{
IErrorInfo* info;
BSTR msg;
info = e->ErrorInfo();
info->GetDescription(&msg);
info->Release();
message = CString(msg);
}
// other com errors
else
{
message = e->ErrorMessage();
}
cout << "MTB Error: " << message <<":"<<(unsigned int) e->Error()<< endl;
}
int main(int argc, char **argv)
{
for (int i = 0 ; i < 4 ; i++)
{
IMTBConnectionPtr m_MTBConnection;
try
{
cout <<"1" << endl;
HRESULT a = CoInitializeEx(NULL,COINIT_SPEED_OVER_MEMORY);
cout <<"2" << endl;
m_MTBConnection = IMTBConnectionPtr(CLSID_MTBConnection);
cout <<"3" << endl;
m_MTBConnection->Close();
cout <<"4" << endl;
CoUninitialize();
cout <<"5" << endl;
}
catch(_com_error e)
{
DisplayError(&e);
}
cout << endl;
}
}
The runtime output
1
2
MTB Error: 00000000002205F8:2147746132
1
2
MTB Error: 00000000002205F8:2147746132
1
2
MTB Error: 00000000002205F8:2147746132
1
2
MTB Error: 00000000002205F8:2147746132
Rather Verbose Output from Dependency Walker
http://pastebin.com/7Y33z3Pj

cout << "MTB Error: " << message <<":"<<(unsigned int) e->Error()<< endl;
cout isn't very good at displaying Unicode strings, it merely displays the string pointer value. Not useful of course, use wcout instead. And favor displaying the error code in hex. 0x80040154 is a very common COM error, "Class not registered". Thousands of questions about it already, you just need to get the COM server registered properly. Ask the vendor or author if you don't know how to do that.

00000000002205F8 looks like a memory pointer. You are passing a CString to cout, which only accepts char* or std::string for string values. Maybe the CString contains a Unicode string that is not being converted to Ansi correctly. Also, when calling IErrorInfo::GetDescription(), you are leaking the returned BSTR. You need to free it with SysFreeString() when you are done using it.
Error code 2147746132 (hex 0x80040154) is Severity=FAIL, Facility=FACILITY_ITF, Code=340. FACILITY_ITF typically means the error code is a custom error code defined by the interface that failed. But in this case, 0x80040154 is also a standard error code: REGDB_E_CLASSNOTREG.

If your problem is to rectify the error which you are getting then
then issue is as #Remy pointed out , your com assembly is not registered in the machine you are currently executing your program rather in the other machine it got registered. Register the assembly (for eg COMAssembly.dll which is in C:\ drive) by running the following command in command prompt.
regsvr32 c:\COMAssembly.dll
if its a C++ com assembly , if its a C# assembly register it by using command
regasm c:\COMAssembly.dll
(where regasm can be run in a VS command prompt , otherwise if you are running in normal command prompt then you have to first call vsvars32.bat then call regasm)

Related

WriteConsole doesn't work with PowerShell ISE?

WriteConsole does not work with PowerShell ISE.
Neither WriteConsoleW or WriteConsoleA do.
See, for example, this program:
#include <iostream>
#include <Windows.h>
void w() {
DWORD written;
BOOL const success = WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), L"Printed\n", 8, &written, nullptr);
std::wcout << (success ? L"Success" : L"Failure") << L". Wrote " << written << L" characters." << std::endl;
}
void a() {
DWORD written;
BOOL const success = WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), "Printed\n", 8, &written, nullptr);
std::cout << (success ? "Success" : "Failure") << ". Wrote " << written << " characters." << std::endl;
}
int main() {
w();
a();
return 0;
}
Ran from PowerShell (or Command Prompt, or Git Bash), it prints:
Printed
Success (wrote 8 characters)
Printed
Success (wrote 8 characters)
But from PowerShell ISE:
Failure (wrote 0 characters)
Failure (wrote 0 characters)
To provide background information on Bertie Wheen's own helpful answer:
Perhaps surprisingly, the Windows PowerShell ISE does not allocate a console by default. (The console-like UI that the ISE presents is not a true Windows console).
A console is allocated on demand, the first time a console-subsystem program is run in a session (e.g., cmd /c ver)
Even once that has happened, however, interactive console-subsystem programs are fundamentally unsupported (try choice /m "Prompt me", for instance).
Interactively, you can test if a console has been allocated or not with the following command: [Console]::WindowTop; if there's no console, you'll get a The handle is invalid error.
It follows from the above that your program cannot assume that a console is present when run in the ISE.
One option is to simply not support running in the ISE, given that it is:
no longer actively developed
and there are various reasons not to use it (bottom section), notably not being able to run PowerShell (Core) 6+, and the limitations with respect to console-subsystem programs mentioned above.
As for a successor environment: The actively developed, cross-platform editor that offers the best PowerShell development experience is Visual Studio Code with its PowerShell extension.
As for the potential reason for the poor console support in the ISE: zett42 notes:
A possible reason why ISE developers choose not to allocate a console could stem from the historic difficulties of creating a custom, embedded console within an app's own window. Developers had to resort to hackish, unsupported ways of doing that. Only recently (2018) Windows got a dedicated pseudo-console (ConPTY) API.
The reason why is shown by this program:
#include <iostream>
#include <Windows.h>
int main() {
DWORD const file_type = GetFileType(GetStdHandle(STD_OUTPUT_HANDLE));
if (file_type == FILE_TYPE_CHAR) {
std::cout << "char" << std::endl;
} else if (file_type == FILE_TYPE_PIPE) {
std::cout << "pipe" << std::endl;
} else {
std::cout << file_type << std::endl;
}
return 0;
}
When run from PowerShell (or Command Prompt, or Git Bash), it prints:
char
But from PowerShell ISE:
pipe
WriteConsole cannot write through a pipe, and thus fails. The same thing happens when run from PowerShell / Command Prompt / Git Bash if the output is piped.

This breakpoint will not be hit

I looked at numerous posts concerning this problem but none of them apply in my case.
I have a C++ class in one file that has 3 methods. I can set a breakpoint in one method. However, I cannot set a breakpoint on any line of code in the other two methods. This class is build as a library with DEBUG set. All optimizations are turned off.
Below is the code for the two problem methods in this class.
Blockquote
#include "pch.h"
#include <stdio.h>
#include <afxwin.h>
#include <cstring>
#include <io.h>
#include <iostream>
#include <string>
#include "Log.h"
CLog::CLog()
{
ptLog = NULL; // this is the file ptr
}
void CLog::Init()
{
int iFD;
DWORD iLength;
int iStat;
HMODULE hMod;
std::string sPath;
std::string sFile;
int i;
hMod = GetModuleHandle(NULL); // handle to this execuatble
std::cout << "Module = " << hMod;
if(hMod)
{
// Use two bytes ASCII (UNICODE) if set by compiler
char acFile[120];
// Full path name of exe file
GetModuleFileName(hMod, acFile, sizeof(acFile));
std::cout << "File Name = " << acFile<<"\n";
// extract file name from full path and append .log
sPath = acFile;
i = sPath.find_last_of("\\/");
sFile = sPath.substr(i + 1);
sFile.copy(acFile, 120);
std::cout << " File Name Trunc = " << sFile;
sFile.append(".log");
iStat = fopen_s(&ptLog, sFile.data(), "a+"); // append log data to file
std::cout << "fopen stat = " << iStat;
if (iStat != 0) // failed to open error log
{
return;
}
iFD = _fileno(ptLog);
iLength = _filelength(iFD);
// Check length. If too large rename and create new file.
if (iLength > MAX_LOG_SIZE)
{
fclose(ptLog);
char acBakFile[80];
strcpy_s(acBakFile, 80, acFile);
strcat_s(acBakFile, ".bak"); // new name of old log file
remove(acBakFile); // remove previous bak file if it exists
rename(acFile, acBakFile);
fopen_s(&ptLog, acFile, "a+"); // Create new log file
}
}// end if (hMod)
}
,,,
ptLog is declared as FILE *
This class is invoked with the following code:
#include <iostream>
#include "..\Log\Log.h"
int main()
{
CLog Logger;
Logger.Init();
Logger.vLog((char *) "Hello \n");
}
Blockquote
This code is also compiled as debug. If a set a breakpoint on "Loggger.Init()"
the debugger will hit the breakpoint. If select 'Step Into' it will not enter
the code in the Init() method. The code does execute since I can see the text on the console. If I put breakpoints anywhere in the Init() method they do not break.
I did the following:
Removed log.lib from the input to the Linker.
Obviously, the Link failed due to unresolved externals.
Put back log.lib and rebuilt.
Turned off the option "Require source files that exactly match the original version"
Debug and breakpoints worked.
Enabled the option.
Retried debug and the breakpoints still worked.
Did a full rebuild and breakpoints worked.
I don't really understand it because I had performed numerous cleans and rebuilds
previously.
I did find another issue. I had '/clr' option on.
This is for Common Language Runtime support for the .lib.
The module linked to it did not have Common Language Runtime on. In this case,
the breakpoints were ignored. When I turned off '/ clr', the breakpoints
functioned properly

loadlibrary fails for current path with GetLastError() == 0

I have a simple program that loads a DLL from the current path
#include <iostream>
#include <windows.h>
using namespace std;
auto loaddll(const char * library) {
auto dllModule = LoadLibrary(library);
if(dllModule == NULL)
throw "Can't load dll";
return dllModule;
}
int main() {
try {
auto Handle = loaddll("ISab.dll");
} catch(const char * error) {
cerr << "An Unexpected error :" << error << endl;
cerr << "Get Last Error : " << GetLastError();
}
}
the load library fails for every DLL in the current path but succeeds for DLL like User.dll
if I ran it output will be like
An Unexpected error :Can't load dll
Get Last Error : 0
this also fails if i specify full path to dll
When a Win32 API call fails, and sets the error code, you must call GetLastError before calling any other Win32 API function. You don't do that.
Raising an exception, streaming to cerr etc. are all liable to call other Win32 API functions and so reset the error code.
Your code must look like this:
auto dllModule = LoadLibrary(library);
if (dllModule == NULL)
auto err = GetLastError();
Once you have the error code you should be better placed to understand why the module could not be loaded. Common error codes for LoadLibrary include:
ERROR_MOD_NOT_FOUND which means that the module, or one of its dependencies, cannot be located by the DLL search.
ERROR_BAD_EXE_FORMAT which invariably means a 32/64 bit mismatch, either with the module you load, or one of its dependencies.

Access violation while initializing matlab-compiler dll / lib in c++ only during debugging

what I'm trying to do is integrate a MATLAB-Compiler dll/lib to an new c++ project.
I followed this instruction: How do I integrate my C++ shared Library generated from MATLAB which seams working good (no build errors and intelisense is working good, so it seams all required information are there).
I'm using a very simple mathlab code / function for testing:
function output = extest( arg1,arg2 )
output = arg1+arg2;
end
And the "default" c++ code for matlab functions:
#include "extest.h"
#include <cstdlib>
#include <stdio.h>
int main(int argc, char** argv){
mclmcrInitialize();
if (!mclInitializeApplication(NULL,0)){
std::cerr << "could not initialize the application properly" << std::endl;
return -1;
}
if(!extestInitialize()){
std::cerr << "could not initialize the library properly" << std::endl;
return -1;
}
else{
try{
//code itself (not jet reached therefore removed)
}catch(const mwException& e){
std::cerr << e.what() << std::endl;
return -2;
}
catch(...){
std::cerr << "Unexpected error thrown" << std::endl;
return -3;
}
extestTerminate();
}
mclTerminateApplication();
return 0;
}
After e few moments after the debugger tries to run the line if(!extestInitialize()) the following error gets thrown.
Exception thrown at 0x000002BF72E0EE55 in DllTestingCpp.exe: 0xC0000005: Access violation reading location 0x0000000000000008.
I can hit visual studios continue > button and it is continued after lets say 20x click on it. Starting the code by ctrl + F5 (without debugging) everything is working good.
Any ideas why this happens in debug mode? Or better how I can get rid of this error?
PS: extest is my lib name and using Matlab R2017a 64bit and Visual Studio 2017 (debugging with x64),
The same problem (Matlab2017 + VS 2015) for me.
Probably there is some conflict with java used by MATLAB.
I've fixed it by
const char *args[] = {"-nojvm"};
const int count = sizeof(args) / sizeof(args[0]);
mclInitializeApplication(args, count))
instead of
mclInitializeApplication(NULL,0)
I had the same issue(using VS2019) and I found the following answer here:
https://uk.mathworks.com/matlabcentral/answers/182851-how-do-i-integrate-my-c-shared-library-generated-from-matlab-r2013b-in-visual-studio-2013
I encountered this same issue and reported it to Mathworks. They responded that for VS2013 and later, the debugger is set to break when 0xc0000005 occurs, even though in this case it is handled by the JVM.
The fix is to go to Debug>Windows>Exception Settings>Win32 and uncheck '0xc0000005 Access Violation'. In VS2012, this setting is unchecked by default.
This seems to work o.k.

Visual Studio C++ : Debug Assertion Failed

I recently tried to create a program that can read an ODBC database then write the entries in an Excel file by using the CRecordset class, the program complilates perfectly, but the problems come in the execution...
First error :
Debug Assertion Failed!
Program: C:\Windows\system32\mfc140ud.dll
File: f:\dd\vctools\vc7libs\ship\atlmfc\include\afxwin1.inl
Line: 24
Second error :
Debug Assertion Failed!
Program: C:\Windows\system32\mfc140ud.dll
File: f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\dbcore.cpp
Line: 3312
The two errors are pointing toward the mfc140ud.dll file, it's not a missing file, so it's not the problem.
Here is the function where the exception is raised:
void parseDB(CRecordset &rs, const CString &SqlString, CString strOut) {
std::cout << "test2";
rs.Open(CRecordset::snapshot, SqlString, CRecordset::readOnly);
std::string entry;
std::fstream file;
std::cout << "test3";
while(!rs.IsEOF()) {
std::cout << "test4";
rs.GetFieldValue((short)0, strOut);
CT2CA pszConvertedAnsiString = strOut;
entry = pszConvertedAnsiString;
writeXLSX(entry.c_str(), file);
rs.MoveNext();
}
rs.Close();
}
The "std::cout << "test"" are here for debugging, and my program generates these errors right after the "test2" display, so I deducted that the error comes from the "Open" line.
This is the way I initialize the CRecordset:
CString sDsn;
CDatabase db;
CRecordset rs(&db);
CString strOut;
CString SqlString;
Then, I use a CALL SQL function in a switch-case:
switch (sequence) {
case 1:
SqlString = "CALL GETCUSNAME(AGENTS)";
break;
case 2:
SqlString = "CALL GETCUSNAME(CLIENT)";
break;
default:
AfxMessageBox(_T("Wrong entry!"));
}
I searched on many sites and I couldn't find an answer, that's why I ask a question here, thanks by advance.
The first assertion comes from AfxGetResourceHandle complaining that it has not been set up correctly.
This will usually happen because you either didn't call AfxWinInit at the start of your application (if you have a console application and didn't set it up with the MFC wizard, this is very likely the case), or you're writing an MFC DLL called from non-MFC code, and you didn't add AFX_MANAGE_STATE(AfxGetStaticModuleState( )); at the start of every externally visible function.
I believe the second is because MFC requires you to wrap CALL queries in curly braces, like so: {CALL GETCUSNAME(AGENTS)}. Otherwise the call is not recognized, and code execution enters a path it is not supposed to take.