Home > Software engineering >  C#: Use negative char numbers in C imported dll
C#: Use negative char numbers in C imported dll

Time:06-21

I imported a DLL that I compiled with rato.hpp:

#ifndef RATO_H
#define RATO_H

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

and 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();
        }
    }

When importing it in my CSharp code, I can't cast negative values:

[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);

I tryied to convert, but it doesn't work, it keeps sending positive values instead of negative.

EDIT: Tryied to convert to Sbyte but get error "System.OverflowException: 'Value was either too large or too small for a signed byte.'"

[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);

How can I sucessfull pass negative char value to C imported Dll?

Thanks in advance and sorry for my bad english.

CodePudding user response:

char in C# is a 16-bit unsigned type so obviously you can't use it to interop with char in C . sbyte is the way to go. However the range of sbyte is -128 to 127, similar to unsigned char in C when CHAR_BIT == 8, so obviously -150 can't fit in C# sbyte/C char

Note: char in C can be signed or unsigned, so if for example you use the /J option in MSVC or the -funsigned-char option in GCC in your project then you can't pass a negative value to the C function

  •  Tags:  
  • c# c
  • Related