Windows - Unable to find WMI WiFi_AdapterAssociationInfo class - windows

I am trying to execute the example at https://theroadtodelphi.wordpress.com/2011/10/15/all-about-wifi-networks-and-wifi-adapters-using-the-wmi-and-delphi/ in visual C++, wherein:
the WMI class WiFi_AdapterAssociationInfo is queried
retrieve WiFi asset information
On windows 2012 and Windows 8.1 am getting the error that unable to locate the WMI class, the code I am executing is placed below, I am getting erro code 0x80041010, please help here:
// wmiQuery.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <atlbase.h> // For ATL autorelease classes (CComBSTR, CComPtr)
#include <wbemidl.h> // For WMI
#pragma comment(lib, "wbemuuid.lib") // Link to WMI library. (Can do in library includes instead)
std::string GetOsVersionString()
{
HRESULT hr = ::CoInitializeSecurity(NULL, -1, NULL, NULL,
RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE,
NULL, EOAC_NONE, NULL);
CComPtr<IWbemLocator> pWbemLocator;
hr = pWbemLocator.CoCreateInstance(CLSID_WbemLocator);
CComPtr<IWbemServices> pWbemServices;
hr = pWbemLocator->ConnectServer(CComBSTR(L"root\\cimv2"), NULL, NULL, 0, NULL, 0, NULL, &pWbemServices);
CComPtr<IEnumWbemClassObject> pEnum;
CComBSTR cbsQuery = L"Select Version from WiFi_AdapterAssociationInfo";
hr = pWbemServices->ExecQuery(CComBSTR("WQL"), cbsQuery, WBEM_FLAG_FORWARD_ONLY, NULL, &pEnum);
ULONG uObjectCount = 0;
CComPtr<IWbemClassObject> pWmiObject;
hr = pEnum->Next(WBEM_INFINITE, 1, &pWmiObject, &uObjectCount);
CComVariant cvtVersion;
hr = pWmiObject->Get(L"SSID", 0, &cvtVersion, 0, 0);
std::string sOsVersion = CW2A(cvtVersion.bstrVal);
return sOsVersion;
}
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
std::string sOsVersion = GetOsVersionString();
::CoUninitialize();
return 0;
}

Related

NT Security API: SECURITY_DESCRIPTOR.Control, when can I see SE_OWNER_DEFAULTED?

From Windows NT security API, SE_OWNER_DEFAULTED is a flag bit from SECURITY_DESCRIPTOR_CONTROL.
MSDN states it quite briefly:
(SE_OWNER_DEFAULTED) Indicates that the SID of the owner of the security descriptor was provided by a default mechanism. This flag can be used by a resource manager to identify objects whose owner was set by a default mechanism.
I'm curious that when I can see this flag set.
I write NtfsOwner.cpp to display owner SID of an NTFS file/directory's security descriptor, and use GetSecurityDescriptorOwner to query that SE_OWNER_DEFAULTED flag, but have no chance seeing it even once.
Could somebody give me some clue. Could it be possible that SE_OWNER_DEFAULTED exhibits on other type of NT objects(not on a file/directory)?
#include <Windows.h>
#include <AclAPI.h>
#include <sddl.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <locale.h>
template<typename T1, typename T2>
bool IsSameBool(T1 a, T2 b)
{
if(a && b)
return true;
else if(!a && !b)
return true;
else
return false;
}
void myDisplayNtfsOwner(const TCHAR *szfn)
{
DWORD succ = 0;
HANDLE hFile = CreateFile(szfn,
READ_CONTROL, // dwDesiredAccess=GENERIC_READ etc
FILE_SHARE_READ|FILE_SHARE_WRITE, // shareMode
NULL, // SecuAttr, no need bcz we are opening existing file
OPEN_EXISTING, // dwCreationDisposition
FILE_FLAG_BACKUP_SEMANTICS, // this is required for open a directory
NULL);
if(hFile==INVALID_HANDLE_VALUE)
{
_tprintf(_T("Warning: CreateFile() failed!(WinErr=%d) But I will go on calling GetSecurityInfo(0xFFFFffff, ...)\n"),
GetLastError());
}
SECURITY_DESCRIPTOR *pSD = nullptr;
DWORD winerr = GetSecurityInfo(hFile, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION,
NULL, NULL, NULL, NULL,
(PSECURITY_DESCRIPTOR*)&pSD);
assert(winerr==0);
SID* psidOwner = nullptr;
BOOL isOwnerDefaulted = 0;
succ = GetSecurityDescriptorOwner(pSD, (PSID*)&psidOwner, &isOwnerDefaulted);
assert(succ);
PTSTR strOwner = nullptr;
succ = ConvertSidToStringSid(psidOwner, &strOwner);
assert(succ);
_tprintf(_T("Owner SID is: %s\n"), strOwner);
_tprintf(_T("Is owner SID defaulted? %s\n"), isOwnerDefaulted?_T("yes"):_T("no"));
assert(IsSameBool(pSD->Control & SE_OWNER_DEFAULTED, isOwnerDefaulted));
LocalFree(strOwner);
LocalFree(pSD);
CloseHandle(hFile);
}
int _tmain(int argc, TCHAR* argv[])
{
setlocale(LC_ALL, "");
if(argc==1)
{
const TCHAR *s = _T("D:\\test\\foo.txt");
_tprintf(_T("Missing parameters.\n"));
_tprintf(_T("Example:\n"));
_tprintf(_T(" NtfsOwner1 %s\n"), s);
exit(1);
}
const TCHAR *szfn = argv[1];
myDisplayNtfsOwner(szfn);
return 0;
}

How do I connect the Graphics Capture API to IMFSinkWriter

I am attempting to write some code that connects the Windows::Graphics::Capture API to IMFSinkWriter in order to capture the desktop to an MP4 file. I find that the IMFSinkWriter WriteSample function always returns 0x80070057 and I'm trying to understand why. I suspect there is a somewhat obvious mistake as I am not extremely familiar with COM, WinRT, DirectX, etc. Any ideas?
#include <iostream>
#include <Windows.h>
// XXX workaround bug in platform headers where this has a circular declaration
#include "winrt/base.h"
namespace winrt::impl
{
template <typename Async>
auto wait_for(Async const& async, Windows::Foundation::TimeSpan const& timeout);
}
// XXX
#include <dxgi.h>
#include <inspectable.h>
#include <dxgi1_2.h>
#include <d3d11.h>
#include <mfapi.h>
#include <mfidl.h>
#include <mfreadwrite.h>
#include <codecapi.h>
#include <strmif.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.System.h>
#include <winrt/Windows.Graphics.Capture.h>
#include <windows.graphics.capture.interop.h>
#include <windows.graphics.directx.direct3d11.interop.h>
#pragma comment(lib, "Mfuuid.lib")
#pragma comment(lib, "Mfplat.lib")
#pragma comment(lib, "mfreadwrite.lib")
#pragma comment(lib, "Mf.lib")
winrt::com_ptr<IMFSinkWriter> sinkWriter;
std::chrono::steady_clock::time_point firstFrameTime;
std::chrono::steady_clock::time_point lastFrameTime;
bool recordedFirstFrame = false;
void OnFrameArrived(winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool const& sender, winrt::Windows::Foundation::IInspectable const &) {
winrt::Windows::Graphics::Capture::Direct3D11CaptureFrame frame = sender.TryGetNextFrame();
std::chrono::steady_clock::time_point frameTime = std::chrono::steady_clock::now();
LONGLONG duration = 0;
LONGLONG frametime100ns;
if (!recordedFirstFrame) {
recordedFirstFrame = true;
firstFrameTime = frameTime;
frametime100ns = 0;
}
else {
frametime100ns = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - firstFrameTime).count() / 100;
duration = std::chrono::duration_cast<std::chrono::milliseconds>(frameTime - lastFrameTime).count();
}
auto surface = frame.Surface();
auto access = surface.as<Windows::Graphics::DirectX::Direct3D11::IDirect3DDxgiInterfaceAccess>();
winrt::com_ptr<ID3D11Texture2D> texture;
winrt::check_hresult(access->GetInterface(winrt::guid_of<ID3D11Texture2D>(), texture.put_void()));
IMFMediaBuffer* buffer;
MFCreateDXGISurfaceBuffer(__uuidof(ID3D11Texture2D), texture.get(), 0, FALSE, &buffer);
IMFSample *sample;
winrt::check_hresult(MFCreateSample(&sample));
HRESULT hr = sample->AddBuffer(buffer);
printf("add buffer! %x\n", hr);
hr = sample->SetSampleTime(frametime100ns);
printf("set sample time (%lld) %d\n", frametime100ns, hr);
hr = sample->SetSampleDuration(duration);
printf("set sample duration (%lld) %d\n", duration, hr);
hr = sinkWriter->WriteSample(0 /* video stream index */, sample);
printf("wrote sample %x\n", hr);
lastFrameTime = frameTime;
}
int main()
{
winrt::init_apartment(winrt::apartment_type::multi_threaded);
winrt::check_hresult(MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET));
// get a list of monitor handles
std::vector<HMONITOR> monitors;
EnumDisplayMonitors(
nullptr, nullptr,
[](HMONITOR hmon, HDC, LPRECT, LPARAM lparam) {
auto& monitors = *reinterpret_cast<std::vector<HMONITOR>*>(lparam);
monitors.push_back(hmon);
return TRUE;
},
reinterpret_cast<LPARAM>(&monitors)
);
//get GraphicsCaptureItem for first monitor
auto interop_factory = winrt::get_activation_factory<winrt::Windows::Graphics::Capture::GraphicsCaptureItem, IGraphicsCaptureItemInterop>();
winrt::Windows::Graphics::Capture::GraphicsCaptureItem item = { nullptr };
winrt::check_hresult(
interop_factory->CreateForMonitor(
monitors[0],
winrt::guid_of<ABI::Windows::Graphics::Capture::IGraphicsCaptureItem>(),
winrt::put_abi(item)
)
);
// Create Direct 3D Device
winrt::com_ptr<ID3D11Device> d3dDevice;
winrt::check_hresult(D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT,
nullptr, 0, D3D11_SDK_VERSION, d3dDevice.put(), nullptr, nullptr));
winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice device;
const auto dxgiDevice = d3dDevice.as<IDXGIDevice>();
{
winrt::com_ptr<::IInspectable> inspectable;
winrt::check_hresult(CreateDirect3D11DeviceFromDXGIDevice(dxgiDevice.get(), inspectable.put()));
device = inspectable.as<winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice>();
}
auto idxgiDevice2 = dxgiDevice.as<IDXGIDevice2>();
winrt::com_ptr<IDXGIAdapter> adapter;
winrt::check_hresult(idxgiDevice2->GetParent(winrt::guid_of<IDXGIAdapter>(), adapter.put_void()));
winrt::com_ptr<IDXGIFactory2> factory;
winrt::check_hresult(adapter->GetParent(winrt::guid_of<IDXGIFactory2>(), factory.put_void()));
ID3D11DeviceContext* d3dContext = nullptr;
d3dDevice->GetImmediateContext(&d3dContext);
// setup swap chain
DXGI_SWAP_CHAIN_DESC1 desc = {};
desc.Width = static_cast<uint32_t>(item.Size().Width);
desc.Height = static_cast<uint32_t>(item.Size().Height);
desc.Format = static_cast<DXGI_FORMAT>(winrt::Windows::Graphics::DirectX::DirectXPixelFormat::R16G16B16A16Float);
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.BufferCount = 2;
desc.Scaling = DXGI_SCALING_STRETCH;
desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
desc.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
winrt::com_ptr<IDXGISwapChain1> swapchain;
winrt::check_hresult(factory->CreateSwapChainForComposition(d3dDevice.get(), &desc, nullptr, swapchain.put()));
auto framepool = winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool::CreateFreeThreaded(device, winrt::Windows::Graphics::DirectX::DirectXPixelFormat::R16G16B16A16Float, 2, item.Size());
auto session = framepool.CreateCaptureSession(item);
framepool.FrameArrived(OnFrameArrived);
//Setup MF output stream
winrt::com_ptr<IMFDXGIDeviceManager> devManager;
UINT resetToken;
winrt::check_hresult(MFCreateDXGIDeviceManager(&resetToken, devManager.put()));
winrt::check_hresult(devManager->ResetDevice(d3dDevice.get(), resetToken));
winrt::com_ptr<IMFByteStream> outputStream;
winrt::check_hresult(MFCreateFile(MF_ACCESSMODE_READWRITE, MF_OPENMODE_DELETE_IF_EXIST, MF_FILEFLAGS_NONE, L"C:\\test.mp4", outputStream.put()));
//configure MF output media type
winrt::com_ptr<IMFMediaType> videoMediaType;
//winrt::com_ptr<IMFMediaType> audioMediaType;
//for video
winrt::check_hresult(MFCreateMediaType(videoMediaType.put()));
winrt::check_hresult(videoMediaType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video));
winrt::check_hresult(videoMediaType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_H264));
winrt::check_hresult(videoMediaType->SetUINT32(MF_MT_AVG_BITRATE, 2000000));
winrt::check_hresult(videoMediaType->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive));
winrt::check_hresult(videoMediaType->SetUINT32(MF_MT_MPEG2_PROFILE, eAVEncH264VProfile_Main));
winrt::check_hresult(videoMediaType->SetUINT32(MF_MT_YUV_MATRIX, MFVideoTransferMatrix_BT601));
winrt::check_hresult(MFSetAttributeSize(videoMediaType.get(), MF_MT_FRAME_SIZE, item.Size().Width, item.Size().Height));
winrt::check_hresult(MFSetAttributeRatio(videoMediaType.get(), MF_MT_FRAME_RATE, 30, 1));
winrt::check_hresult(MFSetAttributeRatio(videoMediaType.get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1));
//Creates a streaming writer
winrt::com_ptr<IMFMediaSink> mp4StreamSink;
winrt::check_hresult(MFCreateMPEG4MediaSink(outputStream.get(), videoMediaType.get(), NULL, mp4StreamSink.put()));
//setup MF Input stream
winrt::com_ptr<IMFMediaType> inputVideoMediaType;
HRESULT hr = S_OK;
GUID majortype = { 0 };
MFRatio par = { 0 };
hr = videoMediaType->GetMajorType(&majortype);
if (majortype != MFMediaType_Video)
{
throw new winrt::hresult_invalid_argument();
}
// Create a new media type and copy over all of the items.
// This ensures that extended color information is retained.
winrt::check_hresult(MFCreateMediaType(inputVideoMediaType.put()));
winrt::check_hresult(videoMediaType->CopyAllItems(inputVideoMediaType.get()));
// Set the subtype.
winrt::check_hresult(inputVideoMediaType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_ARGB32));
// Uncompressed means all samples are independent.
winrt::check_hresult(inputVideoMediaType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE));
// Fix up PAR if not set on the original type.
hr = MFGetAttributeRatio(
inputVideoMediaType.get(),
MF_MT_PIXEL_ASPECT_RATIO,
(UINT32*)&par.Numerator,
(UINT32*)&par.Denominator
);
// Default to square pixels.
if (FAILED(hr))
{
winrt::check_hresult(MFSetAttributeRatio(
inputVideoMediaType.get(),
MF_MT_PIXEL_ASPECT_RATIO,
1, 1
));
}
winrt::check_hresult(MFSetAttributeSize(inputVideoMediaType.get(), MF_MT_FRAME_SIZE, item.Size().Width, item.Size().Height));
inputVideoMediaType->SetUINT32(MF_MT_VIDEO_ROTATION, MFVideoRotationFormat_0); //XXX where do we get the rotation from?
winrt::com_ptr<IMFAttributes> attributes;
winrt::check_hresult(MFCreateAttributes(attributes.put(), 6));
winrt::check_hresult(attributes->SetGUID(MF_TRANSCODE_CONTAINERTYPE, MFTranscodeContainerType_MPEG4));
winrt::check_hresult(attributes->SetUINT32(MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, 1));
winrt::check_hresult(attributes->SetUINT32(MF_MPEG4SINK_MOOV_BEFORE_MDAT, 1));
winrt::check_hresult(attributes->SetUINT32(MF_LOW_LATENCY, FALSE)); ///XXX should we?
winrt::check_hresult(attributes->SetUINT32(MF_SINK_WRITER_DISABLE_THROTTLING, FALSE)); //XX shuold we?
// Add device manager to attributes. This enables hardware encoding.
winrt::check_hresult(attributes->SetUnknown(MF_SINK_WRITER_D3D_MANAGER, devManager.get()));
//winrt::com_ptr<IMFSinkWriter> sinkWriter;
winrt::check_hresult(MFCreateSinkWriterFromMediaSink(mp4StreamSink.get(), attributes.get(), sinkWriter.put()));
sinkWriter->SetInputMediaType(0, inputVideoMediaType.get(), nullptr);
winrt::com_ptr<ICodecAPI> encoder;
sinkWriter->GetServiceForStream(0 /* video stream index */, GUID_NULL, IID_PPV_ARGS(encoder.put()));
VARIANT var;
VariantInit(&var);
var.vt = VT_UI4;
var.ulVal = eAVEncCommonRateControlMode_Quality;
winrt::check_hresult(encoder->SetValue(&CODECAPI_AVEncCommonRateControlMode, &var));
var.ulVal = 70;
winrt::check_hresult(encoder->SetValue(&CODECAPI_AVEncCommonQuality, &var));
winrt::check_hresult(sinkWriter->BeginWriting());
session.StartCapture();
std::cout << "Hello World!\n";
Sleep(1000);
session.Close();
sinkWriter->Flush(0);
sinkWriter->Finalize();
}
I was able to track down the problem. The above code had two issues:
Need to call SetCurrentLength() on the IMFMediaBuffer object. It seems silly since the way to get the length is to get the IMF2DBuffer interface from the IMFMediaBuffer object and call GetContiguousLength(), but it works.
Taking the texture straight from the OnFrameArrived() callback and passing it into the IMF sink is also wrong. This will exhaust the framepool (which is declared as having 2 frames) and hang the encoder. One possible solution is to copy the data out into a new texture before passing it to the encoder.

MFCreateDeviceSource returns error 0x80070002 for webcam

I'm currently trying to implement webcam video capture into a project.
First I was trying Direct Show, which worked on one computer but not on another.
So now I'm trying Media Foundation.
I mostly followed the examples provided by Microsoft.
Upon calling MFCreateDeviceSource() I receive the error code 0x80070002 (-2147024894).
This error code is not really documented in this context.
I get this result for three separate webcams of two different types of webcam, all of which work with other programs using Direct Show (eg VLC).
Thank you for any hint.
Operating system: Windows7
SDK: Windows SDK v7.1
IDE: Visual Studio 2008
Code:
// MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET) -- is called successfully in a previous function)
IMFMediaSource* media_source = 0;
IMFSourceReader* source_reader = 0;
IMFAttributes* pAttributes = 0;
hr = MFCreateAttributes(&pAttributes, 2);
if (FAILED(hr)) {
return false;
}
// Set the device type to video.
hr = pAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
if (FAILED(hr)) {
return false;
}
// Set the symbolic link.
hr = pAttributes->SetString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,(LPCWSTR)&device_name);
if (FAILED(hr)) {
return false;
}
// Create device source interface
hr = MFCreateDeviceSource(pAttributes, &media_source);
if (FAILED(hr)) {
// HERE I RECEIVE 0x80070002
return false;
}
// Create source reader
IMFAttributes* attr;
MFCreateAttributes(&attr,1);
attr->SetUINT32(MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING,1);
hr = MFCreateSourceReaderFromMediaSource(media_source,attr,&source_reader);
if(FAILED(hr)) {
return false;
}
I edited your code to actually get the device name through enumerating capture devices present in the system and it worked fine, it lacks proper error checking, but I suggest you try the same, enumerate the devices and get the symbolic link from the actual device to see if that is the issue:
#include <mfapi.h>
#include <mfidl.h>
#include <mfreadwrite.h>
#pragma comment(lib, "mfplat.lib")
#pragma comment(lib, "mf.lib")
#pragma comment(lib, "mfreadwrite.lib")
int main(int argc, char** argv)
{
HRESULT hr;
hr = ::CoInitialize(NULL);
if (FAILED(hr))
abort();
hr = ::MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET);
if (FAILED(hr))
abort();
IMFMediaSource* media_source = 0;
IMFSourceReader* source_reader = 0;
IMFAttributes* pAttributes = 0;
hr = MFCreateAttributes(&pAttributes, 2);
if (FAILED(hr))
abort();
// Set the device type to video.
hr = pAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
if (FAILED(hr))
abort();
UINT32 count;
IMFActivate **ppDevices = NULL;
hr = MFEnumDeviceSources(pAttributes, &ppDevices, &count);
if (FAILED(hr))
abort();
if (count == 0)
abort();
// Create the media source object.
IMFMediaSource *pSource = NULL;
hr = ppDevices[0]->ActivateObject(IID_PPV_ARGS(&pSource));
if (FAILED(hr))
abort();
pSource->AddRef();
IMFAttributes* pSourceAttributes;
hr = pSource->QueryInterface(__uuidof(IMFAttributes), (void**)&pSourceAttributes);
if (FAILED(hr))
abort();
const size_t nDeviceNameSize = 1024;
LPWSTR pDeviceName = new WCHAR[nDeviceNameSize];
UINT32 nActualBufferSize;
hr = pSourceAttributes->GetString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK, pDeviceName, nDeviceNameSize, &nActualBufferSize);
if (FAILED(hr))
abort();
// Set the symbolic link.
hr = pAttributes->SetString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,pDeviceName);
if (FAILED(hr))
abort();
// Create device source interface
hr = MFCreateDeviceSource(pAttributes, &media_source);
if (FAILED(hr)) // HERE I RECEIVE 0x80070002
abort();
// Create source reader
IMFAttributes* attr;
MFCreateAttributes(&attr,1);
attr->SetUINT32(MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING,1);
hr = MFCreateSourceReaderFromMediaSource(media_source,attr,&source_reader);
if(FAILED(hr))
abort();
::CoUninitialize();
return EXIT_SUCCESS;
}
Hope this helps.

Getting the version of Renesas USB 3.0 Host Controller driver on Windows

Older versions of the Renesas USB 3.0 Host Controller have issues that may cause problems. To alert my customers of such problems, I need to detect outdated versions. To do this, I want to retrieve the running driver version same as the Renesas USB 3.0 Host Controller Utility does.
With OSR IrpTracker, I've determined the IOCTL and structure. Here's sample code that opens each Renesas USB Host Controller's device interface and queries the version number.
#include <initguid.h>
#include <windows.h>
#include <setupapi.h>
#include <stdlib.h>
#include <winioctl.h>
#include <pshpack1.h>
DEFINE_GUID(GUID_DEVINTERFACE_NUSB3XHC, 0xac051b02L, 0x603b, 0x4b3c, 0xb1, 0x4b, 0x95, 0xc9, 0x26, 0x8d, 0xe0, 0x81);
struct NUSB3XHC_DRIVER_VERSION
{
UCHAR Major;
UCHAR Minor;
UCHAR Build;
UCHAR Revision;
UCHAR Unknown[2]; // no idea what this is -- {0, 0} on my machine
};
struct NUSB3XHC_FIRMWARE_VERSION
{
USHORT BcdVersion; // UI displays this as BCD
};
#define IOCTL_NUSB3XHC_GET_DRIVER_VERSION CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_NUSB3XHC_GET_FIRMWARE_VERSION CTL_CODE(FILE_DEVICE_UNKNOWN, 0x808, METHOD_BUFFERED, FILE_ANY_ACCESS)
#include <poppack.h>
BOOL GetVersion(LPCTSTR DevicePath, NUSB3XHC_DRIVER_VERSION* DriverVersion, NUSB3XHC_FIRMWARE_VERSION* FirmwareVersion)
{
HANDLE hDevice = CreateFile(DevicePath, GENERIC_ALL, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hDevice == NULL)
return FALSE;
BOOL success = FALSE;
DWORD returned;
if (DeviceIoControl(hDevice, IOCTL_NUSB3XHC_GET_DRIVER_VERSION, NULL, 0, DriverVersion, sizeof(NUSB3XHC_DRIVER_VERSION), &returned, NULL))
{
success = (returned == sizeof(NUSB3XHC_DRIVER_VERSION));
}
if (DeviceIoControl(hDevice, IOCTL_NUSB3XHC_GET_FIRMWARE_VERSION, NULL, 0, FirmwareVersion, sizeof(NUSB3XHC_FIRMWARE_VERSION), &returned, NULL))
{
success = success && (returned == sizeof(NUSB3XHC_FIRMWARE_VERSION));
}
CloseHandle(hDevice);
return success;
}
int _tmain(int argc, _TCHAR* argv[])
{
int crap = IOCTL_NUSB3XHC_GET_FIRMWARE_VERSION;
HDEVINFO hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_NUSB3XHC, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
if (hDevInfo != INVALID_HANDLE_VALUE)
{
SP_DEVICE_INTERFACE_DATA devIfaceData;
devIfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
DWORD Index = 0;
do
{
if (!SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &GUID_DEVINTERFACE_NUSB3XHC, Index, &devIfaceData))
break; // hopefully ERROR_NO_MORE_ITEMS
DWORD requiredSize;
SetupDiGetDeviceInterfaceDetail(hDevInfo, &devIfaceData, NULL, NULL, &requiredSize, NULL);
// returns with ERROR_INSUFFICIENT_BUFFER
PSP_DEVICE_INTERFACE_DETAIL_DATA devIfaceDetailData =
(PSP_DEVICE_INTERFACE_DETAIL_DATA) malloc(requiredSize);
devIfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &devIfaceData, devIfaceDetailData, requiredSize, NULL, NULL))
{
NUSB3XHC_DRIVER_VERSION driverVersion;
NUSB3XHC_FIRMWARE_VERSION firmwareVersion;
if (GetVersion(devIfaceDetailData->DevicePath, &driverVersion, &firmwareVersion))
{
_tprintf(_T("%s: driver version: %d.%d.%d.%d, firmware version: %x\n"), devIfaceDetailData->DevicePath,
driverVersion.Major,
driverVersion.Minor,
driverVersion.Build,
driverVersion.Revision,
firmwareVersion.BcdVersion);
}
else
{
_tprintf(_T("Failed getting version data from %s.\n"), devIfaceDetailData->DevicePath);
}
}
free(devIfaceDetailData);
++Index;
}
while(1);
}
return 0;
}

0xc000007b Error - but all DLLs are 32 bit

I am compiling my C++ code with /clr option using Visual Studio 2008 on Windows 7 32 bit OS targeting .NET Framework 3.5.
All the DLLs are 32 bit (verified using Dependency Walker).
As per my research this error comes up when 32 bit code calls 64 bit DLLs but this not the case here.
Are there any other root causes of error 0xc000007b?
Just happened to resolve this issue.
It seems that this error is not only caused by mixing 64 bit libraries in 32 bit code but also when libraries are messed up - in my case I was using binary PCRE library.
I built PCRE myself using MingW and now everything works fine.
For use .NET FW 4.0, you should use legacy activation shim code to load .NET FW as COM component
into your hosting app, like this:
Use macro
#define LEGACY_ACTIVATION_SHIM_ALLOW_LEGACY_API_FALLBACK
Sudoku.Runtime.h:
#pragma once
//
extern "C" int wWinMainCRTStartup();
Sudoku.Runtime.cpp:
// Sudoku.Runtime.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
int _runtime()
{
wWinMainCRTStartup();
return 0;
}
int APIENTRY _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
try
{
//CoInitializeEx(NULL, 0);
//CoUninitialize();
HRESULT hr;
ICorRuntimeHost *pHost = NULL;
hr = LegacyActivationShim::CorBindToRuntimeEx(NULL, NULL, STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN_HOST, CLSID_CorRuntimeHost, IID_ICorRuntimeHost, reinterpret_cast<LPVOID*>(&pHost));
if (!FAILED(hr))
{
IUnknown *pAppDomainPunk = NULL;
hr = pHost->CreateDomainEx(TEXT("_runtime"), NULL, NULL, &pAppDomainPunk);
if (!FAILED(hr))
{
_::_AppDomain *pDefaultDomain = NULL;
hr = pAppDomainPunk->QueryInterface(__uuidof(_::_AppDomain), reinterpret_cast<LPVOID*>(&pDefaultDomain));
if (!FAILED(hr))
{
_::_ObjectHandle *pObjHandle = NULL;
hr = pDefaultDomain->CreateInstance(_bstr_t("Sudoku"), _bstr_t("Sudoku.Runtime"), &pObjHandle);
if (!FAILED(hr))
{
VARIANT v;
VariantInit(&v);
hr = pObjHandle->Unwrap(&v);
if (!FAILED(hr))
{
_::IRuntime *pRemotingHost = NULL;
hr = v.pdispVal->QueryInterface(__uuidof(_::IRuntime), (void**) &pRemotingHost);
if (!FAILED(hr))
{
::System::Reflection::Assembly^ ra = Assembly::GetExecutingAssembly();
array<::System::Byte>^ bytes = ra->GetName()->GetPublicKeyToken();
SAFEARRAY *psa = SafeArrayCreateVector(VT_UI1, 0, bytes->Length);
BYTE *pData;
hr = SafeArrayAccessData(psa, (void **)&pData);
if (!FAILED(hr))
{
for(int i=0; i < bytes->Length; i++) pData[i] = bytes[i];
hr = SafeArrayUnaccessData(psa);
if (!FAILED(hr))
{
pRemotingHost->Run(psa);
}
pHost->UnloadDomain(pAppDomainPunk);
}
}
pObjHandle->Release();
}
pDefaultDomain->Release();
}
pAppDomainPunk->Release();
}
pHost->Release();
}
LegacyActivationShim::CorExitProcess(0);
}
}
catch(...)
{
}
return 0;
}
stdafx.h:
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
// TODO: reference additional headers your program requires here
// Exclude rarely-used stuff from Windows headers
#define VC_EXTRALEAN
#define WIN32_LEAN_AND_MEAN
#import <mscorlib.tlb> auto_rename \
rename("value", "___value") \
rename("ReportEvent", "___ReportEvent") \
rename_namespace("_") \
raw_interfaces_only \
high_property_prefixes("_get","_put","_putref")
#import "..\\Public\\Sudoku.tlb" auto_rename \
rename_namespace("_") \
raw_interfaces_only \
high_property_prefixes("_get","_put","_putref")
// C RunTime Header Files
#include <tchar.h>
#include "cor.h"
#include "mscoree.h"
#include "strongname.h"
#include "Sudoku.Runtime.h"
#include "AssemblyInfo.h"
#include "Resource.h"
#define LEGACY_ACTIVATION_SHIM_ALLOW_LEGACY_API_FALLBACK
#include "LegacyActivationShimDelayLoad.h"
LegacyActivationShim.h:
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// LegacyActivationShim.h
//
// This file allows simple migration from .NET Runtime v2 Host Activation APIs
// to the .NET Runtime v4 Host Activation APIs through simple shim functions.
// To use, just include this header file after the header file that declares the
// deprecated APIs you are using, and append the "LegacyActivationShim::" namespace
// in front of all deprecated API calls.
//
// For example,
// #include "mscoree.h"
// ...
// CorBindToRuntimeEx(
// NULL, NULL, 0, CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (LPVOID *)&pRH));
// becomes
// #include "mscoree.h"
// #include "LegacyActivationShim.h"
// ...
// LegacyActivationShim::CorBindToRuntimeEx(
// NULL, NULL, 0, CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (LPVOID *)&pRH));
//
// To enable fallback to the legacy APIs when v4.0 is not installed on the machine,
// define LEGACY_ACTIVATION_SHIM_ALLOW_LEGACY_API_FALLBACK before including this
// header file.
//
// To use the legacy API fallback in a delay-loaded fashion, include LegacyActivationShimDelayLoad.h
// instead.
//
Sudoku.Runtime.cs:
[Serializable]
[ComVisible(true)]
[Obfuscation(Exclude = true)]
public class Runtime : IRuntime
{
public void Run(byte[] publikKeyToken)
{
Application.Run(publikKeyToken);
}
}
[ComVisible(true)]
[Obfuscation(Exclude = true)]
public interface IRuntime
{
void Run(byte[] publikKeyToken);
}

Resources