C#:在C导入DLL中使用负char数字
我导入了我用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
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();
}
}
在我的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);
如何成功地将负char值传递给c进口的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:
[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 tried to convert, but it doesn't work, it keeps sending positive values instead of negative.
EDIT: Tried 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 sucessfully pass negative char value to C imported DLL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
char
在C#中是一种16位的无符号类型,因此显然您不能使用它与C ++中的char
互动。sbyte
是必经之路。但是 > sbyte IS -128至127,类似于
,因此很明显-150不能适合在c#char_bit == 8
在C中的无符号char中sbyte
/cchar
注意:
chod> char
在C中可以签名或无符号,因此,如果您使用/j
在msvc 或-funSigned-char-char-char
在gcc中在项目中,您不能将负值传递给负值C函数char
in C# is a 16-bit unsigned type so obviously you can't use it to interop withchar
in C++.sbyte
is the way to go. However the range ofsbyte
is -128 to 127, similar tounsigned char
in C whenCHAR_BIT == 8
, so obviously -150 can't fit in C#sbyte
/Cchar
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