【发布时间】:2014-09-21 14:20:20
【问题描述】:
我正在尝试在 C# 项目中使用 C DLL。
我在 C 中有一个函数:
extern __declspec(dllexport) void InitBoard(sPiece board[8][8]);
片段结构:
typedef struct Piece
{
ePieceType PieceType; //enum
ePlayer Player; //enum
int IsFirstMove;
} sPiece;
我在 C# 中有 PInvoke:
[DllImport("chess_api.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
static extern void InitBoard([MarshalAs(UnmanagedType.LPArray, SizeConst = 64)]ref sPiece[] board);
C# 上的 sPiece 结构:
[StructLayout(LayoutKind.Sequential)]
public struct sPiece
{
public ePieceType PieceType;
public ePlayer Player;
public int IsFirstMove;
}
当我运行 PInvoke 时,我收到以下错误:
对 PInvoke 函数“Chess!Chess.Main::InitBoard”的调用使堆栈不平衡。这可能是因为托管 PInvoke 签名与非托管目标签名不匹配。检查 PInvoke 签名的调用约定和参数是否与目标非托管签名匹配。
我尝试将调用约定更改为Cdecl,但是当我运行它时,VS 卡住了。
我该怎么办?
【问题讨论】:
-
@马克。我看到了这个答案,但没有帮助,因为我尝试像那里所说的那样更改 PInvoke,它卡住了我的 VS。
-
InitBoard 需要一个指针,但您给它一个指针指针,因为具有引用类型的 ref 是双重间接。这是您将发现的下一个错误。
标签: c# c struct pinvoke dllimport