Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C#: Use negative char numbers in C imported dll

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading