how to resolve AccessViolationException - access-violation

Could you please help in resolving the below mentioned issue:
Following are the code snippet:
Managed code (VC++) - wrapper code:
Method-1:
void displayString(std::string abc)
{
std::string xyz=abc;
std::cout<<xyz;
}
Method-2:
void sendData(System::String^ input)
{
char* inputData = (char*)Marshal::StringToHGlobalAnsi(input).ToPointer();
std::string argData = inputData;
displayString(argData); //Working fine
//passing string instance to unmanaged code
/* while execution the below line the system throws: _CrtIsValidHeapPointer(pUserData), _BLOCK_TYPE_IS_VALID(pHead->nBlockUse), HEAP CORRUPTION DETECTED, and finally AccessViolationException */
sendDisplayString(argData); //AccessViolationException
sendDisplayString("Hello"); //AccessViolationException
}
unmanaged code C++ dll:
void sendDisplayString(std::string input)
{
std::cout<<input;
}
Note: Searched in all provided link but there is no resolution for this issue. All the links route to MSDN marshalling page.
Thanks in advance.

I guess it answers your question: http://support.microsoft.com/kb/172396

Related

C++/WinRT: CoreApplication::Run(IFrameworkViewSource const&) is throwing E_INVALIDARG

I'm trying to figure out why at this point in the code I'm getting an E_INVALIDARG hresult:
// main.cpp
class App : public implements<App, IFrameworkView>
{
// stuff ...
};
class AppFactory : public implements<AppFactory, IFrameworkViewSource>
{
public:
IFrameworkView CreateView()
{
return make<App>();
}
};
int WINAPI wWinMain(
_In_ HINSTANCE,
_In_ HINSTANCE,
_In_ LPWSTR,
_In_ int)
{
init_apartment();
auto vpf = make<AppFactory>();
CoreApplication::Run(vpf); // <-- throwing E_INVALIDARG somewhere inside CoreApplication::Run
uninit_apartment();
return S_OK;
}
I'd have expected a compile error if I didn't do something required by a class inheriting implements<AppFractory, IFrameworkViewSource>, but as far as I know I'm checking (static) boxes.
fwiw the exception is triggered here:
// Windows.ApplicationModel.Core.h
template <typename D> auto consume_Windows_ApplicationModel_Core_ICoreApplication<D>::Run(winrt::Windows::ApplicationModel::Core::IFrameworkViewSource const& viewSource) const
{
check_hresult(WINRT_IMPL_SHIM(winrt::Windows::ApplicationModel::Core::ICoreApplication)->Run(*(void**)(&viewSource)));
}
The thing inside check_result(...) is what's returning E_INVALIDARG, and subsequently triggering the exception. I'm not a super expert at writing windows applications, largely still in the "copy the template and hope it works while trying to understand something" phase. If there's some kind of tool I should be using to understand what the actual argument I'm passing is that is invalid, I'd appreciate some kind of pointer. I would think if I'm not passing the correct thing here, the strong type check of the argument would trigger a compile error and I'd have an opportunity to address the issue.
Honestly I'm lost here, would appreciate a hint towards where to look to resolve my issue. Thank you.
Update:
Don't know if this is relevant but in the Output tab in VS a line prints out:
Exception thrown at 0x00007FFA6D9A4FD9 (KernelBase.dll) in MyProgram.exe: WinRT originate error - 0x80070057 : 'serverName'.
I have no idea what this is... "serverName"? I don't even see a mention of this in the CoreApplication::Run docs.

Crash in UpdateRenderTargetView methode DirectX12

So I looked into some tutorials for DirectX12 and when I copied the code that I downloaded from here it worked but when I brought them into a class and wanted to use it, it just crashes in UpdateRenderTargetView method at the m_BackBuffers[i] = backBuffer;
It says:
Exception thrown at 0x00007FF831C65FA1 (d3d10warp.dll) in Hazelnut.exe: 0xC0000005: Access violation writing location
The Code:
void D3D12Core::UpdateRenderTargetViews(ComPtr<IDXGISwapChain4> swapChain, ComPtr<ID3D12DescriptorHeap> descriptorHeap)
{
auto rtvDescriptorSize = m_Device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(descriptorHeap->GetCPUDescriptorHandleForHeapStart());
for (int i = 0; i < m_BufferCount; ++i)
{
ComPtr<ID3D12Resource> BackBuffer;
swapChain->GetBuffer(i, IID_PPV_ARGS(&BackBuffer));
m_Device->CreateRenderTargetView(BackBuffer.Get(), nullptr, rtvHandle);
m_BackBuffers[i] = BackBuffer;
rtvHandle.Offset(rtvDescriptorSize);
}
}
Class members That I used in function:
class D3D12Core
{
public:
//Some members
static const uint8_t m_BufferCount = 3;
ComPtr<ID3D12Resource> m_BackBuffers[m_BufferCount];
private:
ComPtr<ID3D12Device2> m_Device;
//Some members
};
I tried everything that I could but didn't find the cause.
Normally it shouldn't crash at all.
Please be gentle.I'm new to Stackoverflow.
Any help will be appreciated.
Edit:
D3D12Core
D3D12Core Implementation
And I use it like this:
auto commnadQueue = D3D12Core::Get().GetCommandQueue(D3D12_COMMAND_LIST_TYPE_DIRECT);
m_SwapChain = D3D12Core::Get().CreateSwapChain(m_WindowHandle, commnadQueue->GetD3D12CommandQueue(), m_Width, m_Height);
m_RTVDescriptorHeap = D3D12Core::Get().CreateDescriptorHeap(1, D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
D3D12Core::Get().UpdateRenderTargetViews(m_SwapChain, m_RTVDescriptorHeap);
the UpdateRenderTargetViews function will get call by another function in window class that will be used for WndProc.
I didn't write in which class or file this written I don't think it will be necessary.
Well after you provided some more source code, I am pretty sure the mistake is here:
m_RTVDescriptorHeap = D3D12Core::Get().CreateDescriptorHeap(1, D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
which should actually be
m_RTVDescriptorHeap = D3D12Core::Get().CreateDescriptorHeap(D3D12Core::m_BufferCount, D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
You are offseting the handle in a for loop which goes out of bounds in second iteration.

Excetpion handling in c++/cli

Actually i am working on c++/CLI dll which is using C# dll and c++/cli dll will use from native c.
c++/cli code is like:-
public ref class Class1
{
// TODO: Add your methods for this class here.
public:
static Managed_EMV_DLL::Managed_EMV ^obj = gcnew Managed_EMV(); // object of c# class
bool INIT_READER(unsigned int *);
bool READ_KEY(unsigned int *ERROR_CODE,unsigned char *RETURN_ARRAY, unsigned int *Array_LENGTH);
};
-i want to handle the exception in c++/CLI code,
-handle exception when c# dll not found.
how i can make it.
What is the exact problem you're facing .... See the below example format.
try
{
}
catch(FormatException ^) // display an appropriate message
{
Console::WriteLine(L"You must enter a valid number "
L"and no other character!");
}
Just sort out what exception could be thrown from C# dll and then put appropriate handles in your C++/CLI code.
I want to handle any kind of exception not only FormatException or TypeInitializationException.
Here i write code like:-
try
{
}
catch (Exception^ ex)
{
Console::WriteLine("Error in C++/CLI INIT function: {0}", ex->ToString());
}
catch (...)
{
Console::WriteLine("Error in INIT");
}
and it works good.... i hope it will catch any kind of exception...

Managed C++, Object reference not set to an instance of an object

I've run into this problem before, but never in a situation like this. I'm completely confused. As the question states, I'm getting the runtime error "Object reference not set to an instance of an object." Using the debugger tools, I think I've pinpointed the problem to this line:
dataFileLocation = path;
The entire function is here:
void DATReader::SetPath(String^ path)
{
if(!File::Exists(path))
{
MessageBox::Show( "DATReader (missing dat file: \n"+path+"\n )", "Error", MessageBoxButtons::OK, MessageBoxIcon::Exclamation);
return;
}
dataFileLocation = path;
}
dataFileLocation is declared here, but nothing is assigned to it:
ref class DATReader
{
private:
System::String^ dataFileLocation;
// ...
}
Now I know the reason I'm getting the error is because dataFileLocation is assigned to nothing. But I'm having problems assigning it. When I add = 0; to it, it won't build because its a ref class. When I try to assigned it to = 0; in the constructor, it yells at me for trying to convert it from a System::String^ to an int. If I assign it to a = gcnew String(""); it builds, but throws the same runtime exception.
I don't get it, am I reading the debugger wrong, and this isn't the source of the problem at all? I've just started to use managed code recently, so I'm confused :\
You may want to check and make sure your DATReader object isn't null as well It may be throwing the exception at your DATReader.SetPath() call.
This is a nicety in C# that's missing in C++/CLI. C# generates code that ensures this can never be null. Easily seen in the debugger by setting a breakpoint on the method and inspecting "this". Here's an example program that reproduces the exception:
#include "stdafx.h"
using namespace System;
ref class Example {
String^ dataFileLocation;
public:
void SetPath(String^ path) {
dataFileLocation = path; // Set breakpoint here and inspect "this"
}
};
int main(array<System::String ^> ^args)
{
Example^ obj /* = gcnew Example */;
obj->SetPath("foo");
return 0;
}
Remove the /* */ comments to fix. Fix your code by looking at the call stack to find the method that forgot to instantiate the object.
Managed C++ uses nullptr for null references. So you can check:
if (path == nullptr) { ... }
or use:
if (!String::IsNullOrEmpty(path))

Exposing a managed COM local server - E_NOINTERFACE

Im trying to expose a local server that is written in C# to unmanaged code to allow interop! The managed code looks like that:
[Guid("A0D470AF-0618-40E9-8297-8C63BAF3F1C3")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMyLocalInterface
{
void LogToServer(string message);
}
[Guid("9E9E5403-7993-49ED-BAFA-FD9A63A837E3")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class MyLocalClass : IMyLocalInterface
{
public MyLocalClass()
{
Console.WriteLine("Object created!");
}
public void LogToServer(string message)
{
Console.WriteLine("Log > " + message);
}
}
class Program
{
[MTAThread]
static void Main(string[] args)
{
var srv = new RegistrationServices();
var cookie = srv.RegisterTypeForComClients(typeof(MyLocalClass), RegistrationClassContext.LocalServer | RegistrationClassContext.RemoteServer, RegistrationConnectionType.MultipleUse);
Console.ReadLine();
srv.UnregisterTypeForComClients(cookie);
}
}
And my unmanaged code does the following:
#import "ManagedLocServer.tlb" no_namespace raw_interfaces_only
int _tmain(int argc, _TCHAR* argv[])
{
CoInitializeEx(NULL, COINIT_MULTITHREADED);
{
IMyLocalInterfacePtr ptr;
ptr.CreateInstance(__uuidof(MyLocalClass));
ptr->LogToServer(L"Initializing...");
}
CoUninitialize();
return 0;
}
After debugging ive seen that CoCreateInstance works without any problems, that means "Object created" is printed into the managed servers console. But then QueryInterface on that object fails with E_NOINTERFACE. Im a bit confused why this happens. Is it a problem with registration (i only have a LocalServer32 entry for my CLSID)? Is it a problem within my managed code? Would be nice if someone could give me a hint :)
Greetings
Joe
You are using out-of-process COM. That requires marshaling support, to make a method call the arguments of the method need to be serialized. That's normally done by building the proxy/stub DLL from the code generated by midl.exe from the .idl file. Or by using the standard marshaller which works with the type library. Both require registry entries in HKCR\Interface
You get the E_NOINTERFACE because COM cannot find a marshaller. This is trivial to solve if you have an .idl file but you don't, the server is implemented in .NET. No idea how to solve this, I never tried to make this work. A remote possibility is that the CLR interop layer provides marshaling support. But you'd surely at least have to use ComInterfaceType.InterfaceIsDual. This is just a guess. If I tried to make this work, I'd start from an .idl first.