2010-07-12 56 views
0

我在C#中调用C++函数。C#结构到C++编组问题

这是C++函数头:

int src_simple (SRC_DATA *data, int converter_type, int channels) ; 

而这正是equivilent C#函数:

[DllImport("libsamplerate-0.dll")] 
    public static extern int src_simple(ref SRC_DATA sd, int converter_type, int channels); 

这是C++的SRC_DATA结构,然后在C#:

typedef struct 
    { float *data_in, *data_out ; 

     long input_frames, output_frames ; 
     long input_frames_used, output_frames_gen ; 

     int end_of_input ; 

     double src_ratio ; 
    } SRC_DATA ; 

这是我定义的C#结构:

[StructLayout(LayoutKind.Sequential, Pack = 1)] 
public struct SRC_DATA 
{ 

    public IntPtr data_in, data_out; 

    public long input_frames, output_frames; 
    public long input_frames_used, output_frames_gen; 

    public int end_of_input; 
    public double src_ratio; 

} 

最大的问题是最后一个参数src_ratio没有正确传递给C++函数(它将其视为0或无效)。

我的声明是否正确?

感谢

回答

4

你确定问题出在src_ratio成员中吗?长在C#中是64位。在Win32平台上的C++长32位,我认为你需要在C#中使用int作为长的C++结构成员。另外,Pack = 1看起来有点奇怪,你在C++中使用相同的结构成员对齐方式吗?

+0

你说得对,pack = 1是一个错误..我只是让它使用默认:) – Roey 2010-07-12 08:35:28

1

你强迫包装在C#中,但不是在C++。可能发生的情况是C++编译器使用四个附加字节填充7个in32,以确保double是8字节对齐的。

检查#pragma pack编译器指令。

0

检查C++编译器中int的大小。 C#int总是32位。