Reputation: 1708
Im creating an unmanaged DLL in Visual Studio 2010.
In order to test my DLL I have created another project with Visual Basic and i've attached it to the solution.
VB code calls to my InstallHook function in the DLL, passing a delegate of the callback function at VB. Then the DLL creates a hook and everytime a key is pressed the VB callback is called receiving the key and some other params as argument.
Well, the problem is that after some keys has been pressed, and the buffer in the VB callback reaches a specific size, the program crash. To be more specific, when the callback is called by the last time and it writes into its buffer in VB, it's like it overlaps in somewhere because the next time the callback is going to be called in the DLL, the program crash without reach the callback (the pointer in the dll is fine)
I dont understand well the architecture of .Net and i dont know exactly what could be wrong, but im very confident in the code i've done and the problem should be something technical with the memory management in .Net.
Edit: I forgot to say that if I call the callback from within the VB code, then it works fine. The callback is normally called from a WndProc installed in the same window.
Thanks....
Upvotes: 2
Views: 1007
Reputation: 564931
the pointer in the dll is fine
I suspect this is the problem. If you pass an address into a native routine, and then use it beyond the scope of the single method call, you run some risks.
The problem is that .NET uses a compacting garbage collector. This means that the runtime may "move" the buffer to a completely different location between method calls. As such, at some point, when you write to it, it could be in a completely different location.
You can work around this via allocating and managing the memory yourself via the Marshal class. Alternatively, you can use the GCHandle class to pin the memory and prevent it from being moved.
Upvotes: 3