0
我出現以下情況例外,當我運行GetBoard
方法(但Initialize
好的工作方法):C# - 方法的類型簽名不兼容PInvoke。隨着MarshalDirectiveException
System.Runtime.InteropServices.MarshalDirectiveException was unhandled
HResult=-2146233035
Message=Method's type signature is not PInvoke compatible.
Source=MatinChess.Net
StackTrace:
at MatinChess.Net.ExternMethods.GetBoard()
at MatinChess.Net.MatinChess.GetBoard() in C:\Users\Matin\Documents\GitHub\MatinChessDLL\dotnet\MatinChess.Net\MatinChess.cs:line 12
at MatinChess.Net.Demo.Program.PrintBoard(MatinChess chess) in C:\Users\Matin\Documents\GitHub\MatinChessDLL\dotnet\MatinChess.Net.Demo\Program.cs:line 53
at MatinChess.Net.Demo.Program.Main(String[] args) in C:\Users\Matin\Documents\GitHub\MatinChessDLL\dotnet\MatinChess.Net.Demo\Program.cs:line 14
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
我寫它是建立在x86設置下面的C#結構:
[DllImport("MatinChess.dll", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public extern static void Initialize();
[DllImport("MatinChess.dll", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public extern static ChessBoard GetBoard();
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct ChessBoard
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
byte[] board;
public char this[int x, int y]
{
get
{
return (char)board[y * 8 + x];
}
}
}
這裏是我的C++結構,它是由MSVC2015 32位編譯的:
struct ChessBoard
{
char board[8][8];
};
我猜它不喜歡的結構返回值。嘗試一個出來參數。在c#代碼中沒有char的地方,CharSet和SetLastError設置看起來是不必要的。 –
http://stackoverflow.com/questions/33806649/c-sharp-p-invoke-c-method-returning-a-byte - 這可能是你所需要的 – csharpfolk
雖然這是一個很好的答案,我不認爲它適用於此。 –