MALOUDA-PSA 2024-05-01 14:45 采纳率: 96.9%
浏览 3
已结题

WebAssembly的问题6

//main.cc:
#ifndef EM_PORT_API
#   if defined(__EMSCRIPTEN__)
#       include <emscripten.h>
#       if defined(__cplusplus)
#           define EM_PORT_API(rettype) extern "C" rettype EMSCRIPTEN_KEEPALIVE
#       else
#           define EM_PORT_API(rettype) rettype EMSCRIPTEN_KEEPALIVE
#       endif
#   else
#       if defined(__cplusplus)
#           define EM_PORT_API(rettype) extern "C" rettype
#       else
#           define EM_PORT_API(rettype) rettype
#       endif
#   endif
#endif

#include <stdio.h>
#include <string>

using namespace std;

EM_PORT_API(string) show_me_the_answer() {
    return "42--aa";
}

int main() {
    printf("你好,世界!\n");
    return 0;
}

// html:

console.log(Module._show_me_the_answer());

程序运行结果没用解析为 42--aa, 而是 undefined .

  • 写回答

6条回答 默认 最新

  • 码农阿豪@新空间代码工作室 Java领域优质创作者 2024-05-01 14:45
    关注
    让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
    这个问题的原因是代码中的 EM_PORT_API 宏定义没有正确的处理字符串返回类型。在定义 EM_PORT_API 的时候,应该分别处理返回类型为字符串和其他类型的情况。例如,应该这样定义 EM_PORT_API: #if defined(__EMSCRIPTEN__)
    #include <emscripten.h>
    #ifdef __cplusplus
        #define EM_PORT_API(rettype) extern "C" rettype EMSCRIPTEN_KEEPALIVE
    #else
        #define EM_PORT_API(rettype) rettype EMSCRIPTEN_KEEPALIVE
    #endif
    

    #else #if defined(__cplusplus) #define EM_PORT_API(rettype) extern "C" rettype #else #define EM_PORT_API(rettype) rettype #endif #endif 在定义字符串返回类型的时候,应该使用 char* 作为返回类型,并且需要约定返回的字符串的内存由调用方管理。这个问题的修复代码如下: #if defined(__cplusplus) #define EM_PORT_API(rettype) extern "C" rettype #else #define EM_PORT_API(rettype) rettype #endif EM_PORT_API(const char*) show_me_the_answer() { return "42--aa"; } 修复后,程序运行结果为 "42--aa",可以正确地返回字符串。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

问题事件

  • 系统已结题 5月20日
  • 已采纳回答 5月12日
  • 创建了问题 5月1日

悬赏问题

  • ¥15 Windows Script Host 无法找到脚本文件"C:\ProgramData\Player800\Cotrl.vbs”
  • ¥15 matlab自定义损失函数
  • ¥15 35114 SVAC视频验签的问题
  • ¥15 impedancepy
  • ¥15 求往届大挑得奖作品(ppt…)
  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图