如何通过emscripten在C ++和javascript之间传递字符串 [英] How to pass strings between C++ and javascript via emscripten
问题描述
我正在学习emscripten,在C ++和JS之间传递字符串时,我甚至无法获得最基本的字符串操作。
I am learning emscripten, and I can't even get the most basic string manipulation working, when passing strings between C++ and JS.
例如,我会喜欢写一个字符串长度函数。在C ++中:
For example, I would like to write a string length function. In C++:
extern "C" int stringLen(std::string p)
{
return p.length();
}
从javascript调用:
Called from javascript as:
var len = _stringLen("hi.");
这对我来说产生 0
。如何按预期工作?我应该在这里使用哪种字符串类型? char const *
? 的std :: wstring的
? 的std :: string
?似乎没有工作;我总是得到相当随机的值。
This yields 0
for me. How do I make this work as expected? Which string type should I use here? char const*
? std::wstring
? std::string
? None seem to work; I always get pretty random values.
这只是一个开始......我如何从C ++返回这样的字符串?
This is only the beginning... How do I then return a string from C++ like this?
extern "C" char *stringTest()
{
return "...";
}
在JS中:
var str = _stringTest();
再一次,我找不到办法让这项工作;我总是在JS中得到垃圾。
Again, I cannot find a way to make this work; I always get garbage in JS.
所以我的问题很清楚:如何通过Emscripten封送JS和C ++之间的字符串类型?
So my question is clearly: How do I marshal string types between JS and C++ via Emscripten?
推荐答案
externC无法识别std :: string。
extern "C" doesn't recognize std::string.
您可能想尝试这个:
Test.cpp
You may want to try this:
Test.cpp
#include <emscripten.h>
#include <string.h>
extern "C" int stringLen(char* p)
{
return strlen(p);
}
使用以下命令编译cpp代码:
Use the following command to compile the cpp code :
emcc Test.cpp -s EXPORTED_FUNCTIONS="['_stringLen']
示例测试代码:
Test.html
Sample test code :
Test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello World !</title>
<script src="a.out.js"></script>
<script>
var strLenFunction = Module.cwrap('stringLen', 'number', ['string']);
var len1 = strLenFunction("hi."); // alerts 3
alert(len1);
var len2 = strLenFunction("Hello World"); // alerts 11
alert(len2);
</script>
</head>
</html>
这篇关于如何通过emscripten在C ++和javascript之间传递字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!