我正在嘗試使用來自C#的非托管API,并將頭撞墻. (關(guān)于PInvoke,我是個(gè)初學(xué)者.)
頭文件的相關(guān)部分如下所示:
#define CTAPICALL __stdcall
#ifdef __cplusplus
extern "C" {
#endif
extern BOOL CTAPICALL ctTagReadEx(HANDLE,LPCSTR,LPSTR,DWORD,CT_TAGVALUE_ITEMS*); /* read extended data from tag */
#ifdef __cplusplus
}
#endif
CT_TAGVALUE_ITEMS如下所示:
typedef struct
{
DWORD dwLength; /* size, in bytes, of this structure */
unsigned __int64 nTimestamp; /* timestamp */
unsigned __int64 nValueTimestamp; /* value timestamp */
unsigned __int64 nQualityTimestamp; /* quality timestamp */
BYTE bQualityGeneral; /* quality general */
BYTE bQualitySubstatus; /* quality substatus */
BYTE bQualityLimit; /* quality limit */
BYTE bQualityExtendedSubstatus; /* quality extended substatus */
UINT nQualityDatasourceErrorCode; /* quality datasource error */
BOOLEAN bOverride; /* quality override flag */
BOOLEAN bControlMode; /* quality control mode flag */
} CT_TAGVALUE_ITEMS;
我的C#方法聲明:
[DllImport("ctapi.dll", SetLastError = true)]
public static extern bool ctTagReadEx(
IntPtr hCTAPI,
[MarshalAs(UnmanagedType.LPStr)] string tag,
[MarshalAs(UnmanagedType.LPStr)] System.Text.StringBuilder value,
int length,
CtTagValueItems tagValueItems);
C#結(jié)構(gòu):
[StructLayout(LayoutKind.Sequential)]
public struct CtTagValueItems
{
public int dwLength;
public ulong nTimestamp;
public ulong nValueTimestamp;
public ulong nQualityTimestamp;
public byte bQualityGeneral
public byte bQualitySubstatus;
public byte bQualityLimit;
public byte bQualityExtendedSubstatus;
public uint nQualityDatasourceErrorCode;
public uint bOverride;
public uint bControlMode;
}
當(dāng)我這樣調(diào)用它時(shí)(從以x86構(gòu)建的測試程序集中),我得到一個(gè)System.AccessViolationException:嘗試讀取或?qū)懭胧鼙Wo(hù)的內(nèi)存:
StringBuilder valueBuilder = new StringBuilder(300);
CtTagValueItems tagValueItems = new CtTagValueItems {dwLength = Marshal.SizeOf(typeof (CtTagValueItems))};
bool ok = CTAPI.ctTagReadEx(new IntPtr(handle), "TIC_Hold_PV", valueBuilder, valueBuilder.Capacity, tagValueItems);
我一直在嘗試各種事情,例如使用LayoutKind.Explicit和/或CallingConvention = CallingConvention.Cdecl,但無濟(jì)于事.
有人可以幫忙嗎,? 解決方法: >為什么將UINT映射為ushort.它沒有4個(gè)字節(jié)嗎? >原生BOOLEAN類型映射為4個(gè)字節(jié),即AFAIK. >您需要通過ref(作為類或ref)傳遞CtTagValueItems. >檢查呼叫約定. >檢查注釋中寫的內(nèi)容. 來源:https://www./content-1-538201.html
|