About Monkey 2 › Forums › Monkey 2 Programming Help › how to deal with extern cpp's string
This topic contains 3 replies, has 2 voices, and was last updated by
abakobo
1 year, 4 months ago.
-
AuthorPosts
-
December 5, 2017 at 10:11 pm #12151
I have an extern method i’d like to import/wrap to mx2 but it has a cpp string& as argument. I’ve already successful played with extern cher* using Cstring but can’t figure out how to play with thesestd cpp strings.
Is there something out of the box provided in mx2 (like Cstring/String.FromCstring) or do i have to convert it by myself cpp side?the method (the std::string& errorMsg is my trouble):
Monkey1readFromFile(const char* filename, std::string& errorMsg, b2World* existingWorld = NULL);December 6, 2017 at 12:13 pm #12177there’s the std::string.c_str() method that returns a char array, i’ll go with thar cpp side..
December 7, 2017 at 4:43 am #12186Also there is a method std::string::data() but:
There are no guarantees that a null character terminates the character sequence pointed by the value returned by this function.
AFAIK monkey’s CString is null-terminated, therefore c_str() is a right choice.
December 7, 2017 at 10:53 am #12188I finaly decided to go with std::copy so I keep the memory allocated by mx2 and don’t have to worry about GC/memory stuffs.
It’s passing a fixed size char_t array and then transforms it to string when back to mx2. It the way I felt the safest (with my knowledge;)the aim was to deal with the error message..
cpp side
Monkey12345678910111213141516171819202122b2World* b2dJsonReadFromFile_ext (const char* filename, char* charErrMsg, int charsize, b2World* existingWorld) {std::string errMsg;b2dJson json;b2World* returnWorld = json.readFromFile(filename, errMsg, existingWorld );if (charsize>8) { // the char array must have a certain size..if (errMsg.size()<charsize-2){std::copy(errMsg.begin(), errMsg.end(), charErrMsg);}else {std::string errMsgBis;errMsgBis = errMsg.substr (0,charsize-3);std::copy(errMsgBis.begin(), errMsgBis.end(), charErrMsg);charErrMsg[errMsgBis.size()] = '\0'; // terminating the cstring}}return returnWorld;}mx2 side
Monkey123456789101112131415161718192021ExternFunction b2dJsonReadFromFile_ext:b2World(filename:CString , errorMsg:char_t Ptr , charsize:Int , existingWorld:b2World = Null)PublicFunction b2dJsonReadFromFile:b2World(filename:String , existingWorld:b2World = Null)Local maxChrSize:Int=321Local buf:=New char_t[maxChrSize]Local retWorld:=b2dJsonReadFromFile_ext(filename , buf.Data , maxChrSize , existingWorld )#If __DEBUG__'print the error message if in debug modePrint String.FromCString( buf.Data )#EndifReturn retWorldEnd -
AuthorPosts
You must be logged in to reply to this topic.