英文:
How to pass args to wasm?
问题
#include <iostream>
int main(int argc, char** argv) {
if (argc > 1)
printf("%s", argv[1]);
}
构建:
emcc ./test.cpp -sENVIRONMENT=shell -o test.js
将命令行参数传递到C++代码中。
英文:
I use emcc to complie a C++ code into js.
But how to pass args to C++ code?
#include<iostream>
int main(int argc, char** argv) {
if (argc > 1)
printf("%s", argv[1]);
}
build :
emcc ./test.cpp -sENVIRONMENT=shell -o test.js
pass commadline args into c code
答案1
得分: 2
这个stackexchange答案似乎与您的用例相似:
在运行您的函数之前,放置以下代码:
Module['arguments'].push('first_param');
Module['arguments'].push('second_param');
int main(int argc, char *argv[])
{
assert(argc == 3);
assert(strcmp(argv[1], "first_param") == 0);
assert(strcmp(argv[2], "second_param") == 0);
}
编辑:
所以,最终我有时间安装了d8
,并使其正常工作。
对我来说,在生成的test.js
中,有这一行:
if (Module['arguments']) arguments_ = Module['arguments'];legacyModuleProp('arguments', 'arguments_');
您必须在此之前放置参数,所以它应该如下所示:
Module['arguments'] = [];
Module['arguments'].push('first_param');
Module['arguments'].push('second_param');
if (Module['arguments']) arguments_ = Module['arguments'];legacyModuleProp('arguments', 'arguments_');
然后使用emcc
进行编译,并使用d8
运行。我遇到了另一个错误,因为我没有在printf
调用中添加换行符,所以输出没有打印,这似乎也发生在您的代码中。幸运的是,有一个关于标准输出没有完全刷新的错误消息,所以我明白了这个问题。
英文:
It seems that this stackexchange answer is similar to your use-case:
Place
Module['arguments'].push('first_param');
Module['arguments'].push('second_param');
before you run your function.
int main(int argc, char *argv[])
{
assert(argc == 3);
assert(strcmp(argv[1], "first_param") == 0);
assert(strcmp(argv[2], "second_param") == 0);
}
Edit:
So, I finally had time to install d8
, and I made it work.
For me, in the generated test.js
, there is this line:
if (Module['arguments']) arguments_ = Module['arguments'];legacyModuleProp('arguments', 'arguments_');
You have to place the arguments before this, so it should look like:
Module['arguments'] = [];
Module['arguments'].push('first_param');
Module['arguments'].push('second_param');
if (Module['arguments']) arguments_ = Module['arguments'];legacyModuleProp('arguments', 'arguments_');
You then compile with emcc
and run with d8
. I got another error because I did not end my printf
call without a newline, so the output was not printing, a thing that seems to also happen in your code. Fortunately, there was an error message about the stdout not fully flushing, so I got to understand that was the problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论