如何使用 P/Invoke 将 unsigned long 传递给 Linux 共享库
我在 Mono 中使用 C#,并尝试使用 pinvoke 来调用 Linux 共享库。
c# 调用定义为:
[DllImport("libaiousb")]
extern static ulong AIOUSB_Init();
Linux 函数定义如下:
unsigned long AIOUSB_Init() {
return(0);
}
Linux 代码的编译命令是:
gcc -ggdb -std=gnu99 -D_GNU_SOURCE -c -Wall -pthread -fPIC
-I/usr/include/libusb-1.0 AIOUSB_Core.c -o AIOUSB_Core.dbg.o
我可以调用该函数,但返回结果很糟糕。它应该是 0,但我得到了一些巨大的损坏数字。
我已将 printf 放入 Linux 代码中,就在返回函数值之前,它是正确的。
我注意到有点奇怪的一件事是 printf 应该在函数返回之前发生。但是,我看到函数返回到C#,然后c#打印返回结果,最后显示printf结果。
I am using C# in Mono and I'm trying to use pinvoke to call a Linux shared library.
The c# call is defined as:
[DllImport("libaiousb")]
extern static ulong AIOUSB_Init();
The Linux function is defined as follows:
unsigned long AIOUSB_Init() {
return(0);
}
The compile command for the Linux code is:
gcc -ggdb -std=gnu99 -D_GNU_SOURCE -c -Wall -pthread -fPIC
-I/usr/include/libusb-1.0 AIOUSB_Core.c -o AIOUSB_Core.dbg.o
I can call the function ok but the return result is bonkers. It should be 0 but I'm getting some huge mangled number.
I've put printf's in the Linux code just before the function value is returned and it is correct.
One thing I have noticed that is a little weird is that the printf should occur before the function returns. However, I see the function return to C# and then the c# prints the return result and finally the printf result is displayed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自此处:
因此,C
unsigned long
通常会转换为 .NETUInt32
:From here:
For this reason a C
unsigned long
is usually translated to a .NETUInt32
:您可能在 C unsigned long 为 32 位的系统上运行它。 C# unsigned long 是 64 位。如果要确保返回值是 64 位无符号长整型,请包含
stdint.h
并从 AIOUSB_Init() 返回uint64_t
。You're probably running that on a system where C unsigned long is 32-bits. C# unsigned long is 64 bits. If you want to make sure the return value is a 64-bits unsigned long, include
stdint.h
and return anuint64_t
from AIOUSB_Init().