将std :: string中的const char *传递到Lua堆栈时会变为null。

我有一段代码,从我的游戏支持的不同类型设备中收集设备 ID,并设置 lua 全局变量,将当前设备的 id 值存储在其中。

当我获得 iOS 设备的 id 时,我从混合的 C++/Objective-C 类中收到一个 const char*,并将其传递到 Lua 堆栈中。一切都运行良好。

然而,我从负责获取 Android 设备 id 的代码中收到的是 std::string。当我推送 deviceId.c_str() 时,我在 Lua 中得到了 nil。

我尝试从负责获取设备 id 的代码传递 const char*,但当它从函数中返回时,指针似乎出了些问题 [这就是为什么我决定返回字符串,这种方式可以正常工作]。

我该怎么做才能无问题地传递 std::string 的 const char*?

编辑:

我尝试使用 strcpy,但它没有起作用:/ 仍然存在相同的问题。

那么...负责从不同设备中收集 deviceId 的代码如下所示:

#include "DeviceInfo.h"
#include "DeviceInfoIOS.h"
#include "DeviceInfoAndroid.h"
#include <string>

USING_NS_CC;

extern "C" {

const char *getDeviceId() {

    const char *deviceId;

    CCLog("test");

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    DeviceInfoIOS ios;
    deviceId = ios.getIOSDeviceId();
    CCLog("iOS platform %s", deviceId);

#endif  // CC_PLATFORM_IOS

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

    CCLog("Android platform");
    std::string tempId = getAndroidDeviceId();
    CCLog("Android platform test %s", tempId.c_str());
    char y[tempId.size() + 1];
    strcpy(y, tempId.c_str());
    deviceId = (const char*) y;
    CCLog("Android platform %s", deviceId);

#endif  // CC_PLATFORM_ANDROID
    CCLog("Finished platform check");
    return deviceId;
}

}

只是小小的提示:所有日志看起来都没问题。成功传递了设备 id。

这是我将设备 id 传递到 Lua 的方式:

//deviceInfo
CCLog("DeviceInfo load");
const char *deviceId = getDeviceId();
CCLog("DeviceInfo %s", deviceId);
lua_pushstring(d_state, deviceId);
lua_setglobal(d_state, "DEVICE_ID");

同时,在这里,日志文件包含设备 id。

原文链接 https://stackoverflow.com/questions/8703560

点赞
stackoverflow用户734069
stackoverflow用户734069

你的 getDeviceId 函数有问题。tempIdy 都是栈变量。一旦你返回函数,它们就会被 _销毁_。返回指向栈变量的指针总是不明智的。

你的函数应该返回一个 std::string。如果不能返回字符串,则应该返回使用 new 分配char* 数组,并且用户需要使用 delete 进行释放。这通常是为什么最好直接返回 std::string。或者,你可以使用固定大小(而不是基于字符串的大小)来声明 y 作为 static 本地变量。

2012-01-02 20:06:55