DLL out int不被接受

时间:2014-03-02 18:00:40

标签: c# c++ dll

我在C#中构建了一个DLL。

在以下函数中,IDE告诉我函数_api.Version有一些无效的参数。但我不认为这是真的。

    public int getVersion(out int uMaj, out int uMin, out int uBuild, out int uDev)
    {
        ApiError error;
        error = _api.Version(uMaj, uMin, uBuild, uDev); //IDE does not like this
        int iRet = (int)error;
        return iRet;
    }

“版本”功能定义如下:

    public ApiError Version(out int major, out int minor, out int build, out int device);

有人看到我的错误吗? 谢谢你的帮助!

我的DLL的整个代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using B.Api;

namespace ABWrapperNET
{

    public class clsWrapper
    {
        someApi _api = new someApi();

        public int getVersion(out int uMaj, out int uMin, out int uBuild, out int uDev)
        {
            ApiError error;
            error = _api.Version(uMaj, uMin, uBuild, uDev);
            int iRet = (int)error;
            return iRet;
        }
    }
}

2 个答案:

答案 0 :(得分:3)

在C#中,您需要在调用网站以及成员声明中指定outref修饰符。这意味着任何阅读代码的人都知道发生了什么。 (在我看来,这对可读性有很大的推动作用。)

所以你想要:

public int GetVersion(out int uMaj, out int uMin, out int uBuild, out int uDev)
{
    ApiError error = _api.Version(out uMaj, out uMin, out uBuild, out uDev);
    return (int)error;
}

注意:

  • 我修改了方法名称以遵循.NET命名约定
  • 我删除了error
  • 的无意义声明/作业分割
  • 我已将演员的临时变量移除到int;如果你想要
  • ,你可以重新引入它以进行调试
  • 我个人会在每个方法参数上删除u前缀,例如:

    public int GetVersion(out int major, out int minor, out int build, out int foo)
    

...用缩写“dev”代表的任何内容替换foo

您还应该考虑只返回一个Version对象,并使用异常来处理错误:

public Version GetVersion()
{
    int major, minor, build, foo;
    ApiError error = _api.Version(out major, out minor, out build, out foo);
    if (error != ApiError.Success) // Or whatever it uses
    {
        // You'd probably need to create this class yourself
        throw new ApiException(error);
    }
}

答案 1 :(得分:2)

在对函数的调用中,您需要在变量名前加out

我猜这个要求是为了可读性目的。通常情况下,程序员不会期望将一个整数传递给要修改的函数,因此如果outref不在那里,那么被修改的变量将是一个巨大的惊喜。