Reputation: 3423
I've got this piece of code, where I gather device id from different types of devices supported by my game and set lua global to have value of id of current device. When I get id of the iOS device I receive a const char* from a mixed C++/Objective-C class and pass it on to the Lua stack. It all works fine. However I receive std::string from a piece of code responsible for getting Android device id. When I push deviceId.c_str() I get nil in Lua. I've tried passing const char* from the code responsible for getting the device id, but then it seems something wrong goes on with the pointer when it's returned from function [that's why I decided to return string, it works fine this way].
What should I do to allow passing const char* out of std::string without problems?
EDIT: I've tried using strcpy but it didn't work :/ still having the same problem.
So.. the code responsible for gathering deviceId from different devices looks like this:
#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;
}
}
Just a small note: All the logs look ok. Devie id is passed fine.
This is how I pass device id to Lua:
//deviceInfo
CCLog("DeviceInfo load");
const char *deviceId = getDeviceId();
CCLog("DeviceInfo %s", deviceId);
lua_pushstring(d_state, deviceId);
lua_setglobal(d_state, "DEVICE_ID");
Also in here, logfile contains the device id.
Upvotes: 0
Views: 2287
Reputation: 473537
Your getDeviceId
function is broken. Both tempId
and y
are stack variables. They will be destroyed once you return. Returning pointers to stack variables is always a bad idea.
Your function ought to return a std::string
. Failing that, it should return a char*
array that it allocates with new
, and that the user is expected to deallocate with delete
. That's generally why it's preferable to just return a std::string
. Alternatively, you could delcare y
as a static
local variable using a fixed size (rather than one based on the string).
Upvotes: 2