none
P/Invoke and 'access violation' in target DLL RRS feed

  • Question

  • Hi,

     

    I am using P/Invoke to call a function in a C++ DLL. When I call the function it returns the following error string:

     

    Access violation at address 0497013F in module 'cdapi.dll'. Read of address 000000FF.

     

    I do not have access to the C++ DLL, but I do have the following definition for the function I am attempting to call:

     

    Code Snippet

    CDResult CDAPI CD_OpenDataset(UINT uDatasetID, PCDOpenDatasetOptions lpdo, LPHANDLE lphDataset);

     

     

    I am calling this using P/Invoke as follows:

     

    Code Snippet

    [DllImport(@"C:\WINNT\system32\cdapi.dll")]

    public static extern UInt16 CD_OpenDataset(UInt32 uDatasetID, TCDOpenDatasetOptions lpdo, IntPtr lphDataSet);

     

     

    And, am calling this P/Invoke as:

     

    Code Snippet

    IntPtr ptr = Marshal.AllocCoTaskMem(1024);

    TCDOpenDatasetOptions tcdOpenDatasetOptions;

     

    resultCode = PInvoke.CD_OpenDataset(1, tcdOpenDatasetOptions, ptr);

     

     

     

    I have done a little looking into this, and believe that the error message 'access violation' above means that the C++ DLL is attempting to use memory that it doesn't own. I am not sure why this is the case. I do not have access to the C++, but can modify my C# calling application. I would be grateful for any suggestions.

     

    Many thanks!

    Martin

    Wednesday, May 14, 2008 9:01 AM

Answers

  • I have managed to quash this 'access violation' error by changing my P/Invoke code to:

     

    Code Snippet

    [DllImport(@"C:\WINNT\system32\cdapi.dll")]

    public static extern UInt16 CD_OpenDataset(UInt32 uDatasetID, ref TCDOpenDatasetOptions lpdo, ref IntPtr lphDataSet);

     

     

    It is just  a subtle change- am passing my IntPtr by ref.

     

    It was confusing enough getting my head around pointers and IntPtr in the first place, now seems very odd passing it by 'ref' too!

     

    Anyway, it seems to make the C++ DLL happy.

     

    Thanks,

    Martin

     

     

    Wednesday, May 14, 2008 10:35 AM