Immediate Access Violation when debugging Windows.Devices.Sensors project in Windows 7 - c++-cli

I have a large solution with 50+ unmanaged projects in it. I have recently added a project with managed code in it to the solution. The managed code accesses Windows.Devices.Sensors in a .NET dll. This dll is eventually wrapped by unmanaged code and called from another unmanaged project.
My problem is that I get the following access violation before main() even executes.
Unhandled exception at 0x744b8ea0 in myApplication.exe: 0xC0000005: Access violation.
Managed code:
#using <Windows.winmd>
using namespace Windows::Devices::Sensors;
#include <math.h>
namespace TabletSensors
{
namespace NET
{
public ref class DotNetDllClass
{
public:
DotNetDllClass()
{
Initialization();
}
~DotNetDllClass()
{
}
float* GetQuaternion()
{
OrientationSensorReading^ reading = _orientation->GetCurrentReading();
if( reading != nullptr )
{
float* quat = new float[4];
quat[0] = reading->Quaternion->X;
quat[1] = reading->Quaternion->Y;
quat[2] = reading->Quaternion->Z;
quat[3] = reading->Quaternion->W;
return quat;
}
else
{
return NULL;
}
}
private:
void Initialization()
{
_orientation = OrientationSensor::GetDefault();
if( _orientation != nullptr )
{
_orientation->ReportInterval = 16;
}
else
{
// not good ... throw exception or something
}
}
OrientationSensor^ _orientation;
};
}
}
Wrapper header file:
namespace TabletSensors
{
namespace NETWrapper
{
class DLLEXPORT_SENSORS WrapperClass
{
public:
__stdcall WrapperClass();
__stdcall ~WrapperClass();
float* __stdcall GetQuaternion();
};
}
}
Wrapper cpp file:
#define MIXSENSORS_BUILD
#include <gcroot.h>
#include "DotNetWrapper.h"
#include "DotNetDll.h"
using namespace TabletSensors::NETWrapper;
using namespace TabletSensors::NET;
static gcroot<TabletSensors::NET::DotNetDllClass^> Sensors = nullptr;
static System::UInt16 refCount = 0;
#pragma managed
inline TabletSensors::NET::DotNetDllClass^ GetSensors(void)
{
return (TabletSensors::NET::DotNetDllClass^)Sensors;
}
void Init()
{
++refCount;
if(GetSensors() == nullptr)
{
Sensors = gcnew TabletSensors::NET::DotNetDllClass();
}
}
void CleanUp()
{
if( refCount > 0 )
{
--refCount;
}
}
float* GetQuaternion_()
{
return Sensors->GetQuaternion();
}
#pragma unmanaged
TabletSensors::NETWrapper::WrapperClass::WrapperClass()
{
Init();
}
TabletSensors::NETWrapper::WrapperClass::~WrapperClass()
{
CleanUp();
}
float* TabletSensors::NETWrapper::WrapperClass::GetQuaternion()
{
float* x = new float[4];
return GetQuaternion_();
}
#pragma managed
Unmanaged project referencing my wrapper class:
#include "DotNetWrapper.h"
.
.
.
void UnmanagedProject::Update()
{
// if this line is present, I get an access violation without hitting any breakpoints.
TabletSensors::NETWrapper::WrapperClass _tabletSensors;
.
.
.
}
Since the managed code is trying to access Tablet Sensors I understand why it doesn't work on my Windows 7 desktop. What I don't understand it why it won't even allow me to debug my code at all. No breakpoints are hit before the Access Violation occurs.
What I would really like to figure out is how to use exception handling or #ifdefs to keep this crash from happening. But I have had very little luck.
Any ideas?

The fix is to Delay Load the managed DLL. The allows the application to run until that DLL is explicitly called. Thanks to Ben Voight for his answer here: https://stackoverflow.com/a/28467701/1454861

Related

C++/WinRT: MIDL 3.0 type: Char - compile of generated code returns 'T must be WinRT type'. Is there a support usage?

Using the idl source containing the MIDL 3.0 simple type Char:
namespace BrokenMIDL_Char
{
[default_interface]
runtimeclass MainPage : Windows.UI.Xaml.Controls.Page
{
MainPage();
Int32 MyProperty;
Char MyStationLetter_1;
//Char MyStationLetter_2;
//Char MyStationLetter_3;
}
}
And the supporting functions
wchar_t MyStationLetter_1()
{
throw hresult_not_implemented();
}
void MyStationLetter_1(wchar_t /*value*/)
{
throw hresult_not_implemented();
}
char16_t MyStationLetter_2()
{
throw hresult_not_implemented();
}
void MyStationLetter_2(char16_t /*value*/)
{
throw hresult_not_implemented();
}
char MyStationLetter_3()
{
throw hresult_not_implemented();
}
void MyStationLetter_3(char /*value*/)
{
throw hresult_not_implemented();
}
Results in an error
T must be a WinRT type
My understanding was that the MIDL 3.0 types are the definition the WinRT types.
The MIDL compiler emits:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
template<typename TDeclaringType, typename TValue>
void SetValueTypeMember_MyStationLetter_1(
::winrt::Windows::Foundation::IInspectable const& instance,
::winrt::Windows::Foundation::IInspectable const& value)
{
instance.as<TDeclaringType>().MyStationLetter_1(::winrt::unbox_value<TValue>(value));
}
During testing, I have a solution you could make a try.
You could open the Property tab > Properties > Configuration Properties > C/C++ > Language, find Treat Wchar_t As Built in Type property and select the No(/Zc:wchar_t-) option. Then, try to build your project.

Undefined Reference errors when using IL2CPP in Unity

after switching unity scripting to IL2CPP scripting my android build is gettting a lot of undefined reference errors. A lot of them reference to IOS ARKit related stuff. Can i use #if !UNITY_IOS statements to remove them from my android build ? and where can i put these #if statements ?
errors are realated to Bulk_Assembly-CSharp_8.cpp.. i tried putting #if statements in it for platform specific build but does not seem to make a difference
if !UNITY_IOS
public class ARFaceAnchor
{
private UnityARFaceAnchorData faceAnchorData;
private static Dictionary<string, float> blendshapesDictionary;
public ARFaceAnchor (UnityARFaceAnchorData ufad)
{
faceAnchorData = ufad;
if (blendshapesDictionary == null) {
blendshapesDictionary = new Dictionary<string, float> ();
}
}
public string identifierStr { get { return faceAnchorData.identifierStr; } }
public Matrix4x4 transform {
get {
Matrix4x4 matrix = new Matrix4x4 ();
matrix.SetColumn (0, faceAnchorData.transform.column0);
matrix.SetColumn (1, faceAnchorData.transform.column1);
matrix.SetColumn (2, faceAnchorData.transform.column2);
matrix.SetColumn (3, faceAnchorData.transform.column3);
return matrix;
}
}
public ARFaceGeometry faceGeometry { get { return new ARFaceGeometry (faceAnchorData.faceGeometry); } }
public Dictionary<string, float> blendShapes { get { return GetBlendShapesFromNative(faceAnchorData.blendShapes); } }
delegate void DictionaryVisitorHandler(IntPtr keyPtr, float value);
[DllImport("__Internal")]
private static extern void GetBlendShapesInfo(IntPtr ptrDic, DictionaryVisitorHandler handler);
Dictionary<string, float> GetBlendShapesFromNative(IntPtr blendShapesPtr)
{
blendshapesDictionary.Clear ();
GetBlendShapesInfo (blendShapesPtr, AddElementToManagedDictionary);
return blendshapesDictionary;
}
[MonoPInvokeCallback(typeof(DictionaryVisitorHandler))]
static void AddElementToManagedDictionary(IntPtr keyPtr, float value)
{
string key = Marshal.PtrToStringAuto(keyPtr);
blendshapesDictionary.Add(key, value);
}
}
endif
If you want to remove from Android build, use
#if !UNITY_ANDROID
// your code here
#endif
Will be more helpful if you can post your error message is pertaining to which line.
Thanks Darren,
i must have got it all wrong. so
if !UNITY_ANDROID means if NOT Android ?

Call c++ code in c# by a cli wrapper

I have a c++ code that needs to be called in c# by a cli wrapper. I am stuck at the operator overloading part.
//this is my code
//Cppclass.h
#ifdef CPP_EXP_EXPORTS
#define CPP_EXP __declspec(dllexport)
#else
#define CPP_EXP __declspec(dllimport)
#endif
class CPP_EXP Cppclass;
CPP_EXP Cppclass operator-(Cppclass const &, Cppclass const &);
class CPP_EXP Cppclass
{
public:
friend CPP_EXP Cppclass operator-(Cppclass const &, Cppclass const &);
};
//this is my managed c++ code.
#include "Cppclass.h"
namespace Wrapper
{
public ref class cppwrapclass
{
public:
static cppwrapclass ^ operator-(cppwrapclass%A,cppwrapclass%B)
{
operator-(A.obj,B.obj);
return gcnew cppwrapclass();
}
private:
Cppclass *obj;
};
}
Its showing an intellisense error and not getting compiled.
You write a wrapper like this:
public ref class cppwrapclass
{
public:
cppwrapclass(Cppclass *obj)
: obj(obj)
{
}
~cppwrapclass()
{
this->!cppwrapclass();
}
!cppwrapclass()
{
if (obj)
{
delete obj;
obj = nullptr;
}
}
static cppwrapclass^ operator-(cppwrapclass% A, cppwrapclass% B)
{
return gcnew cppwrapclass(new Cppclass(*A.obj - *B.obj));
}
private:
Cppclass* obj;
};
A.obj is of type Cppclass*, therefore *A.obj is of type Cppclass, and *A.obj - *B.obj is a temporary Cppclass which needs to be moved to the heap in order to be referenced by the wrapper, hence the copy constructor call: new Cppclass(*A.obj - *B.obj).
The rest is the Dispose pattern and finalizer plumbing code.

MFC DLL: class object value is not persisting throughout the exported call

I have written MFC dll having 3 methods are exported. I have declared class object as global and initialized it in first method then second and third method use and process it.
Issue is that class obeject's value is not getting persisting throughout the file. when second or third method gets call from C# client application, class
object value is getting NULL.
Could anybody tell me why this is happening! I have tried this same scnaerio in another application but this issue is not reproduced.
Code:
Interface File:
#include "StdAfx.h"
#define DLLEXPORT __declspec(dllexport)
using namespace nsAnalyzer;
static CWindowsAnalyzer *pWindowsAnalyzer = NULL;
extern "C" DLLEXPORT void Init( const wchar_t *sCurrentUserDataDir,
const wchar_t *sMachineName,
const wchar_t *sMacId )
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
try
{
nsAnalyzer::CWindowsAnalyzer *pWindowsAnalyzer = new CWindowsAnalyzer( CString(sCurrentUserDataDir),
CString(sMachineName),
CString(sMacId) );
if(pWindowsAnalyzer)
{
pWindowsAnalyzer->Init();
}
}
catch(const std::exception& e)
{
cout<<"Error: Exception occured in Init: "<<e.what()<<endl;
}
}
extern "C" DLLEXPORT bool Analyze()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
bool bResult = false;
try
{
if(pWindowsAnalyzer->ConsolidateRawActivities())
{
cout<<"ConsolidateRawActivities succeed"<<endl;
bResult = true;
}
else
{
cout<<"ConsolidateRawActivities failed"<<endl;
bResult = false;
}
}
catch(const std::exception& e)
{
cout<<"Error: Exception occured in Analyze: "<<e.what()<<endl;
}
return bResult;
}
extern "C" DLLEXPORT void Dispose()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
try
{
// Disponse windows analyzer
if(pWindowsAnalyzer)
{
delete pWindowsAnalyzer;
}
// Dispose Logger
CLogger::DisposeInstance();
}
catch(const std::exception& e)
{
cout<<"Error: Exception occured in Dispose: "<<e.what()<<endl;
}
}

SFML Input system problem

So I was porting my game engine from SDL to SFML, and now I have a problem with my input system.
Input.h
#ifndef BULLWHIP_INPUT_H
#define BULLWHIP_INPUT_H
#include
class bc_Input
{
public:
bool bm_KeyHit(sf::Key::Code key);
bool bm_KeyDown(sf::Key::Code key);
int bm_MouseX();
int bm_MouseY();
void bm_init(sf::RenderWindow app);
private:
sf::RenderWindow App;
const sf::Input& input;
};
#endif
Input.cpp
#include "Input.h"
bool bc_Input::bm_KeyDown(sf::Key::Code key)
{
return in.IsKeyDown(key)
}
bool bc_Input::bm_KeyHit(sf::Key::Code key)
{
sf::Event event;
while(App.GetEvent(event) && event.Type == sf::Event::KeyPressed)
{
switch(event.Key.Code)
{
case key: return true; break;
default:
break;
}
}
}
void bc_Input::bm_init(sf::RenderWindow app)
{
App = app;
in = App.GetInput();
}
int bc_Input::bm_MouseX()
{
return in.GetMouseX();
}
int bc_Input::bm_MouseY()
{
return in.GetMouseY();
}
I get these errors from this:
C:\c++\sdl\bullwhip\lib\Bullwhip\/Input.h:15: error: 'bc_Input::App' cannot appear in a constant-expression
C:\c++\sdl\bullwhip\lib\Bullwhip\/Input.h:15: error: '.' cannot appear in a constant-expression
C:\c++\sdl\bullwhip\lib\Bullwhip\/Input.h:15: error: a function call cannot appear in a constant-expression
C:\c++\sdl\bullwhip\lib\Bullwhip\/Input.h:15: error: ISO C++ forbids initialization of member 'input'
C:\c++\sdl\bullwhip\lib\Bullwhip\/Input.h:15: error: making 'input' static
C:\c++\sdl\bullwhip\lib\Bullwhip\/Input.h:15: error: invalid in-class initialization of static data member of non-integral type 'sf::Input&'
c:\program files (x86)\codeblocks\mingw\bin../lib/gcc/mingw32/4.4.0/../../../../include/SFML/System/NonCopyable.hpp:57: error: 'sf::NonCopyable::NonCopyable(const sf::NonCopyable&)' is private
c:\program files (x86)\codeblocks\mingw\bin../lib/gcc/mingw32/4.4.0/../../../../include/SFML/Window/Window.hpp:56: error: within this context
You're calling the copy constructor here:
void bc_Input::bm_init(sf::RenderWindow app)
{
App = app;
in = App.GetInput();
}
Note one of your error messages:
error: 'sf::NonCopyable::NonCopyable(const sf::NonCopyable&)
In order to avoid this problem, you should use an actual constructor for your sf::Input object along with an initialization list.
Alternatively, if you've already initialized a sf::RenderWindow in a higher subsystem (as is likely the case), simply changing your member variable App to a reference should do the trick.
//header
sf::RenderWindow& App;
...
//source
void bc_Input::bm_init(sf::RenderWindow& app)
{
App = app;
in = App.GetInput();
}