C#:在 C 导入的 dll 中使用负字符数

茹乌津胡

我导入了一个用 rato.hpp 编译的 DLL:

#ifndef RATO_H
#define RATO_H

extern "C"
{
    __declspec(dllexport) void mouse_move(char button, char x, char y, char wheel);
}
#endif

和rato.cpp:

typedef struct {
        char button;
        char x;
        char y;
        char wheel;
        char unk1;
    } MOUSE_IO;

void mouse_move(char button, char x, char y, char wheel)
    {
        MOUSE_IO io;
        io.unk1 = 0;
        io.button = button;
        io.x = x;
        io.y = y;
        io.wheel = wheel;

        if (!callmouse(&io)) {
            mouse_close();
            mouse_open();
        }
    }

在我的 CSharp 代码中导入它时,我不能转换负值:

[DllImport("Rato.dll")]
public static extern void mouse_move(char button, char x, char y, char wheel);

mouse_move((char)0,(char)0,(char)-150,0);

我尝试转换,但它不起作用,它一直发送正值而不是负值。

编辑:尝试转换为 Sbyte 但收到错误“System.OverflowException:'对于有符号字节而言,值太大或太小。'”

[DllImport("Rato.dll")]
public static extern void mouse_move(sbyte button, sbyte x, sbyte y, sbyte wheel);

mouse_move(0,0,Convert.ToSByte(-150),0);

我怎样才能成功地将负字符值传递给 C 导入的 Dll?

在此先感谢并为我的英语不好感到抱歉。

福禄

char在 C# 中是 16 位无符号类型,因此显然您不能使用它与charC++ 中的互操作。sbyte是要走的路。然而,范围sbyte是 -128 到 127,类似于unsigned charC 中的 when CHAR_BIT == 8,所以显然 -150 不适合 C# sbyte/Cchar

注意:char在 C 中可以是有符号的或无符号的,因此,例如,如果您在项目/J中使用 MSVC中的选项或-funsigned-charGCC中的选项,那么您不能将负值传递给 C 函数

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章