我有从 C dll 导出的以下函数:
// C
BOOL WINAPI GetAttributeValue(
IN TAG * psTag,
IN DWORD dwEltIdx,
IN DWORD dwAttrIdx,
OUT BYTE * pbBuffer,
IN OUT DWORD * pdwLen )
// C#
[DllImport(Simulator.ASSEMBLY, SetLastError = true, CallingConvention = CallingConvention.StdCall)]
public extern static int GetAttributeValue(
IntPtr tag_id,
int element_index,
int attribute_index,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=4)]
byte[] data_buffer,
[In, Out]
ref int data_length
);
这就是我尝试使用它的方式,基于 SO 上的几个答案:
int result = -1;
byte[] buffer = new byte[2048];
int length = buffer.Length;
result = Simulator.GetAttributeValue(
tag.NativeId,
element_index,
attribute_index,
buffer,
ref length
);
int[] output = new int[length];
for (int i = 0; i < length; i++)
{
output[i] = buffer[i];
}
return output;
我尝试的另一件事是,同样基于在 SO 上找到的答案:
[DllImport(Simulator.ASSEMBLY, SetLastError = true, CallingConvention = CallingConvention.StdCall)]
public extern static int GetAttributeValue(
IntPtr tag_id,
int element_index,
int attribute_index,
IntPtr data_buffer, // changed this
[In, Out]
ref int data_length
);
// snip
GCHandle pinned_array = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr pointer = pinned_array.AddrOfPinnedObject();
result = Simulator.GetAttributeValue(
tag.NativeId,
element_index,
attribute_index,
pointer,
ref length
);
// snip, copying stuff to output
pinned_array.Free();
return output;
现在,在这两种情况下,mylength
似乎都正确填写,但buffer
始终为空。我不太精通 P/Invoke 和编组,所以我不确定这是否正确。有一个更好的方法吗?