2014-09-21 53 views
0

我有以下的PInvoke :(CC#的PInvoke不改變對象

[DllImport("chess_api.dll", CallingConvention = CallingConvention.Cdecl)] 
static extern void InitBoard([MarshalAs(UnmanagedType.LPArray, SizeConst = 64)]sPiece[] board); 

C

__declspec(dllexport) void InitBoard(sPiece board[8][8]); 

在InitBoard功能,基質變化的值,但在打電話給PInvoke後我不要看到變化。

sPiece[] board = new sPiece[64]; 
InitBoard(board); 
//Here the values ​​of the board is still initialized (as before the function call) at default values 

我試圖將變量更改爲ref(雖然它已經引用),但它卡住程序的函數被調用時,所以我不認爲這是解決方案。

我花了一段時間纔到這裏(我對這個主題感興趣)我很樂意幫助!

編輯:

sPiece在C:

typedef struct Piece 
{ 
    ePieceType PieceType; //enum 
    ePlayer Player; //enum 
    int IsFirstMove; 
} sPiece; 

sPiece在C#:

[StructLayout(LayoutKind.Sequential)] 
public struct sPiece 
{ 
    public ePieceType PieceType; 
    public ePlayer Player; 
    public int IsFirstMove; 
} 
+0

'sPiece'是什麼? (在C&C#中) – SLaks 2014-09-21 04:38:51

+0

@SLaks。我在這個問題上加了這個。 OMG !! – 2014-09-21 04:42:11

回答

2

也許你是失敗調用函數之前分配內存。

sPiece[] board = new sPiece[64]; 
InitBoard(board); 

聲明函數是這樣的:

[DllImport("chess_api.dll", CallingConvention = CallingConvention.Cdecl)] 
static extern void InitBoard([Out] sPiece[] board); 

默認編組爲[In]。雖然由於你的結構體是blittable,你傳遞的數組是固定的,並且調用的行爲就像是[In,Out]一樣。所以我認爲如果你願意,你可以省略[Out],但是如上所述它更清楚。

如果您願意,您可以添加UnmanagedType.LPArray選項,但不需要。

+0

OMG !! 它終於奏效!非常感謝你! – 2014-09-21 06:25:12

+0

打敗了我一拳...以及有關此類功能的更多信息,MSDN有一個很好的寫法[這裏](http://msdn.microsoft.com/en-us/library/hk9wyw21(v = vs。 110)的.aspx) – ryrich 2014-09-21 06:25:34