将带有char *的struct传递给C#中的C ++ dll函数

时间:2017-11-14 09:29:32

标签: c# c++ dll struct dllimport

我在C#中使用C ++ dll并且在将char *传递给它时遇到了问题。

首先,该功能看起来如下:

[DllImport("xyz.dll")]
public static extern int ReadWrite_VCP(IntPtr handle, ref DATA_BUFFER readBuffer, ref DATA_BUFFER writeBuffer, int timeout);

结构定义为:

public struct DATA_BUFFER
{
    public string buffer;
    [MarshalAs(UnmanagedType.U4)]
    public int length;
    [MarshalAs(UnmanagedType.U4)]
    public int transferCount;
}

函数调用是:

ReadWrite_VCP(handle, ref rBuffer, ref wrBuffer, 5000);

一般来说,这样可以正常工作,但问题是,ReadWrite_VCP函数会写一个char数组(包括' \ 0'字符)。这导致了如果数据是' \ 0' ' 1' ' 2' ' 3' ,该字符串为空,因为它被' \ 0'

终止

我已经尝试过使用Stringbuilder或字节数组,但没有任何成功。

在C ++ Side上,该函数如下所示:

typedef struct 
{
    UCHAR *buffer;
    UINT32 length; 
    UINT32 transferCount; 
} DATA_BUFFER ;

功能:

unsigned int ReadWrite_VCP (HANDLE handle, DATA_BUFFER* ReadBuffer, DATA_BUFFER* writeBuffer, UINT32 timeout);

我希望有人能帮助我!

谢谢!

1 个答案:

答案 0 :(得分:0)

是的,你完全正确!

我的结构改为:

select * from (
  select a.acno, a.currbal, a.branchno,
    avg(a.currbal) over (partition by a.branchno) as abal
  from acmaster a
)
where currbal > abal;

      ACNO    CURRBAL   BRANCHNO       ABAL
---------- ---------- ---------- ----------
         2       2000          2       1500
         3       3000          3       2500

在我调用函数之前,分配一个Byte数组并设置指向它的指针

        public struct DATA_BUFFER
    {
        public IntPtr  buffer;
        [MarshalAs(UnmanagedType.U4)]
        public int length;
        [MarshalAs(UnmanagedType.U4)]
        public int transferCount;
    }

谢谢!