DllImport C ++ DLL to C # application, BYTE * p

I have an exported function in a C ++ DLL.

// C++ DLL (Blarggg.dll)

extern "C"
{
     USHORT ReadProperty( BYTE * messsage, USHORT length, BYTE * invokeID ) 
    {
         if( invokeID != NULL ) {
            * invokeID = 10 ; 
        }
         return 0;
    }
}

      

What I would like to make available for my C # application

// C# app 
[DllImport("Blarggg.dll")]
public static extern System.UInt16 ReadProperty(
        /* [OUT] */ System.Byte[] message,
        /* [IN]  */ System.UInt16 length,
        /* [OUT] */ System.Byte[] invokeID ); 


private void DoIt() 
{
    System.Byte[] message = new System.Byte[2000];
    System.Byte[] InvokeID = new System.Byte[1];
    System.UInt16 ret = ReadProperty( message, 2000, InvokeID ); // Error 
}

      

The problem is I keep getting the following error message.

Blarggg.dll received an uncaught exception of type "System.NullReferenceException" Additional Information: An object reference is not set on an object instance.

I am using VS2008 to build DLL and C #.

I am not a C # programmer.

What am I doing wrong?

+2


source to share


4 answers


I pasted your code straight into VS2008 and it works fine on my 32 bit machine (added .def file to set the exported name). Is your C ++ library a pure win32 project? The error message you provided seems to imply that it raised a CLR exception.



+2


source


Try the following:



[DllImport("Blarggg.dll", CallingConvention := CallingConvention.Cdecl)] 
public static extern System.UInt16 ReadProperty( 
        /* [IN]  */ System.Byte[] message, 
        /* [IN]  */ System.UInt16 length, 
        /* [OUT] */ out System.Byte invokeID );  


private void DoIt()  
{ 
    System.Byte[] message = new System.Byte[2000]; 
    System.Byte InvokeID; 
    System.UInt16 ret = ReadProperty( message, 2000, out InvokeID );
} 

      

+2


source


You may need to use the System.Runtime.InteropServices.Marshal class to convert between managed and unmanaged types.

0


source


Can you do this with C ++ types?

I was under the impression that you can use the DLLImport C DLLs.

We use DLLImport with C ++ Dll just fine, but we declare our external functions as

extern "C" __declspec(dllexport) ...

      

Take a look at this web page:

http://dotnetperls.com/dllimport-interop

0


source







All Articles