WinRT library not working in Release mode - c++

I've have been trying to build a desktop application using WinRT libraries in Visual Studio 2012.
The code snippet goes as follows.
[STAThread]
int wmain (Platform :: Array <String ^> ^ args)
{
wcout << L"Copyright (c) Microsoft Corporation. All rights reserved." << endl;
wcout << L"FindPackages sample" << endl << endl;
try
{
auto packageManager = ref new Windows::Management::Deployment::PackageManager();
auto packages = packageManager->FindPackages();
int packageCount = 0;
std::for_each(Windows::Foundation::Collections::begin(packages), Windows::Foundation::Collections::end(packages),
[&packageManager, &packageCount](Windows::ApplicationModel::Package^ package)
{
DisplayPackageInfo(package);
DisplayPackageUsers(packageManager, package);
wcout << endl;
packageCount += 1;
});
}
catch (AccessDeniedException^)
{
wcout << L"FindPackagesSample failed because access was denied. This program must be run from an elevated command prompt." << endl;
return 1;
}
catch (Exception^ ex)
{
wcout << L"FindPackagesSample failed, error message: " << ex->ToString()->Data() << endl;
return 1;
}
getchar();
return 0;
}
This is used to list the metro apps details. And this code works fine in DEBUG mode. But when I change it to release mode, I am getting an error:
error LNK2001: unresolved external symbol _NtProcessStartup
NOTE:
I've changed certain settings such as
Configuration properties -> C/C++-> COnsume Windows Runtime Exception to Yes(/ZW)Configuration properties -> C/C++-> Code Generation-> Enable Minimal Rebuild to NO(/gm-)Configuration properties -> C/C++-> Code Generation-> Runtime LIbrary to Multi-threaded DLL(/MD)
Its been told that these settings are mandatory for WinRT library inclusion.
So basically, I have to run my code in Multi_Threaded (/MT) format for Release mode. But /MT or /Mtd is not compatible with (/ZW) method which is necessary for WinRT libraries.
Please guide me on my mistakes.

The fact that you get a message about a missing NtProcessStartup symbol implies that the linker switch /SUBSYSTEM:NATIVE was used. Because this in the only option that requires a NtProcessStartup function instead of wmain/main. So your release mode options have somehow marked your application as a NATIVE (usually device driver) application. (Or you specifically added a /ENTRY:NtProcessStartup but that seems very unlikely to me).

Related

How to access SetThreadDescription() in Windows 2016 Server, Version 1607

If I just call SetThreadDescription() from WinAPI, it works on Windows 10, Version 2004. However, on Windows 2016 Server, 1607 it produces the following message box:
The procedure entry point SetThreadDescription could not be located in the dynamic link library
and the path to my executable program follows in the message.
According to this article:
SetThreadDescription is only available by Run Time Dynamic Linking on
Windows Server 2016, 1607.
So I tried dynamic linking as follows:
typedef HRESULT (WINAPI *TSetThreadDescription)(HANDLE, PCWSTR);
namespace {
TSetThreadDescription gpSetThreadDescription = nullptr;
}
void Initialize() {
HMODULE hKernel32 = GetModuleHandleA("Kernel32.dll");
if (hKernel32 == nullptr) {
cerr << "FATAL: failed to get kernel32.dll module handle, error: " << GetLastError() << endl;
quick_exit(5);
}
gpSetThreadDescription = reinterpret_cast<TSetThreadDescription>(
GetProcAddress(hKernel32, "SetThreadDescription"));
if (gpSetThreadDescription == nullptr) {
cerr << "FATAL: failed to get SetThreadDescription() address, error: " << GetLastError() << endl;
quick_exit(6);
}
}
This code also works on Windows 10. However, I'm getting error 127 ("The specified procedure could not be found") on Windows Server 2016.
What am I doing wrong about the run-time dynamic linking?
Apparently, despite MSDN says "DLL: Kernel32.dll", the function is actually in KernelBase.DLL, so I've fixed the problem after changing to:
HMODULE hKernelBase = GetModuleHandleA("KernelBase.dll");

Connect To Matlab 2017b from c++ vs2013

I would like to read some variable's value in Matlab from c++. I searched in Internet and found out below example in Matlab Documentation Page.
for using this example I Did below steps:
I add this include path to project :
c:\program files\Matlab\r2017b\extern\include
then I Add this path Library Directory :
c:\program Files\Matlab\r2017b\extern\lib\win64\microsoft
then I Add this library to project :
"libMatlabEngine.lib"
"libMatlabDataArray.lib"
then I placed needed DLLs beside application EXE file.
then I ran the application after that application faced with access violataion error when startMATLAB() Method has been ran.
Note: I had other problem that I resolved it. but I think that problem was very strange and may be knowing that problem help you to find main reason of my problems.
problem was : when I set dll's files path in environment variables my app didn't find dlls and get "no entry point to *.dll" run time error. but when I copy dlls beside of exe, my app saw them.(I restarted VS2013 after change environment variables.)
#include "MatlabDataArray.hpp"
#include "MatlabEngine.hpp"
#include <iostream>
void callgetVars() {
using namespace matlab::engine;
// Start MATLAB engine synchronously
std::unique_ptr<MATLABEngine> matlabPtr = startMATLAB();
// Evaluate MATLAB statement
matlabPtr->eval(convertUTF8StringToUTF16String("[az,el,r] = cart2sph(5,7,3);"));
// Get the result from MATLAB
matlab::data::TypedArray<double> result1 = matlabPtr->
getVariable(convertUTF8StringToUTF16String("az"));
matlab::data::TypedArray<double> result2 = matlabPtr->
getVariable(convertUTF8StringToUTF16String("el"));
matlab::data::TypedArray<double> result3 = matlabPtr->
getVariable(convertUTF8StringToUTF16String("r"));
// Display results
std::cout << "az: " << result1[0] << std::endl;
std::cout << "el: " << result2[0] << std::endl;
std::cout << "r: " << result3[0] << std::endl;
}
I use vs2013 and Matlab 2017b in windows 7.
Thanks for your help.

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.

"Access violation" Error on displaying string of simple Oracle Query (VS10 Exp C++)

I am struggling with an issue regarding running a SQL statement to an Oracle database through C++, using occi. My code is as follows:
#include <iostream>
#include "occi.h"
namespace oc = oracle::occi;
int main() {
std::cout << "Setting up environment...\n";
oc::Environment * env = oc::Environment::createEnvironment();
std::cout << "Setting up connection...\n";
oc::Connection * conn = env->createConnection("user","pass","server");
std::cout << "Creating statement...\n";
//Very simply query...
oc::Statement * stmt = conn->createStatement("SELECT '1' FROM dual");
std::cout << "Executing query...\n";
oc::ResultSet * rs = stmt->executeQuery();
while(rs->next()) {
std::cout << rs->getString(1) << std::endl; //Error is thrown at this line, but after printing since I can see '1' on the console.
}
stmt->closeResultSet(rs);
conn->terminateStatement(stmt);
env->terminateConnection(conn);
oc::Environment::terminateEnvironment(env);
return 0;
}
The error that is shown is:
Unhandled exception at 0x1048ad7a (msvcp100d.dll) in MyDatabaseApp.exe: 0xC0000005: Access violation reading location 0xccccccd0.
My program stops inside 'xstring' at the following line of code:
#if _ITERATOR_DEBUG_LEVEL == 0
....
#else /* _ITERATOR_DEBUG_LEVEL == 0 */
typedef typename _Alloc::template rebind<_Elem>::other _Alty;
_String_val(_Alty _Al = _Alty())
: _Alval(_Al)
{ // construct allocator from _Al
....
}
~_String_val()
{ // destroy the object
typename _Alloc::template rebind<_Container_proxy>::other
_Alproxy(_Alval);
this->_Orphan_all(); //<----------------------Code stops here
_Dest_val(_Alproxy, this->_Myproxy);
_Alproxy.deallocate(this->_Myproxy, 1);
this->_Myproxy = 0;
}
#endif /* _ITERATOR_DEBUG_LEVEL == 0 */
If I change my query to:
oc::Statement * stmt = conn->createStatement("SELECT 1 FROM dual");
and the loop statement to:
std::cout << rs->getInt(1) << std::endl;
It works fine with no errors. I think this is because getting an integer simply returns a primitive, but when an object is being returned it is blowing up (I think on a destructor, but I'm not sure why...)
I have been playing around with this for hours today, and I am pretty stuck.
Some information about my system:
OS - Windows XP
Oracle Version - 10g
IDE - Microsoft Visual Studio 2010 Express C++
My project properties are as follows:
C/C++ - General - Additional Include Directories = C:\oracle\product\10.2.0\client_1\oci\include;%(AdditionalIncludeDirectories)
C/C++ - Code Generation - Multi-threaded Debug DLL (/MDd)
Linker - General - Additional Library Directories = C:\oracle\product\10.2.0\client_1\oci\lib\msvc\vc8;%(AdditionalLibraryDirectories)
Linked - Input - Additional Dependencies = oraocci10.lib;oraocci10d.lib;%(AdditionalDependencies)
I hope I haven't been confusing with too much info... Any help or insight would be great, Thanks in advance!
EDIT If I rewrite my loop, storing the value in a local variable, the error is thrown at the end of the loop:
while(rs->next()) {
std::string s = rs->getString(1); //s is equal to "1" as expected
std::cout << s << std::endl; //This is executed successfully
} //Error is thrown here
Usually such kind of problems come from differences in build environments (IDE) of end user and provider.
Check this.
Related problems:
Unhandled exception at 0x523d14cf (msvcr100d.dll)?
Why does this program crash: passing of std::string between DLLs
First try to use correct lib and dll. If compiled in debug mode then all libs and dlls must be debug. Use VC++ Modules view to be sure that proper DLL loaded.
I was lucky with my application to have all libs compiled for MSVC2010. So I just check debug and release mode DLLs and got working application.
I revisited this issue about a month ago and I found that the MSVC2010 occi library was built for Oracle 11g. We are running Oracle 10g, so I had to use the MSVC2005 library. So I installed the outdated IDE and loaded the Debug library and it worked (for some reason the release version wouldn't work though).
EDIT
For anyone who is having the same problem I was, if downgrading the IDE from MSVC2010 to MSVC2005 with the appropriate libraries doesn't work, you could try upgrading the Oracle client from 10g to 11g and use the MSVC2010 library, as suggested by harvyS. In retrospect this would've probably been the better solution.

oracle occi getString gives _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

I am trying to do a getString on a ResultSet from a OCCI Oracle query but I always get the _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) assertion. My project is Multi-Threaded Debug and I have tried to set it to Single-Thread Debug, as I found suggested online, but that makes no difference.
I'm a bit at a loss what is causing this assertion to occur. Can someone help?
It seems I only have it with the getString() function, not with any other.
oracle::occi::Environment* environment;
oracle::occi::Connection* con;
oracle::occi::Statement* stmt;
oracle::occi::ResultSet* res;
try{
environment = oracle::occi::Environment::createEnvironment(oracle::occi::Environment::DEFAULT);
con = environment->createConnection("db", "pssw", "DATABASE");
std::cout << "created connection" << std::endl;
std::stringstream query;
query << "SELECT MOD_KEY, MOD_SCRIPTLANGUAGE, MOD_SOURCE, MOD_CODE, MOD_STYLE, MOD_TYPE ";
query << "FROM DB.MEDICAL_OBS_DEF ";
query << "WHERE MOD_KEY = 735";
stmt = con->createStatement(query.str());
res = stmt->executeQuery();
res->setMaxColumnSize(3,100);
std::cout << "executed query" << std::endl;
std::string mystring;
while (res->next())
{
/*mystring = */res->getString(3); ///_BLOCK_TYPE_IS_VALID(pHead->nBlockUse) Assert!
}
std::cout << "printed resultset" << std::endl;
stmt->closeResultSet(res);
con->terminateStatement(stmt);
environment->terminateConnection(con);
}catch(oracle::occi::SQLException &e){
std::cout<<e.what();
}
Have you linked to the debug versions of Oracle DLLs (oraocci11d.lib and oraocci11d.dll)?
It seems that your program uses the memory debugging option of Visual Studio while the Oracle DLLs you're using don't. So the error occurs because the run-time library thinks there's a memory allocation/deallocation problem.
What compiler are you using?
Make sure to download properly occi version
http://www.oracle.com/technetwork/database/occidownloads-083553.html
You must use DLL runtime:
DLL multithread Debug (/MDd) for debug with oraocci11d.lib and oraocci11d.dll
DLL multithread (/MD) for release with oraocci11.lib and oraocci11.dll
if you DB using UTF8 character set
try using following
Environment *environment = Environment::createEnvironment("AL32UTF8","UTF8");