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

问题描述 投票:2回答:1

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 []或string。我该如何在调用dll的c#中定义结构和方法? wave_date的长度是固定的,比方说就像100。

c# c++ dll struct
1个回答
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以确定真正的调用约定。

© www.soinside.com 2019 - 2024. All rights reserved.