Direct3D11 - Access violation executing location xxx on CreateSwapChainForCoreWindow - c++

I am learning C++ and Direct3D11/Direct2D (on top of UWP) for fun, but am struggling getting my little test program to run. It throws an access violation (see below for exact exception) when I call CreateSwapChainForCoreWindow.
I used the D3D Device for other calls and they worked so I don't think that is the issue. The swap chain description is relatively straight-forward and the swap chain itself will be set in the call. So, I assume that the exception is because I am passing an incorrect pointer to the window but I can't solve it.
Exception:
Exception thrown at 0x00007FF8FE44F4E0 (Windows.UI.dll) in UWP D2D example v3.exe: 0xC0000005: Access violation executing location 0x00007FF8FE44F4E0.
Code snippet (https://github.com/cwebb95/Direct2D_cppwinrt):
ComPtr<IDXGISwapChain1> swapChain = nullptr;
DX::ThrowIfFailed(dxgiFactory->CreateSwapChainForCoreWindow(m_d3dDevice.Get(),
reinterpret_cast<IUnknown*>(&CoreWindow::GetForCurrentThread()),
&swapChainDescription,
NULL,
&swapChain));

I was able to solve my problem by changing the second parameter to:
static_cast<::IUnknown*>(winrt::get_abi(CoreWindow::GetForCurrentThread()))
from:
reinterpret_cast<IUnknown*>(&CoreWindow::GetForCurrentThread())
I am not knowledge enough yet to know why that fixed the problem, but I will research and hopefully figure it out (any leads on that question would be much appreciated).

Related

Access Violation DirectWrite

I am using the DirectWrite API and I am implementing my own layout and text rendering engine. I have already created my IDWriteTextLayout object successfully. When I make the following call I receive an Access Violation error and I have no idea why:
DWRITE_LINE_METRICS m_lineMetrics;
UINT32 m_lineCount;
DX::ThrowIfFailed(
m_textLayout->GetLineMetrics(&m_lineMetrics,31,&m_lineCount)
);
I figured it out. I guess I was interpreting the documentation for the function incorrectly. You can pass either a pointer to a single DWRITE_LINE_METRICS structure or an array of DWRITE_LINE_METRICS structures.

InvalidArgumentException when calling D3D's CreateRasterizerState1

I am working in DirectX 11 via C++ and I am getting an error when creating a raserizer state. First, here is the code:
// set up rasterizer
D3D11_RASTERIZER_DESC1 rasterizerStateDescription;
::ZeroMemory(&rasterizerStateDescription, sizeof(D3D11_RASTERIZER_DESC1));
rasterizerStateDescription.FillMode = D3D11_FILL_WIREFRAME;
ID3D11RasterizerState1* rasterizerState;
DX::ThrowIfFailed(m_d3dDevice->CreateRasterizerState1(&rasterizerStateDescription, &rasterizerState));
m_d3dContext->RSSetState(rasterizerState);
Setting FillMode there doesn't really matter - that's just included to illustrate my usage. I've tried setting all of the members, and none of them. In the debugger I can see that all of the other members have their default values.
The error is thrown at CreateRaserizerState1, and is:
First-chance exception at 0x75EC4B32 in my.exe:
Microsoft C++ exception:
Platform::InvalidArgumentException ^ at memory location 0x028DE2CC.
HRESULT:0x80070057
As far as I can tell, raserizerStateDescription and rasterizerState are both valid, so I'm not clear as to why I am getting an invalid argumet exception here.
Commenting out the CreateRasterizerState1 and RSSetState calls allow the application to run normally.
Any suggestions as to how this can be resolved?
Resolved. The problem was that I wasn't specifying DepthClipEnable == true. Because I'm targeting feature level 9.1, DepthClipEnable must be true, and because I was zeroing the memory I was effectively setting it to false.

Load image from KnownFolders into BitmapImage

auto task = create_task(Windows::Storage::KnownFolders::PicturesLibrary->GetFilesAsync(Windows::Storage::Search::CommonFileQuery::OrderBySearchRank));
task.then([&sstrpath](Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFile^>^ files)
{
CCLog("num of files detected %d",files->Size);
Platform::String^ pathstr = files->GetAt(0)->Path;
OutputDebugStringW(pathstr->Data());
auto task2 = create_task(files->GetAt(0)->OpenAsync(Windows::Storage::FileAccessMode::Read));
task2.then([](Windows::Storage::Streams::IRandomAccessStream^ filestream)
{
Windows::UI::Xaml::Media::Imaging::BitmapImage^ bmp = ref new Windows::UI::Xaml::Media::Imaging::BitmapImage();
bmp->SetSource(filestream);
}
);
}
);
This was done on a Win8 RTM with a VS express RTM in C++ (cocos2dx framework). I am trying to load an image from the Picture library and create a BitmapImage out of it. Next was to somehow use the BitmapImage for CCSprite in cococs2dx, but that's not the issue here. The program was able to run all the way into task2 but then crash at when I try to ref new the BitmmapImage. The following was in the output console
First-chance exception at 0x75004B32 in myGame.exe: Microsoft C++ exception:
Platform::WrongThreadException ^ at memory location 0x02D1D794. HRESULT:0x8001010E
First-chance exception at 0x75004B32 in myGame.exe: Microsoft C++ exception: [rethrow] at memory location 0x00000000.
First-chance exception at 0x75004B32 in myGame.exe: Microsoft C++ exception:
Platform::WrongThreadException ^ at memory location 0x02D1E5F0. HRESULT:0x8001010E
Unhandled exception at 0x622C9AD1 (msvcr110d.dll) in PixBlitz.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.
I am not really sure what I have done wrong as most tutorials out there are Javascript or XAML based for Win8 app development.
Creating tasks like that moves code onto different threads. You're getting Platform::WrongThreadException when you access an object from the wrong thread. You have to access GUI components from the same thread every time.
I believe if you RunAsync onto the Dispatcher, that will get the threading right. Pass a delegate to RunAsync, and have that delegate include creating the BitmapImage, and whatever else you want to do with the BitmapImage.
As requested, an example.
I'm not familiar with Win8 development, though I am familiar with the WPF that it's based on. (If C++/CLI supports lambdas now, I'll have to go back and revise some old answers on the subject.)
I believe this is what you want. I may have some of the syntax slightly off on that delegate.
Stream^ filesteam = files->GetAt(0)->Open(FileAccessMode::Read); // we're already on a background thread, no need for a Task if we're not going to call 'then'.
// I'm assuming 'this' is a subclass of Windows.UI.Xaml.Window, or something similar.
this->Dispatcher->RunAsync(CoreDispatcherPriority::Low, []()
{
BitmapImage^ bmp = ref new BitmapImage();
bmp->SetSource(filestream);
}
);

How can I catch an invalid fgetpos call as a C++ exception on Windows?

In Visual C++ 2008, I want to "catch" an exception generated as shown here:
try {
int foo = 20;
::fgetpos(0, (fpos_t*)&foo);
}
//...
Here are adjustments I've made to attempt a successful catch:
SEH is activated (/eha)
I've added a catch(...)
I've added a _set_se_translator vector.
I've added/adjusted to SEH syntax: __try / __except(EXCEPTION_EXECUTE_HANDLER)
In short, I've tried "everything in the book" and I still can't catch the exception. If I replace the call to ::fgetpos with int hey = foo / 0 then suddenly all of the above techniques work as expected. So the exception I'm dealing with from ::fgetpos is somehow "extra special."
Can someone explain why this ::fgetpos error seems uncatchable, and how to work around it?
update When executed in the VS IDE, the output window doesn't name an exception. All it says is this:
Microsoft Visual Studio C Runtime Library has detected a fatal error in MyProgram.exe.
Not very helpful. When I run the console app from the command line, I get a crash dialogue. The "problem details" section of the dialogue includes this information:
Problem Event Name: BEX
Exception Offset:0002fd30
Exception Code: c0000417
Exception Data: 00000000
Additional Information 1:69ad
Additional Information 2:69addfb19767b2221c8e3e7a5cd2f4ae
Additional Information 3:b1ff
Additional Information 4:b1ffca30cadddc78c19f19b6d150997f
Since the code in your dump corresponds to STATUS_INVALID_CRUNTIME_PARAMETER, try _set_invalid_parameter_handler
Most likely, the runtime catches it for you and issues a debug dialog without returning or propagating the exception- that is a CRT call and they may add whatever exception catching code in there they like. It's well within Visual Studio's rights to catch a hardware exception inside a library function, especially if you are running from within the IDE or in debug mode, then it is expected of the runtime.
Of course, when you divide by zero, then there is no library call here to write that extra catching code.

Segmentation Fault when wrapping V8 in a class?

I want to use Google's Javascript Engine V8 in a project, and attempted to write a wrapper class for the engine. Parts of the Code are copied from samples/shell.cc, from the V8 Distribution.
However, it just aborts with a Segmentation fault, and I can't figure out why, although the problem is happening around v8::internal::Top::global_context() (due to an invalid context, which appears to be NULL).. The code itself looks fine to me, but maybe I did something incredibly stupid :-).
The Segmentation fault in my Code happens in v8::Script::Compile.
Code in Question (Updated): https://gist.github.com/4c28227185a14bb6288c
Thanks to Luis G. Costantini R.'s Answer, there is no longer a problem in Set (It doesn't abort anymore), however, exposed names are still not available and will result in a ReferenceError...
Thy to change v8::Context::Scope context_scope(context); from the constructor (line 134) to internal_executeString (before script = v8::Script::Compile(source, name);). That because the destructor of the class v8::Context::Scope exits from the context.
I changed the method addFunction:
void addFunction(const std::string& fname, v8::InvocationCallback func)
{
v8::HandleScope handle_scope;
std::cout << "before ::Set()" << std::endl;
v8::Context::Scope context_scope(context);
context->Global()->Set(v8::String::New(fname.c_str()),
v8::FunctionTemplate::New(func)->GetFunction());
std::cout << "after ::Set()" << std::endl;
}
The function must be added to the global object of the context used to execute the script. There is an excellent tutorial (in two parts) of V8:
http://www.homepluspower.info/2010/06/v8-javascript-engine-tutorial-part-1.html
and
http://www.homepluspower.info/2010/06/v8-javascript-engine-tutorial-part-2.html
If you try to create an instance of JavaScript Function (FunctionTemplate::GetFunction()) or JavaScript Object (ObjectTemplate::NewInstance()) before entering the context (via Context::Scope), you get the segmentation fault. The reason: there is no JavaScript context available and both Function and Object always exist in a JavaScript execution context only. As per V8 documentation:
Function:
A JavaScript function object (ECMA-262, 15.3).
Object:
A JavaScript object (ECMA-262, 4.3.3).
The stack backtrace is almost useless unless I download all the source and try to build it myself, so... :)
Change js.executeString("1+1", true, false); to js.executeString("1+1", true, true); and see what the exception handler tells you?
Looks like you just got stung by this bug, that is if you have not already taken note of it. Perhaps submit another report since the referenced one looks old. Perhaps dig a little deeper and investigate the stack frame at every function call until the Segmentation Fault is received, you could either find a work around or the fix for this bug :)
I had a similar segmentation fault and the problem turned out to be the following. I was creating a new thread and attempting to create an object template and object in that thread. Unfortunately it seems that if you create a thread, you need to make sure that you enter a v8::Context again in order to do such things.
I got it working by passing a Handle to the v8::Context::Calling to the newly created thread and entered it in the new thread by using a scope.
I wrote this here as it is the only useful thing that comes up when I do a google search for the segmentation fault.