我有一個本機的結構:如何從C調用C#傳遞數組作爲成員的結構數組?
typedef struct
{
char Message[STR_MAX];
char Params[10][STR_MAX];
int GetParamStr[10];
int ParamCount;
} FormattedMessage_t;
和回調類型:
typedef void(*FormatMsgCB_t)(FormattedMessage_t *FormatMsgs, int FormatMsgCount);
靜態數組:
static FormattedMessage_t gFormattedMessages[10];
回調函數集:
extern "C" __declspec(dllexport) void DllGuiSetFormatMsgCB(FormatMsgCB_t pCB)
{
gFormatMsgCB = pCB;
}
呼叫從原產地到管理:
void DllGuiSetFormatMessage()
{
gFormatMsgCB(gFormattedMessages, gFormattedMsgIndex);
}
在託管:
[StructLayout(LayoutKind.Sequential)]
public struct FormattedMessage_t
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MaxStrLength)]
public string Message;
public string[] ParamStrings;
public int[] GetParamStrs;
public int ParamCount;
public const int MaxStrLength = StrMax;
}
public static T[] GetArray<T>(IntPtr aTblPtr, int nRows)
{
var entrySize = Marshal.SizeOf(typeof(T));
IntPtr oneRowPtr = new IntPtr(aTblPtr.ToInt64());
T[] array = new T[nRows];
for (int i = 0; i < nRows; i++)
{
array[i] = (T)Marshal.PtrToStructure(oneRowPtr, typeof(T));
oneRowPtr = new IntPtr(oneRowPtr.ToInt64() + entrySize);
}
return array;
}
private void OnSetFormatMsg(IntPtr formatMsg, int nFormatMsg)
{
var array = GetArray<FormattedMessage_t>(formatMsg, nFormatMsg);
foreach (var msg in array)
{
var str = msg.Message;
// and so on
}
}
此工作的getArray對於簡單的類型,結構成員。這超出了我的P/Invoke和Native Interop技能。
這在很多方面可能都是錯誤的。任何提示如何做到這一點(改變這兩個結構是沒有問題的)將不勝感激。
我不記得我頭腦中的細節,但是iirc可以創建一個自定義編組器或將'MarshalAs'標誌添加到'ParamStrings'等。(這些似乎缺失。) – atlaste