[英]How to fix 'Method's type is not PInvoke Compatible'
嘗試返回具有 C++ 中精確布局的結構時,問題是當TCHAR rMsg[256]
包含在 C++ 結構和[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public char rMsg;
包含在 C# 結構中(兩者都將在下面顯示)我收到錯誤“方法的類型與 PInvoke 不兼容”。
我還應該指出 C++ 不是我的,我無法更改它,因為其他功能需要下面給出的結構布局。
我知道問題是 TCHAR,因為當我注釋掉 C++ 和 C# 中的相關行時,我沒有收到錯誤消息。
我正在調用我創建的.dll(我還將在下面的代碼中包含它)只是為了返回一個結構,以便我知道我有正確的語法。
C++:
extern "C" {
__declspec(dllexport) tVDACQ_CallBackRecVal ( _stdcall TestAcq2())
{
//Just adding random values so I know it works.
tVDACQ_CallBackRecVal AR;
AR.rFlags = 1;
AR.rFrameHeight = 10;
AR.rFrameWidth = 10;
return AR;
}
}
//Struct
typedef struct {
int rFlags,
rType,
rEvent,
rSocket;
TCHAR rMsg[256]; //Has to stay as TCHAR
int rFrameWidth,
rFrameHeight;
short* rFrameBuffer;
union {
int rCaptureRows;
int rCaptureFrames;
};
int rCapturePercent;
void* rUserCallBackProc,
* rUserParam;
int rAborted;
void* rPacketData;
int rFGControl;
} tVDACQ_CallBackRecVal;
C#:
//Simply calling the .dll
[DllImport("C:\\Users\\jch\\source\\repos\\FlatPanelSensor\\x64\\Debug\\VADAV_AcqS.dll", EntryPoint = "TestAcq2", CallingConvention = CallingConvention.Cdecl)]
public unsafe static extern tVDACQ_CallBackRec TestAcq2();
[StructLayout(LayoutKind.Sequential)]
public struct tVDACQ_CallBackRec
{
public int rFlags;
public int rType;
public int rEvent;
public int rSocket;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string rMsg; //I believe this is the issue
public int rFrameWidth;
public int rFrameHeight;
public IntPtr rFrameBuffer;
public int rCaptureRows;
public int rCaptureFrames;
public int rCapturePercent;
public IntPtr rUserCallBackProc;
public IntPtr rUserParam;
public int rAborted;
public IntPtr rPacketData;
public int rFGControl;
}
//Then I just call the function
tVDACQ_CallBackRec testStruct= TestAcq2();
我希望一個結構具有所有定義的組件,但是我得到了標題中所述的錯誤。
同樣,如果我不包含 TCHAR(c++ 結構)和字符串(c# 結構),那么我不會收到錯誤,所以我知道這是根本問題,我不知道如何解決該部分。
編輯:有關解決方案,請參閱@David Heffernan 的第一條評論
解決此問題的最簡單方法是更改原型,以便將結構作為參數傳遞給 function 參考:
void _stdcall TestAcq2(tVDACQ_CallBackRecVal *retval)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.