SDK Question Access violation, oapiWriteScenario

Bj

Addon Developer
Addon Developer
Donator
Joined
Oct 16, 2007
Messages
1,886
Reaction score
11
Points
0
Location
USA-WA
Website
www.orbiter-forum.com
Here is the problem;

Access violation reading location

This is it (shortened)

Code:
    string name = "hi";
        char * buff;
        name.push_back(NULL); //append 0 to string so string is 0 terminiated
        //name now == 'hi[null]'  //just to be sure- 
        strcpy(buff,name.c_str());
        oapiWriteScenario_string(scn,"NAMED",buff);

Before anyone asks, it still doesn't work when you remove the push_back.

Something like this works;

oapiWriteScenario_string(scn,"NAMED","babalu");

No other errors, any ideas?
 
You never allocate space for buff.
Why do you want to copy the string in the first place, instead of using name.c_str() directly as the 3rd argument in oapiWriteScenario_string?
 
You never allocate space for buff.
Why do you want to copy the string in the first place, instead of using name.c_str() directly as the 3rd argument in oapiWriteScenario_string?


oop

The more obvious they are...

anyway, its because of compiler error;

'oapiWriteScenario_string' : cannot convert parameter 3 from 'const char *' to 'char *'


This works, Thanks :tiphat:

string name = "hi";
char * buff = new char[50];
strcpy(buff,name.c_str());

FILEHANDLE scn = oapiOpenFile ("TEST",FILE_APP,ROOT);

//oapiWriteScenario_string(scn,"NAMED",buff);
oapiWriteScenario_string(scn,"NAMED",name.c_str());
 
You could also just do this:

Code:
string name = "hi";
oapiWriteScenario_string(scn,"NAMED", (char *)name.c_str());

...to cast away the constness there. In this case it is safe to do because oapiWriteScenario_string does not modify the string passed in.

In any case, if you use the "new->copy->write" sequence anyway, don't forget to free up buff when you're done with it. But all that is a lot less elegant than just typecasting it IMO. :)
 
You could also just do this:

Code:
string name = "hi";
oapiWriteScenario_string(scn,"NAMED", (char *)name.c_str());

...to cast away the constness there. In this case it is safe to do because oapiWriteScenario_string does not modify the string passed in.

In any case, if you use the "new->copy->write" sequence anyway, don't forget to free up buff when you're done with it. But all that is a lot less elegant than just typecasting it IMO. :)
I'd recommend using const_cast so it's explicitly obvious what you're doing:
Code:
string name = "hi";
oapiWriteScenario_string(scn,"NAMED", const_cast<char *>(name.c_str()));
 
Much better would be if Orbiters API would use correct "const" attributes for the call by reference parameters... but well, there are many good fixes for it. :lol:
 
Yup, const correctness never hurts ...
I'd ask for this as a feature request.
 
Back
Top