Unmanaged DLL in C# Web Service

Posted by Telis on Stack Overflow See other posts from Stack Overflow or by Telis
Published on 2010-05-11T08:57:25Z Indexed on 2010/05/11 9:04 UTC
Read the original article Hit count: 543

Filed under:
|

Hi Guys, please help µe as I am new into accessing an unmanaged DLL from C#.. I have a large unmanaged DLL in C++ and I am trying to access the DLL's classes and functions from a C# Web Service.

I have seen many examples how to use DLLImport, but for some reason I am stuck with my very first wrapper method spending many hours with no luck.. What should I do to return an object in my 'Marshaled' [DllImport..] function? I would like to do something like that:

[DllImport("unmanaged.dll")]
public static extern MyClass MyFunction();

Here is the definition of my C++ class and the function that I want to access:

class __declspec(dllexport) TPDate
{
public:
      TPDate();
      TPDate(const TPDate& rhs);
      ...
      //today's date.
      static TPDate   AsOfDate(void);
      ...
}

In my Web service I have declared the following StructLayout:

[StructLayout(LayoutKind.Sequential)]
public class TPDate
{
    public TPDate(TPDate d)
    {
        _tpDate = d;
    }
    public TPDate _tpDate;
}

and here's where I think that I'm not doing something right:

class WrapperTPDate
{
    [DllImport("TPTools.dll", 
        ExactSpelling=false,
        EntryPoint = "?AsOfDate@TPDate@@SA?AV1@XZ", 
        CallingConvention = CallingConvention.StdCall)]
    [return: MarshalAs(UnmanagedType.Struct)]
    **public static extern TPDate AsOfDate();**// HERE THERE IS PROBLEM
};

I am calling the wrapper as follows from my WebMethod:

[WebMethod]
public void ConstructModel()
{
    TPDate date1 = WrapperTPDate.AsOfDate();// Here I get exception
    TPDate date = new TPDate(date1);
}

The exception i am getting is:

System.Web.Services.Protocols.SoapException: Server was unable to process request. --->
System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal 'return value': 
Invalid managed/unmanaged type combination (this type must be paired with LPStruct or 
Interface).

If I change it to LPSTRUCT, I am getting another exception:

System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> 
System.AccessViolationException: Attempted to read or write protected memory. This is often an 
indication that other memory is corrupt

Could you please tell me where I'm doing wrong here Thanks

© Stack Overflow or respective owner

Related posts about unmanaged

Related posts about dllimport