tags:

views:

1240

answers:

2

Hi all, I'm encountering a strange memory read/write error while calling a compiled DLL from C#. I use DllImport to get a handle to the function we need, which writes a return value to a parametric pointer to an int (i.e., int* out). This function is called multiple times within a thread, and runs successfully over the execution life of the first thread. However, if one launches another thread after the first has completed, the call to the external dll throws an AccessViolationException. Since the multiple calls from the first thread execute successfully, I'm thinking this is somehow related to the first thread not releasing the pointers to the relevant integer parameters(?). If so, how can I explicitly release that memory? Or, perhaps someone has a different insight into what might be going on here? Thank you very much.

EDIT: Danny has requested more specifics, and I'm happy to oblige. Here is where the external routine is invoked:

    int success = -1;
    unsafe
    {
        int res = 0;
        int* res_ptr = &res;
        int len = cmd.ToCharArray().Length;
        int* len_ptr = &len;
        CmdInterpreter(ref cmd, len_ptr, res_ptr);
        success = *res_ptr;
    }

Where CmdInterpreter is defined as:

    [DllImport("brugs.dll", EntryPoint="CmdInterpreter", 
        ExactSpelling=false, CallingConvention = CallingConvention.StdCall)]
    public static unsafe extern void CmdInterpreter(ref string cmd, int *len, int *res);

Please let me know if there is any additional info that would be helpful. Thank you!

A: 

It may be the [DllImport]. If you post the [DllImport] signature, and the DLL's ptototype, maybe we can spot a problem.

I read that the Managed, Native, and COM Interop Team released the PInvoke Interop Assistant on CodePlex. http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120

GregUzelac
Thank you greguzelac, I have posted the import signature. If it were a problem with the signature, however, wouldn't it fail on the first invocation? Again, it runs perfectly throughout the whole first thread, it's only when a second thread invokes the method that it fails. Thanks again.
+1  A: 

Given that the problem only occurs when multiple threads are involved, it may be that the command interpreter DLL is using some sort of thread-local storage and doing it incorrectly. It could also have to do with the COM initialization state of the second thread (the one that generates the error).

It would be interesting to know what happens if you launch your new thread and have it call into the DLL before making any calls into the DLL on your first/main thread. If it works, that might support the thread-local storage theory. If it fails, that would support the COM state theory.

Charlie