c++ - 用变量模拟 C++ 命令行参数

标签 c++ dll command-line

我正在尝试将 C++ 源代码转换为 dll。为此,我将 wmain 更改为 MyMethod 并将此源的配置类型更改为动态库 (.dll)。

现在 MyMethod 就像:

int MyMethod(int argc, wchar_t* argv[])
{    }

在此之后,我将 args 传递给此文件,例如:

   MyFile.exe -a arg1 -b "arg2"

现在我想以同样的方式手动进入 dll,就像有人描述的那样 here我将我的代码更改为:

  int MyMethod(int argc, wchar_t* argv[])
{
    int argc1 = 2;
    wchar_t *argv1[2] = { L"-a arg1",L"-b arg2" };
    argc = argc1;
    argv = argv1;
}

但是上面的代码并没有和命令行一样的效果。

是什么让这段代码出错了?!(我的意思是命令行为变量分配了不同的东西?)

更新 1: 我的 wmain 方法是:

    int wmain(int argc, wchar_t* argv[])
    {
        int argc1 = 3;
        wchar_t *argv1[3] = { L"" , L"-a arg1",L"-b arg2" };

        argc = argc1;
        argv = argv1;

        if (!ArgTranslate(argc, argv))
        {
            MessageBoxA(0, "Error", "Not valid args", 0);
            return -1;
        }
    MessageBoxA(0, "Valid", "It is valid", 0);
    return 0;
}

bool ArgTranslate(int argc, wchar_t* argv[])
{

    wchar_t* Parm1= NULL;   
    wchar_t* Parm2= NULL;   

    for (int i = 1; (i < argc) && ((i + 1) < argc); i += 2)
    {
        if (wcscmp(argv[i], L"-a") == 0)
            Parm1 = argv[i + 1];
        else if (wcscmp(argv[i], L"-b") == 0)
            Parm2 = argv[i + 1]; 
    }
    if (Parm1 == NULL || Parm2 == NULL)
        return false;
    else
    return true;
}

最佳答案

main 函数的第一个参数是可执行文件本身的名称。 来自 cppreference :

argv[0] is the pointer to the initial character of a null-terminated multibyte strings that represents the name used to invoke the program itself (or an empty string "" if this is not supported by the execution environment)

如果不使用,您可以只提供一个空字符串 - 所以在您的情况下,您将有 argc1 = 3argv1[3] = {L"", L"- arg1",L"-b arg2"};


编辑 我在评论中提供了简单的修复。这是一个稍微接近 C++11 的版本,也没有使用不必要的临时变量和对 main 的参数的赋值

#include <array>

bool ArgTranslate(int argc, wchar_t const* argv[])
{
    wchar_t const* Parm1 = nullptr;   
    wchar_t const* Parm2 = nullptr;   

    for (int i = 1; (i + 1) < argc; i += 2)
    {
        if (wcscmp(argv[i], L"-a") == 0)
            Parm1 = argv[i + 1];
        else if (wcscmp(argv[i], L"-b") == 0)
            Parm2 = argv[i + 1]; 
    }
    if (!Parm1 || !Parm2)
        return false;
    else
        return true;
}

int wmain(int argc, wchar_t* argv[])
{
    std::array<wchar_t const*, 5> args{L"" , L"-a", L"arg1", L"-b",  L"arg2"};

    if (!ArgTranslate(static_cast<int>(args.size()), args.data()))
    {
        MessageBoxA(0, "Error", "Not valid args", 0);
        return -1;
    }
    MessageBoxA(0, "Valid", "It is valid", 0);
    return 0;
}

关于c++ - 用变量模拟 C++ 命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32613985/

相关文章:

c++ - 如何从 Microsoft Access 调试 dll

Linux - 安全地杀死 apache 拥有的一些进程

c++ - 用 new int[10] 分配的内存必须用 delete[] 释放

c++ - 什么是 "metadata operation failed"VS2008 链接器错误?

c++ - Visual Studio DLL 依赖项导致不必要的重新链接

c# - 将 float* 编码到 C#

perl - 如何在 Perl 中使用反引号捕获两个不同变量中的 STDOUT 和 STDERR

java - 哪个部署的 jar 包含 android.os.SystemClock?

c++ - 这个 GNU C,C++ 宏的扩展是什么

C++:字符串结构的相等性