Issue
I'm writing an Android application which reads a text file in c++ (NDK).
I copy the file list
from assets
folder to /data/user/0/my-package/files/list
where I can read with my native code, after the copy is done or if the destination file is exist, I do the following:
const char* fileName = env->GetStringUTFChars(_name, nullptr);
const char* filePath = env->GetStringUTFChars(_destination, nullptr);
if(copy_file(AAssetManager_fromJava(env, manager),fileName, filePath)){
Reader *r = new Reader();
log("Initializing reader with file: %s",filePath);
thread t(&Reader::read, r, filePath);
t.detach();// will crash if no detach, join() will block the UI thread.
}
And my Reader::read
:
void Reader::read(const char* filePath){
log("Reading from file: %s",filePath);
ifstream infile(filePath);
string line;
while(infile>>line){
// read logic ...
}
}
I get different output, some times
Initializing reader with file: /data/user/0/my-package/files/list
Reading from file: /data/user/0/my-package/files/list
and everything works as expected. But some times I get
Initializing reader with file: /data/user/0/my-package/files/list
Reading from file: /data/user/0/my-package/files
see? It seems that the file path is cut somehow, and my ifstream
is trying to read the directory files
.
I was told that the argument filePath
will be passed to the thread by value by default, and there's no other thread working with the variable, only thing that happens to filePath
after the thread initialization, is:
env->ReleaseStringUTFChars(_destination, filePath);
I have tried many different ways to pass the file path to new thread, if I pass the filePath
like
std::ref(filePath)
, I will get empty string in read
function, because the variable is already cleared outside.
Any suggestion on this?
Solution
Calling ReleaseStringUTFChars before the thread has finished will be disastrous, since the memory that filePath points too will be freed. If you don't fully understand how pointers and memory handling works, I suggest using something like std::string instead of const char*, and pass that string to your function.
Answered By - Sven Nilsson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.