2010-07-12 76 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位。