Can we use C++/Cx inside a static lib (Metro Style) - windows

I am trying to port a native sdk to windows RT and to help me I would like to implement missing functions to emulate registry access, so I have created a Static Library (File->New->Project...->Static Library (Metro Style apps) and I have declared the function like that :
// WinRT stuff
#include <windows.storage.h>
#include <wrl/client.h>
#include <wrl/wrappers/corewrappers.h>
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace ABI::Windows::Storage;
using namespace ABI::Windows::Foundation;
LSTATUS
APIENTRY
RegOpenKeyExW(
_In_ HKEY hKey,
_In_opt_ LPCWSTR lpSubKey,
_In_opt_ DWORD ulOptions,
_In_ REGSAM samDesired,
_Out_ PHKEY phkResult
)
{
LSTATUS ret = ERROR_SUCCESS;
if (hKey == NULL)
return ERROR_INVALID_HANDLE;
if (phkResult == NULL)
return ERROR_INVALID_PARAMETER;
ABI::Windows::Storage::ApplicationDataContainer^ localSettings =
ApplicationData::Current->LocalSettings;
...
}
However when I try to compile I get this error :
1>c:\users\joe\documents\visual studio 2012\projects\lib1\lib1\oal.cpp(275):
error C3699: '^' : cannot use this indirection on type
'ABI::Windows::Storage::ApplicationDataContainer'
I have checked and Consume Windows Runtime Extension (/ZW) is enabled (it's by default) so I am wondering if it's possible to use C++/CX inside a static lib?

If you're using the ABI prefix on your types, then you're referring to the low level C++ type. THe low level types are intended to be used with WRL and cannot use the C++/CX extensions like the ^ operator.
Use ComPtr localSettings instead.

Ok someone told me to add In Librarian->General->Additional Dependecies : %(AdditionalDependencies) and I have removed the ABI:: namespace. Now it works ;-)

Related

optimization options and usage of windows dll calls

I am building a dll for windows, using a Makefile, using cl.exe. I am using VS2015.. this dll uses CNG (bcrypt) for encryption operations, and bcryptr is loaded dynamically using loadlibrary call.
When i build with /Od option to disable optimization, i have no issues with any functionality. but if i use any optimization option /O1, /O2, /Ox, i see the strangest thing happen.. once i retrieve the address for a bcrypt function, such as BCryptGetFipsAlgorithmMode, using GetProcAddress, and then i make the call to that function ptr, the call stack goes away. This results in exception when the calling function tries to return.. it looks almost like when one calls a callback doesn't have the CALLBACK prefix, but i dont see the connection..
That bcrypt function's prototype looks like this:
NTSTATUS WINAPI BCryptGetFipsAlgorithmMode( __out BOOLEAN *pfEnabled)
and WINAPI seems to be defined:
define WINAPI __stdcall
Is there something I am missing? what does optimization have to do with this?
Any help would be appreciated.. Thank You!
Heres the code:
NTSTATUS GetFipsAlgorithmMode(BOOLEAN *pfEnabled )
{
FARPROC pBCryptGetFipsAlgorithmMode = NULL;
NTSTATUS (*_BCryptGetFipsAlgorithmMode)( __out BOOLEAN *);
NTSTATUS status = SPGC_ERR_LIBRARY_ADDRESS_LOOKUP_FAILURE;
if(g_hBCRYPTDLL != NULL)
{
pBCryptGetFipsAlgorithmMode = GetProcAddress(g_hBCRYPTDLL, _T("BCryptGetFipsAlgorithmMode"));
if(pBCryptGetFipsAlgorithmMode != NULL)
{
_BCryptGetFipsAlgorithmMode = (NTSTATUS (*)( __out BOOLEAN *)) pBCryptGetFipsAlgorithmMode;
status = _BCryptGetFipsAlgorithmMode(pfEnabled);
}
}
return status;
}
step over the call to _BCryptGetFipsAlgorithmMode(), and the call stack basically gets cleared.

mciSendString with Visual C++ - Parameters?

I am not a native C++ programmer, so I need some help with the following:
I got this code working:
#pragma comment(lib, "winmm.lib")
LPCWSTR openCDCommand = L"set cdaudio door open";
//comes from Windows.h, needs winmm.lib see header includes
int errCode = mciSendString(openCDCommand, 0, 0, 0);
Questions:
Do I need to work with LPCWSTR? Why didn't I find a System::String example?
How should I handle 'string concatination'? I cant simply do L"foo"+L"baar"?
Am I on the totally wrong way to play sounds with mciSendString? (actually I really want to use MCI Command and MCI sendString as i did in other projects before)
Is there another way to include the external function mciSendString so it can handle handles?
The signature of mciSendString is
MCIERROR mciSendString(
LPCTSTR lpszCommand,
LPTSTR lpszReturnString,
UINT cchReturn,
HANDLE hwndCallback);
So, regarding the first 2 parameters, in unicode it will be a wchar pointer and in multibyte it will be a char pointer. It's the signature. You cannot change that and you shouldn't worry about that.
std::wstring someString( L"Foo" );
someString.append( L"bar ");
I would play sound with core audio API, waveOut or maybe DirectSound. But, not with the mciSendString().
I'm afraid I don't understand this one.. can you explain it better?
This now works for me - took some time, but maybe in future this will help others:
#include "vcclr.h" // compile with /clr(!)
int Player::mciSendStringHandle(String ^ givenHandle)
{
pin_ptr<const wchar_t> wch = PtrToStringChars(givenHandle);
return mciSendString(wch, 0, 0, 0);
}

WinMain exported from a DLL

I am trying to hide the WinMain function inside a DLL in order to avoid typing again much of the code over and over again.
I exported wWinMain from the DLL by declaring it as
extern "C" int WINAPI wWinMain( ... )
{
// repetitive code here
}
and used the linker option /EXPORT:wWinMain, but when I try to use the import library in another project I get the error
LIBCMTD.lib(wincrt0.obj) : error LNK2019: unresolved external symbol _WinMain#16 referenced in function __tmainCRTStartup
Remark I do want to use the GUI interface and I know this is common error when you define a main instead of a WinMain function. Also, I enabled the UNICODE support in both projects. What should I do?
This is not possible as-is, the linker can only set the entrypoint for an EXE to a function that's inside the EXE. Rename the wWinMain() in the DLL to something else. Write a wWinMain() in a source code file that gets linked into your EXE, simply call the DLL's exported function.
// ...somewhere in a .cpp file within my .dll's sources...
#define WinMain WinMainOld // ...to suppress Win32 declaration of WinMain
#include <windows.h>
#undef WinMain // ...so that WinMain below is not replaced
. . .
#pragma comment(linker, "/export:_WinMain#16") // ...to export it from .dll
extern "C" // ...to suppress C++ name decoration
int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR pCmdLine, int nCmdShow)
{
. . .
}
Should you be using WinMain in a DLL? Should it not be DllMain?
If you want to call the WinMain of the dll, you need to replace the CRTWinMainStartup function(_tmainCRTStartup in your liked CRT lib), and make it call your exported WinMain, this stops the linker looking for a local WinMain and still keeps correct flow of the program(the source for the CRT startups should be in the crt source of any compiler)
I find one way to put WinMain inside DLL.
You need to use WinMain instead of wWinMain (I don't know why)
Append a def file into your project and,
append EXPORTS WinMain in def file.
Like this
EXPORTS
WinMain
From the observation, all need exported functions generated, not only WinMain.
After test, the way of __declspec(dllexport) is invalid for WinMain.
Link your program to the DLL library
use #pragma comment(lib, "testDll.lib")
or modify setting in the project.
EXPORT int WINAPI _WinMain_(int (*_main_)(int argc, char **argv), HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR commandLine, int nCmdShow);
int _XMain( int argc, char **argv );
#define XMain WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR commandLine, int nCmdShow)\
{return _WinMain_( _XMain, hInst, hPrevInstance, commandLine, nCmdShow );} \
int _XMain
Then _WinMain_() calls or schedules _XMain().
Over in your application source:
int XMain( int argc, char **argv )
{
}

SysInternal's WinObj device listing mechanism

SysInternals's WinObj can list all device objects.
I wonder how it can list the devices.
Is there any open source we can read?(or a code snippet)
What is the most significant function I should know?
WinObj uses the NT system calls NtOpenDirectoryObject and NtQueryDirectoryObject. There is no driver or kernel code needed. You won't see the imports because these NT functions are loaded via LoadLibrary/GetProcAddress.
You don't have to enumerate the entire object namespace. If you're interested in the device objects call NtOpenDirectoryObject with "\Device", then call NtQueryDirectoryObject on the returned handle.
According to SysInternals' web page:
The native NT API provides routines
that allow user-mode programs to
browse the namespace and query the
status of objects located there, but
the interfaces are undocumented.
I've tried looking at WinObj's import table (dumpbin /imports winobj.exe) but there are no obvious suspects :-(
As per the answer from user1575778 you can use NtOpenDirectoryObject and NtQueryDirectoryObject (which from user mode are identical to ZwOpenDirectoryObject and ZwQueryDirectoryObject respectively) to list the objects inside the object manager namespace.
Have a look at objmgr.hpp of NT Objects aka ntobjx, in particular at the class NtObjMgr::Directory (or DirectoryT). It provides the same functionality nicely wrapped into a C++ class. The whole utility is open source under a liberal license (dual-licensed due to WTL-use: MIT and MS-PL), so bits and pieces can be reused however you please, provided you comply with the license terms.
But here's a simple C++ code example catering just your use case:
#include <Windows.h>
#include <tchar.h>
#include <cstdio>
#include <winternl.h>
NTSTATUS (NTAPI* NtOpenDirectoryObject)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES);
NTSTATUS (NTAPI* NtQueryDirectoryObject)(HANDLE, PVOID, ULONG, BOOLEAN, BOOLEAN, PULONG, PULONG);
VOID (NTAPI* RtlInitUnicodeString_)(PUNICODE_STRING, PCWSTR);
NTSTATUS (NTAPI* NtClose_)(HANDLE);
#define DIRECTORY_QUERY (0x0001)
#define DIRECTORY_TRAVERSE (0x0002)
typedef struct _OBJECT_DIRECTORY_INFORMATION {
UNICODE_STRING Name;
UNICODE_STRING TypeName;
} OBJECT_DIRECTORY_INFORMATION, *POBJECT_DIRECTORY_INFORMATION;
#ifndef STATUS_SUCCESS
#define STATUS_SUCCESS ((NTSTATUS)0x00000000L) // ntsubauth
#endif // STATUS_SUCCESS
#ifndef STATUS_MORE_ENTRIES
#define STATUS_MORE_ENTRIES ((NTSTATUS)0x00000105L)
#endif // STATUS_MORE_ENTRIES
#ifndef STATUS_NO_MORE_ENTRIES
#define STATUS_NO_MORE_ENTRIES ((NTSTATUS)0x8000001AL)
#endif // STATUS_NO_MORE_ENTRIES
int PrintDevices()
{
NTSTATUS ntStatus;
OBJECT_ATTRIBUTES oa;
UNICODE_STRING objname;
HANDLE hDeviceDir = NULL;
RtlInitUnicodeString_(&objname, L"\\Device");
InitializeObjectAttributes(&oa, &objname, 0, NULL, NULL);
ntStatus = NtOpenDirectoryObject(&hDeviceDir, DIRECTORY_QUERY | DIRECTORY_TRAVERSE, &oa);
if(NT_SUCCESS(ntStatus))
{
size_t const bufSize = 0x10000;
BYTE buf[bufSize] = {0};
ULONG start = 0, idx = 0, bytes;
BOOLEAN restart = TRUE;
for(;;)
{
ntStatus = NtQueryDirectoryObject(hDeviceDir, PBYTE(buf), bufSize, FALSE, restart, &idx, &bytes);
if(NT_SUCCESS(ntStatus))
{
POBJECT_DIRECTORY_INFORMATION const pdilist = reinterpret_cast<POBJECT_DIRECTORY_INFORMATION>(PBYTE(buf));
for(ULONG i = 0; i < idx - start; i++)
{
if(0 == wcsncmp(pdilist[i].TypeName.Buffer, L"Device", pdilist[i].TypeName.Length / sizeof(WCHAR)))
{
_tprintf(_T("%s\n"), pdilist[i].Name.Buffer);
}
}
}
if(STATUS_MORE_ENTRIES == ntStatus)
{
start = idx;
restart = FALSE;
continue;
}
if((STATUS_SUCCESS == ntStatus) || (STATUS_NO_MORE_ENTRIES == ntStatus))
{
break;
}
}
(void)NtClose_(hDeviceDir);
return 0;
}
_tprintf(_T("Failed NtOpenDirectoryObject with 0x%08X"), ntStatus);
return 1;
}
int _tmain(int /*argc*/, _TCHAR** /*argv*/)
{
HMODULE hNtDll = ::GetModuleHandle(_T("ntdll.dll"));
*(FARPROC*)&NtOpenDirectoryObject = ::GetProcAddress(hNtDll, "NtOpenDirectoryObject");
*(FARPROC*)&NtQueryDirectoryObject = ::GetProcAddress(hNtDll, "NtQueryDirectoryObject");
*(FARPROC*)&RtlInitUnicodeString_ = ::GetProcAddress(hNtDll, "RtlInitUnicodeString");
*(FARPROC*)&NtClose_ = ::GetProcAddress(hNtDll, "NtClose");
if (!NtOpenDirectoryObject || !NtQueryDirectoryObject || !RtlInitUnicodeString_ || !NtClose_)
{
_tprintf(_T("Failed to retrieve ntdll.dll function pointers\n"));
return 1;
}
return PrintDevices();
}
Some remarks: This will not delve into subdirectories, it will not list any types other than Device and it will not resolve symbolic links, if any. For any of those features, please look at the aforementioned utility's source code and adjust as needed. winternl.h should be available in any recent Windows SDK.
The functions RtlInitUnicodeString_ and NtClose_ have a trailing underscore to avoid clashes with these native API functions, which are declared in winternl.h, but use __declspec(dllimport).
Disclosure: I am the author of ntobjx.
You can use NtOpenDirectoryObject and NtQueryDirectoryObject to enumarate the objects list in a given directory.
To get the details of the object namespace, you must use the Windows NT Undocumented API. That is also used by the WinObj as it is described here that how WinOBj getting the all results..and for those who are saying that we need a driver to do this please, read these lines on given page.
"One obvious way is to use a driver – in kernel mode everything is accessible – so the client app can get the required information by communicating with its own driver. WinObj does not use a driver, however (this is one reason it’s able to execute without admin privileges, although with admin privileges it shows all objects as opposed to partial results)."
You can start with SetupDiCreateDeviceInfoList and use other related functions to enumerate all the devices. This stuff is painful to use.

How can I get HINSTANCE from a DLL?

I have created a DLL in VC++ as Win32 project
DLLMAIN function is
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
Now I need HINSTANCE of the DLL , that need to be passed to Win32 functions.
Are HMODULE and HINSTANCE same?
How can I get HINSTANCE?
An excerpt from the book Windows Via C/C++ [1]
Note As it turns out, HMODULEs and HINSTANCEs are exactly the same thing. If the documentation for a function indicates that an HMODULE is required, you can pass an HINSTANCE and vice versa. There are two data types because in 16-bit Windows HMODULEs and HINSTANCEs identified different things
[1] Richter, Jeffery and Nasarre, Christophe, Windows Via C/C++, 5th ed, Redmond: Microsoft Press 2008, pp. 74
Microsoft linker specific
#include "windows.h"
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
#pragma warning(disable: 4047)
HINSTANCE hInstance = (HINSTANCE)&__ImageBase;
#pragma warning(default: 4047)
I think that these are the same. If you want HINSTANCE of the running process (exe), you should use
GetModuleHandle(NULL);
Calling GetModuleHandle(NULL) from a dll will return the Hinstanc of the EXE that started the DLL; to get the Hinstance for the curently running dll try this tip:
http://www.dotnet247.com/247reference/msgs/13/65259.aspx
DllMain function as it's described in MSDN:
BOOL WINAPI DllMain(
__in HINSTANCE hinstDLL,
__in DWORD fdwReason,
__in LPVOID lpvReserved
);
http://msdn.microsoft.com/en-us/library/ms682583%28v=vs.85%29.aspx
Each DLL has at least a header file, say MyDll.h and a corresponding implementation file MyDll.cpp. Open the header file and add
extern HMODULE hDllModule;//or whatever name you like
Now open the MyDll.cpp file. There is a function DLLMAIN. Add before it HMODULE hDllModule; and insert hDllModuleDll = hModule; before return true;. Your code will look like this:
HMODULE hDllModuleDll;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
hDllModuleDll = hModule;
return TRUE;
}
In functions like ::GetModuleFileNameW(hModule, PathFile, MAX_PATH); that require a HMODULE of the DLL you can pass the global variable hDllModule.
To complement the other answers, for the sake of completness.
The actual signature of DllMain has an HINSTANCE parameter, instead of a HMODULE parameter. The Visual Studio DLL template generates the signature with HMODULE since at least Visual Studio 2008 however, but I believe this to be a minor bug more than anything. VC6 generated the code with HANDLE (even though both HINSTANCE and HMODULE exist). The reason that doesn't cause problems is because HINSTANCE and HMODULE are now exactly the same thing. Unfortunately I was unable to find an ancient enough version of the MSDN documetnation that could have confirmed this.
So the answer is: You get your HINSTANCE as an argument to your DllMain.
Personally I sort of like the distinction between HMODULE and HINSTANCE because it appeals to me as being good code hygiene. It's a bit like using const. But then, a new question arises: Given your HINSTANCE, how do you get your HMODULE in the "hygienic" way?
The windowsx.h header defines GetInstanceModule, which is now a macro that just casts the HINSTANCE to HMODULE. It only exists for code compatibility, along with a bunch of very similar macros.

Resources