2

我在 C++ DLL 中有一个导出函数

// C++ DLL (Blarggg.dll)

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

我想让它可用于我的 C# 应用程序

// 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 
}

问题是我不断收到以下错误消息。

Blarggg.dll 中发生了“System.NullReferenceException”类型的未经处理的异常附加信息:对象引用未设置为对象的实例。

我正在使用 VS2008 来构建 DLL 和 C# 应用程序。

我不是 C# 程序员。

我究竟做错了什么?

4

4 回答 4

2

我将您的代码直接粘贴到 VS2008 中,它在我的 32 位机器上完美运行(添加了一个 .def 文件来设置导出的名称)。你的 C++ 库绝对是纯 win32 项目吗?您提供的错误消息似乎暗示它引发了 CLR 异常。

于 2009-10-21T22:32:12.683 回答
2

试试这个:

[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 );
} 
于 2009-10-21T22:44:56.047 回答
0

您可能需要使用System.Runtime.InteropServices.Marshal 类在托管类型和非托管类型之间进行转换。

于 2009-10-21T21:54:38.323 回答
0

你能用 C++ 类型做到这一点吗?

我的印象是你只能 DLLImport C dll。

我们将 DLLImport 与 C++ Dll 一起使用很好,但我们将外部函数声明为

extern "C" __declspec(dllexport) ...

看看这个网页:

http://dotnetperls.com/dllimport-interop

于 2009-10-21T22:09:36.073 回答