Hodaya Shalom
Hodaya Shalom

Reputation: 4417

PInvoke does not change the object

I have the following PInvoke:(C to C#)

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

On C:

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

In InitBoard function, the values ​​of the matrix changing, but after a call to PInvoke I do not see the change.

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

I tried to change the variable to ref (although it already reference) but it stuck the program when the function was called, so I do not think it's the solution.

It took me a while to get here (I'm new to the subject) I'd love to help!

EDIT:

sPiece On C:

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

sPiece On C#:

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

Upvotes: 0

Views: 69

Answers (1)

David Heffernan
David Heffernan

Reputation: 613461

Possibly you are failing to allocate memory before calling the function.

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

Declare the function like this:

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

The default marshalling is [In]. Although since your struct is blittable, the array you pass is pinned and the call behaves as though it was [In,Out]. So I think you could omit [Out] if you wished, but it is clearer as written above.

You can add the UnmanagedType.LPArray option if you wish but it's not needed.

Upvotes: 2

Related Questions