2013-11-04 28 views
3

我有一个非托管DLL我引用我的项目中使用[DLLImport],但我匹配方法签名时收到奇怪的结果。奇怪的C#平台调用/ DLLImport行为

下面是来自DLL的例子签名:

DLLEXPORT unsigned long OpenPort(unsigned long ulPort, 
            unsigned long ulBaudRate, 
            unsigned long ulByteSize, 
            unsigned long ulPartity, 
            unsigned long ulStopBits, 
            unsigned long ulFlowControl) 

,这里是我的C#代码导入功能:

[DllImport("C:/my.dll", CallingConvention = CallingConvention.Cdecl)] 
public static extern uint OpenPort(ulong ulPort, ulong ulBaudRate, 
    ulong ulByteSize, ulong ulParity, ulong ulStopBits, ulong ulFlowControl); 

通知我宣布这与uint返回类型,如当我尝试使用ulong时,我得到意想不到的结果(长数字通常看起来有点像内存地址)。

但是,如果我使用返回类型int/uint,该函数将运行并返回预期结果。任何人都可以为我阐明这种行为吗?

谢谢。

+1

什么是您的平台上的sizeof(无符号长整数)?它可能是4个字节。 ulong永远是8. –

+0

@ ta.speot.is是的,你是对的..我不知道无符号long的大小在C#和C++之间是不一致的。没有什么令人困惑的:) – Alfie

+0

什么是不使用串口类构建? – Gusdor

回答

3

我假设您的目标平台是Windows,根据您的库的名称DllImport属性。在Windows上,对于32位和64位,C++ long类型(显然,无符号以及有符号)都是4个字节宽。所以,你需要使用uint而不是ulong来声明你的p/invoke。

正确的声明是:现在

[DllImport("C:/my.dll", CallingConvention = CallingConvention.Cdecl)] 
public static extern uint OpenPort(
    uint ulPort, 
    uint ulBaudRate, 
    uint ulByteSize, 
    uint ulParity, 
    uint ulStopBits, 
    uint ulFlowControl 
); 

,如果你的目标平台是Windows以外,那么你需要知道什么unsigned long是该平台上给出具体的建议。

+0

[此答案](http://stackoverflow.com/a/1764206/242520)是有关后一段的更多信息的绝佳起点。 –