在C#中导入C dll,如何转换短**类型

时间:2014-08-05 08:43:08

标签: c# dll import pinvoke

我想在C#中导入一个用C语言编写的dll。以下是我想要调用的函数的格式。

/*
*ReadAnswer
*@param objectID         The answer object ID
*@param answerBuf        The answer buffer.This buffer is automatically allocated by 
                         the function. 
                         It is automatically recycled with each call. A call to this 
                         function with an empty answer or a new request will 
                         automatically free the allocated buffer.
*@param answerBufferSize The answer buffer size.This function return the size of the 
                         allocated buffer in this parameter.

*@return 0 if error occurs
        1 if success
*/

int ReadAnswer(unsigned short *objectID, 
               unsigned short **answerBuf, unsighed short *answerBufferSize )

请帮帮我。我被这个功能所困扰。提前谢谢。

3 个答案:

答案 0 :(得分:1)

C方面通常不足以确定,但在阅读评论后,它应该是这样的:

[DllImport("my.dll")]
private extern static int ReadAnswer(ref ushort objectID, out IntPtr answerBuf, out ushort answerBufferSize);

答案 1 :(得分:1)

该函数应该像这样声明:

[DllImport(dllname)]
private extern static int ReadAnswer(
    out ushort objectID,
    out IntPtr answerBuf,  
    out ushort answerBufferSize
);

这样称呼:

ushort objectID, answerBufSize;
IntPtr answerBufPtr;
int retval = ReadAnswer(out objectID, out answerBufPtr,
    out answerBufSize);
if (retval == 0)
    // handle error
ushort[] answerBuf = new ushort[answerBufSize/2];
Marshal.Copy(answerBufPtr, (Int16[])answerBuf, 0, answerBuf.Length);

我的假设是answerBufSize是以字节为单位的大小。

答案 2 :(得分:0)

首先,C#中没有 unsigned 关键字,请使用 ushort

其次,为了声明指针,你需要在类型之后写 * ,例如:ushort*

最后要导入用C语言编写的dll,请使用:

[System.Runtime.InteropServices.DllImport(requiredDll)]
extern static int ReadAnswer(ushort* objectID, ushort** answerBuf, out ushort* answerBufferSize);

此外,由于函数将缓冲区大小放在 answerBufferSize 中,因此该参数需要 out