[英]Pass C# Byte[] to C++ API
I have to pass an Byte array containing an MAC-Address to a C++ Method. 我必须将包含MAC地址的字节数组传递给C ++方法。 Since I don't have much experience with working with c C++ APIsI don't know how to do this.
由于我没有使用c C ++ API的丰富经验,因此我不知道该怎么做。 I've tried to pass the array itself, but got an
invalid parameter code
as response from the API . 我尝试传递数组本身,但是从API获得了
invalid parameter code
作为响应 。 I've also tried to create an IntPtr
but to no avail. 我也曾尝试创建一个
IntPtr
但无济于事。
I know that the problem is that C++ can't handle managed datatypes such as arrays, so I've to create a unmanaged array somehow, I think. 我知道问题在于C ++无法处理托管数据类型(例如数组),所以我认为必须以某种方式创建非托管数组。
Here is the definition of the C++ Method: 这是C ++方法的定义:
ll_status_t LL_Connect(
ll_intf_t intf,
uint8_t address[6]);
The array in C# is defined the following way: C#中的数组是通过以下方式定义的:
Byte[] addr = new Byte[6];
Of course, the array is not empty. 当然,数组不是空的。
For example: 例如:
C++ C ++
extern "C"
{
__declspec(dllexport) void GetData(uint8_t* data, uint32_t length)
{
for (size_t i = 0; i < length; ++i)
data[i] = i;
}
}
C# C#
[DllImport("LibName.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern void GetData([In, Out] [MarshalAs(UnmanagedType.LPArray)] byte[] data, uint length);
And use in C# 并在C#中使用
byte[] data = new byte[4];
GetData(data, (unit)data.Lenght);
If you have an array fixed length, for example: 如果您有固定长度的数组,例如:
C++ C ++
extern "C"
{
__declspec(dllexport) void GetData(uint8_t data[6])
{
for (size_t i = 0; i < 6; ++i)
data[i] = i;
}
}
C# C#
[DllImport("LibName.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern void GetData([In, Out] [MarshalAs(UnmanagedType.LPArray, SizeConst = 6)] byte[] data);
And use in C# 并在C#中使用
byte[] data = new byte[6];
GetData(data);
For your case: 对于您的情况:
[DllImport("LibName.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int LL_Connect(byte intf, [In, Out] [MarshalAs(UnmanagedType.LPArray, SizeConst = 6)] byte[] address);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.