将struct *从c#传递给c ++ dll

时间:2017-12-21 08:55:54

标签: c# c++ dll struct

c ++ dll中的struct定义如下:

struct WAVE_INFO {
    int channel_num;
    int audio_type;
    char *wave_data;
    int wave_length;
};

这样的调用方法:

extern "C" STRUCTDLL_API int processStruct(WAVE_INFO *pIn, WAVE_INFO *pOut);

我的c#struct中的 wave_data 必须是字节数组(byte [])****,而不是char []或字符串。我该如何在调用dll的c#中定义结构和方法? wave_date的长度是固定的,比方说就像100。

1 个答案:

答案 0 :(得分:2)

首先,我会说C ++结构声明不正确。有效负载是二进制数据,因此数组应为unsigned char*而不是char*

除此之外,由于数组,结构对于编组来说有点繁琐。它是这样的:

[StructLayout(LayoutKind.Sequential)]
struct WAVE_INFO
{
    public int channel_num;
    public int audio_type;
    public IntPtr wave_data;
    public int wave_length;
}

我们无法在结构中使用byte[]进行编组。相反,我们必须将数组声明为IntPtr并自己处理编组。最干净的方法是声明byte[]数组并使用GCHandle将其固定。

导入的函数如下所示:

[DllImport(dllfilename, CallingConvention = CallingConvention.Cdecl)]
static extern int processStruct(ref WAVE_INFO infoIn, ref WAVE_INFO infoOut);

对函数的相当混乱的调用是这样的:

var dataIn = new byte[256];
// populate the input data array
var dataOut = new byte[256];

GCHandle dataInHandle = GCHandle.Alloc(dataIn, GCHandleType.Pinned);
try
{
    GCHandle dataOutHandle = GCHandle.Alloc(dataOut, GCHandleType.Pinned);
    try
    {
        WAVE_INFO infoIn;
        infoIn.audio_type = 1;
        infoIn.channel_num = 2;
        infoIn.wave_data = dataInHandle.AddrOfPinnedObject();
        infoIn.wave_length = dataIn.Length;

        WAVE_INFO infoOut = new WAVE_INFO();
        infoOut.wave_data = dataOutHandle.AddrOfPinnedObject();
        infoOut.wave_length = dataOut.Length;

        int retval = processStruct(ref infoIn, ref infoOut);
        // dataOut should have been populated by processStruct
    }
    finally
    {
        dataOutHandle.Free();
    }
}
finally
{
    dataInHandle.Free();
}

我的假设是第一个参数用于输入,第二个参数用于输出。但是调用者有责任为输出结构分配wave数据数组。

我还假设了一个调用约定,但您必须检查C ++宏STRUCTDLL_API以确定真正的调用约定。