我有以下 C 代码(.h/header),我需要将其转换为 c# 但是我得到的结果是非常随机的...... LED 颜色在调用之间没有变化,但浮点值是并且它们看起来完全与实际值(我设置的)无关。
奇怪的是,我使用相同的结构设置值并且它可以工作 =S
typedef struct TSS_Color
{
float r;
float g;
float b;
}TSS_Color;
/**
* \brief Reads the color of the LED on the sensor.
*
* @param id The identifier for the 3-Space device.
* @param color The color of the device's LED is written to the referenced variable.
* @return An error code indicating either success or failure to execute the call. The code will also indicate the reason for the failure.
*/
EXPORT TSS_Error getLEDColor(TSS_ID id, TSS_Color *color);
/**
* \brief Sets the color of the LED on the sensor to the given RGB color.
*
* @param id The identifier for the 3-Space device.
* @param color The color the device's LED is being set to.
* @return An error code indicating either success or failure to execute the call. The code will also indicate the reason for the failure.
*/
EXPORT TSS_Error setLEDColor(TSS_ID id, TSS_Color color);
然后在 C# 中,我将其转换为以下代码:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Color
{
public float R;
public float G;
public float B;
}
[DllImport("ThreeSpace_API.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "setLEDColor")]
public static extern ResultEnum SetLedColor(
uint deviceId,
Color color
);
[DllImport("ThreeSpace_API.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "getLEDColor")]
public static extern ResultEnum GetLedColor(
uint deviceId,
ref Color color
);
我的问题是 GetLedColor (据称在 C 中工作正常)颜色结构的浮点数似乎都是随机组成的,并且它们的值无论如何都会发生变化(它们不应该)。
包括使用上述代码的代码:
public void SetLedColour(Color color)
{
var resultCode = ThreeSpaceInterop.SetLedColor(_deviceId, color);
}
public Color GetLedColour()
{
Color result =new Color();
var resultCode = ThreeSpaceInterop.GetLedColor(_deviceId, ref result);
return result;
}
resultCode 显示预期的“NoError”。
应该注意的是,使用 OUT 而不是 REF 并不能解决问题......
[DllImport("ThreeSpace_API.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "getLEDColor")]
public static extern ResultEnum GetLedColor(
uint deviceId,
out Color color
);
编辑:他们提供了一个测试 cpp 示例,该程序使用相同的库按预期工作。
这是他们在cpp中的代码:
printf("==================================================\n");
printf("Getting the LED color of the device.\n");
TSS_Color color;
tss_error= getLEDColor(device, &color);
if(!tss_error){
printf("Color: %f, %f, %f\n", color.r, color.g, color.b);
}
else{
printf("TSS_Error: %s\n", TSS_Error_String[tss_error]);
}
printf("==================================================\n");