我正在尝试使用 C# 中的非托管 API,并将我的头撞到墙上。(当谈到 PInvoke 时,我是个初学者。)
头文件的相关部分如下所示:
#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# 结构:
[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;
}
当我这样调用它时(来自构建为 x86 的测试程序集),我得到System.AccessViolationException : Attempted to read or write protected memory
:
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
,但无济于事。
有人可以帮忙吗?