I am trying to make a chess interface using Unity. I have built a simple chess engine in c++ and decided to use its move generation function to verify moves in Unity. So I compiled it as a DLL and I'm using P/Invoke to call it.
What I'm trying to do is to get the moves (strings) inside the struct's array member.
The relevant code below worked in another project (on .Net 5.0), but it doesn't work within Unity. The error I'm getting is:
MarshalDirectiveException: Type string which is passed to unmanaged code must have a StructLayout attribute. DLLTEST.Start () (at Assets/Scripts/DLLTEST.cs:21)
And this confuses me, as it definitely DOES have a StructLayout attribute, doesn't it? What am I missing here?
using System;
using System.Runtime.InteropServices;
using UnityEngine;
public class DLLTEST : MonoBehaviour
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MOVES_IMPORT
{
int size;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 218)]
public string[] Array;
};
[DllImport("LittleChessEngine.dll")]
static extern int EXP_LEGAL_MOVES(ref MOVES_IMPORT mvs);
void Start()
{
var mvs = new MOVES_IMPORT();
var size = EXP_LEGAL_MOVES(ref mvs);
}
}
if relevant:
c++ struct:
struct MOVES_EXPORT {
int size = 0;
char* array[218];
};
function signature in c++:
extern "C" __declspec(dllexport) int EXP_LEGAL_MOVES(MOVES_EXPORT *moves_exp)
This specific solution I took from
https://gist.github.com/esskar/3779066
Also, please don't mind the fixed 218 array size or the naming inconsistencies, that's not what I'm here for!
Any ideas are appreciated!
Edit1: added extern "C" and changed the name of the function in C# so it matches that of the C++ function