System.AccessViolationException: 'Attempted to read or write protected memory. (Making a wrapper for a c++ lib) - c++-cli

My constructor is as next
ScaperEngine::ScaperEngine(GrabberType grabberType, bool timing) {
switch (grabberType)
{
case GrabberType::DepthSenseGrabber:
this->interface = new pcl::DepthSenseGrabber("");
break;
default:
throw new std::exception("Grabber type wasn't chosen correctly");
break;
}
executionPipeline = new ExecutionPipeline();
executionPipeline->setTiming(timing);
}
And then I have some code like:
void ScaperEngine::StartPipeline()
{
IPCLNormalCalculator* normalCalculator = new PCLNormalCalculator(normalCalcMaxDepthChangeFactor, normalSmoothingSize);
executionPipeline->SetPCLNormalCalculator(normalCalculator);
The most strange thing is that the constructor is building executionPipeline in the right way putting its place in memory in 0x0000020ef385e830, but when my c# managed code calls StartPipeline the executionPipeline address changed to 0xcdcdcdcdcdcdcdcd and in Quick Watch the following text appears for its variables <Unable to read memory>.
Please anyone has a clue whats going on?
With many thanks.

The 0xcdcdcdcdcdcdcdcd you are seeing is a special feature of the Visual Studio debugger that represents uninitialized heap memory. A more comprehensive list of codes are available from this StackOverflow question. In brief, it seems as though your C# code is calling StartPipeline() on an invalid object. This could happen, for example, if the pointer is altered to point to a random location in heap memory. Make your C# code (and the runtime) is properly storing the pointer to the ScraperEngine object and not corrupting it along the way.

Related

Is Kotlin synchronized() not locking basic types?

class Notification(val context: Context, title: String, message: String) {
private val channelID = "TestMessages"
companion object ID {
var s_notificationID = -1
}
init {
var notificationID = -1
synchronized(s_notificationID) {
if (++s_notificationID == 0)
createNotificationChannel()
notificationID = s_notificationID
}
The above is being called simultaneously from two threads. A breakpoint in createNotificationChannel() clearly showed that sometimes s_notificationID equals 1.
However, if I change
synchronized(s_notificationID)
to synchronized(ID)
then it seems to lock fine.
Is synchronized() not locking basic types? And if so, why does it compile?
A look at the generated JVM bytecode indicates that the ID example looks like
synchronized(ID) { ... }
which is what you'd expect. However, the s_notificationID example looks more like
synchronized(Integer.valueOf(s_notificationID)) { ... }
In Java, we can only synchronize on objects, not on primitives. Kotlin mostly removes this distinction, but it looks like you've found one place where the implementation still seeps through. Since s_notificationID is an int as far as the JVM is concerned (hence, not an object) but synchronized expects an object, Kotlin is "smart" enough to wrap the value in Integer.valueOf on demand. Unfortunately for you, that produces wildly inconsistent results, because
This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
So for small numbers, this is guaranteed to lock on some cached object in memory that you don't control. For large ones, it may be a fresh object (hence always unlocked) or it might again end up on a cached object out of your hands.
The lesson here, it seems, is: Don't synchronize on primitive types.
Silvio Mayolo explained why it is not a good idea to synchronize on primitives (actually, I think the compiler should warn about this). But I believe there is another problem with this code, probably the main one that makes your synchronized blocks work in parallel.
The problem is that you replace the value of s_notificationID. Even if it would be an object, not a primitive, your synchronized blocks would still run in parallel, because each call to synchronized uses a different object. This is why in Java we usually synchronize on this and not on a field that we need to modify.
TL;DR The lesson here, it seems, is: Don't synchronize on primitive types.
synchronized(i) where i is Int, is actually synchronized(Integer.valueOf(i)).
Only in the range -128 to 127 this value is guaranteed to be a cached value.
Another fact is that ++i cannot be looked at as a mutation of the "object" i, but rather as replacing i by a new "object" with the value i+1.
Thank you broot & Silvio Mayolo for the above.
Experiments I did prove the above.
In my original code I have removed the ++ from
++s_notificationID. Amazingly or not, the lock worked now.
Now with that change I changed var s_notificationID = -1 to be var s_notificationID = -1000. Even more amazing, now the lock again stopped working.
Still, I think this anomaly of basic types undermines the attempt of Kotlin to see basic types as objects, and I think this should have been mentioned clearly in Kotlin documentation.

How to use for loop instead of foreach loop in traversing GetProcessByName

I had been searching through the internet for getting all the processes of an application. And so far all the implementation of traversing it is by using foreach loop which I'm not familiar with. It works but I just can't rest easy for it working without me getting to understand it. So I'd like to ask if someone can show me how to implement such code using for loop.
System::Diagnostics::Process^ current = System::Diagnostics::Process::GetCurrentProcess();
for each (System::Diagnostics::Process^ process in System::Diagnostics::Process::GetProcessesByName(current->ProcessName))
if (process->Id != current->Id)
{
// process already exist
}
I'm using visual studio c++/clr btw, hence :: since it's not in c#.
GetProcessesByName returns a cli::array, so iterate using that and its length property.
cli::array<Process^>^ processes = Process::GetProcessesByName(current->ProcessName);
for (int i = 0; i < processes->Length; i++)
{
if (processes[i]->Id != current->Id)
{
// process already exist
}
}
That said, there might be a better way to do this.
It looks like you're trying to see if there's another copy of your application running, so that you can display an "App is already running, switch to that one instead" message to the user.
The problem is that the process name here is just the filename of your EXE, without the path or the "EXE" extension. Try renaming your application to "Notepad.exe", and run a couple copies of the Windows Notepad, and you'll see that they both show up in the GetProcessesByName result.
A better way to do this is to create a named Mutex, and check for its existence and/or lock status at startup.
Here's an answer that does just that. Prevent multiple instances of a given app in .NET? It is written in C#, but it can be translated to C++/CLI. The only notable thing about the translation is that it's using a C# using statement; in C++/CLI that would be the line Mutex mutex(false, "whatever string");, using C++/CLI's stack semantics.

Casting System::IO::FileStream^ to FILE*

I am working on refactoring a large amount of code from an unmanaged C++ assembly into a C# assembly. There is currently a mixed-mode assembly going between the two with, of course, a mix of managed and unmanaged code. There is a function I am trying to call in the unmanaged C++ which relies on FILE*s (as defined in stdio.h). This function ties into a much larger process which cannot be refactored into the C# code yet, but which now needs to be called from the managed code.
I have searched but cannot find a definitive answer to what kind of underlying system pointer the System::IO::FileStream class uses. Is this just applied on top of a FILE*? Or is there some other way to convert a FileStream^ to a FILE*? I found FileStream::SafeFileHandle, on which I can call DangerousGetHandle().ToPointer() to get a native void*, but I'm just trying to be certain that if I cast this to FILE* that I'm doing the right thing...?
void Write(FILE *out)
{
Data->Write(out); // huge bulk of code, writing the data
}
virtual void __clrcall Write(System::IO::FileStream ^out)
{
// is this right??
FILE *pout = (FILE*)out->SafeFileHandle->DangerousGetHandle().ToPointer();
Write(pout);
}
You'll need _open_osfhandle followed by _fdopen.
Casting is not magic. Just because the input and types output are right for your situation doesn't mean the values are.

Confused by MSDN "recommended way of handling errors" in COM

I have been reading the MSDN dev guide to COM. However the code on this page is confusing. Reproducing here:
The following code sample shows the recommended way of handling unknown errors:
HRESULT hr;
hr = xxMethod();
switch (GetScode(hr))
{
case NOERROR:
// Method returned success.
break;
case x1:
// Handle error x1 here.
break;
case x2:
// Handle error x2 here.
break;
case E_UNEXPECTED:
default:
// Handle unexpected errors here.
break;
}
The GetScode function doesn't seem to be defined, nor is NOERROR, and searching MSDN didn't help. A web search indicated that GetScode is a macro that converts HRESULT to SCODE, however those are both 32-bit ints so I'm not sure what it is for.
It was suggested that it is a historical artifact that does nothing on 32-bit systems, but on 16-bit systems it converts hr to a 16-bit int. However, if that is true, then I do not see how E_UNEXPECTED would be matched, since that is 0x8000FFFF. Also, it's unclear whether x1 and x2 are meant to be 0x800..... values, or some sort of truncated version.
Finally, this code treats all-but-one of the success values as errors. Other pages on the same MSDN guide say that SUCCEEDED(hr) or FAILED(hr) should be used to determine between a success or failure.
So, is this code sample really the "recommended way" or is this some sort of documentation blunder?
This is (pretty) old stuff. The winerror.h file in the SDK says this:
////////////////////////////////////
// //
// COM Error Codes //
// //
////////////////////////////////////
//
// The return value of COM functions and methods is an HRESULT.
// This is not a handle to anything, but is merely a 32-bit value
// with several fields encoded in the value. The parts of an
// HRESULT are shown below.
//
// Many of the macros and functions below were orginally defined to
// operate on SCODEs. SCODEs are no longer used. The macros are
// still present for compatibility and easy porting of Win16 code.
// Newly written code should use the HRESULT macros and functions.
//
I think it's pretty clear. I would trust the SDK first, and the doc after that.
We can see SCODE is consistently defined like this in WTypesbase.h (in recent SDKs, in older SDKs, I think it was in another file):
typedef LONG SCODE;
So it's really a 32-bit.
The text is correct; one should be wary of blindly returning failure codes from internal functions, particularly if your code uses a facility code defined elsewhere in the system.
Specifically, at the COM interface function level, you should ensure that the error codes you're returning are meaningful for your interface, and you should remap errors that originate from inside the function to meaningful error codes.
Practically speaking, however, nobody does this, which is why you see bizarre and un-actionable error dialogs like "Unexpected error".

Will code written in this style be optimized out by RVO in C++11?

I grew up in the days when passing around structures was bad mojo because they are often large, so pointers were always the way to go. Now that C++11 has quite good RVO (right value optimization), I'm wondering if code like the following will be efficient.
As you can see, my class has a bunch of vector structures (not pointers to them). The constructor accepts value structures and stores them away.
My -hope- is that the compiler will use move semantics so that there really is no copying of data going on; the constructor will (when possible) just assume ownership of the values passed in.
Does anyone know if this is true, and happens automagically, or do I need a move constructor with the && syntax and so on?
// ParticleVertex
//
// Class that represents the particle vertices
class ParticleVertex : public Vertex
{
public:
D3DXVECTOR4 _vertexPosition;
D3DXVECTOR2 _vertexTextureCoordinate;
D3DXVECTOR3 _vertexDirection;
D3DXVECTOR3 _vertexColorMultipler;
ParticleVertex(D3DXVECTOR4 vertexPosition,
D3DXVECTOR2 vertexTextureCoordinate,
D3DXVECTOR3 vertexDirection,
D3DXVECTOR3 vertexColorMultipler)
{
_vertexPosition = vertexPosition;
_vertexTextureCoordinate = vertexTextureCoordinate;
_vertexDirection = vertexDirection;
_vertexColorMultipler = vertexColorMultipler;
}
virtual const D3DVERTEXELEMENT9 * GetVertexDeclaration() const
{
return particleVertexDeclarations;
}
};
Yes, indeed you should trust the compiler to optimally "move" the structures:
Want Speed? Pass By Value
Guideline: Don’t copy your function arguments. Instead, pass them by value and let the compiler do the copying
In this case, you'd move the arguments into the constructor call:
ParticleVertex myPV(std::move(pos),
std::move(textureCoordinate),
std::move(direction),
std::move(colorMultipler));
In many contexts, the std::move will be implicit, e.g.
D3DXVECTOR4 getFooPosition() {
D3DXVECTOR4 result;
// bla
return result; // NRVO, std::move only required with MSVC
}
ParticleVertex myPV(getFooPosition(), // implicit rvalue-reference moved
RVO means Return Value Optimization not Right value optimization.
RVO is a optimization performed by the compiler when the return of a function is by value, and its clear that the code returns a temporary object created in the body, so the copy can be avoided. The function returns the created object directly.
What C++11 introduces is Move Semantics. Move semantics allows us to "move" the resource from a certain temporary to a target object.
But, move implies that the object wich the resource comes from, is in a unusable state after the move. This is not the case (I think) you want in your class, because the vertex data is used by the class, even if the user calls to this function or not.
So, use the common return by const reference to avoid copies.
On the other hand,, DirectX provides handles to the resources (Pointers), not the real resource. Pointers are basic types,its copying is cheap, so don't worry about performance. In your case, you are using 2d/3d vectors. Its copying is cheap too.
Personally, I think that returning a pointer to an internal resource is a very bad idea, always. I think that in this case the best aproach is to return by const reference.