Saturday, 14 September 2013

Threading in C# - Using ref Parameter to PInvoke C Function

Threading in C# - Using ref Parameter to PInvoke C Function

I have coded a C# application, which PInvokes a function in a third party
C-language DLL. When I run the code in a single thread, it completes
successfully. When I run the same code through a BackgroundWorker DoWork,
I get the exception Attempted to read or write protected memory. This is
often an indication that other memory is corrupt.
The DLL is nnotes.dll, which is used in Lotus Notes 8.5.3. The application
is 32-bit and run on a 64-bit machine. Windows 7. Visual Studio 2008.
My Code
using DHANDLE = System.UInt64;
...
DHANDLE m_hDb = 0;
...
ushort stat = NotesEntries.NSFDbOpen(NotesConnectionDatabase.FilePath, ref
this.m_hDb);
My DllImport
[DllImport("nnotes.dll")]
public static extern STATUS NSFDbOpen(string path, ref DHANDLE hDb);
The signature according to the documentation
STATUS LNPUBLIC NSFDbOpen(
char far *PathName,
DBHANDLE far *rethDB);
From what I have read, using the ref keyword may be part of the problem.
However, I believe it is necessary because the NSFDbOpen function modifies
the value in hDb with the handle to the Notes database.
Perhaps I am not properly allocating memory for that variable. Perhaps,
when the PIvoked function attempts to modify the value, it attempts to
write to memory that it does not have access to. What can I do about this?
Also, I have a try, catch block around the problem line. If I run the code
in Debug, I get the exception. If I then try the same line again using
"Set Next Statement", the line works correctly, and the ref parameter
contains the handle.
How can I modify the code to work in a multi-threaded environment?

No comments:

Post a Comment