Reputation: 453
In this wrapper method, I return a DN_OPstruct
, which has two const char*
properties: TargetNode_Identifier
and Name
. For p/invoke
, I have to stay with const char*
- Type, std::string
won't work:
DN_OPstruct getDnOperationIntern(const char* charGuid){
DN_OPstruct op;
UA_OPstruct _op;
_op = GetOPData(charGuid);
op.direction = _op.direction;
op.Name = _op.Name.toUtf8();
op.TargetNode_Identifier = _op.TargetNode_Identifier.toUtf8();
op.TargetNode_NamespaceIndex = _op.TargetNode_NamespaceIndex;
op.Type_of_OP = _op.Type_of_OP;
return op ;
}
As I read, you have to strcpy
const char*
s . Without such help, the pointers of the properties will lose thier reference and I get false properties. Example for strcpy:
strcpy(new char[output.size()], output.c_str());
How can implement this in my method?
Upvotes: 0
Views: 410
Reputation: 726489
You shouldn't implement it in your method - instead, you should implement it in a separate function, and use it in all places where you need to make a copy of a string:
char *copyCString(const string& s) {
char *res = new char[s.size()+1]; // Add 1 for null terminator
strcpy(res, s.c_str());
return res;
}
Now you can use this function to make copies as needed:
op.Name = copyCString(_op.Name);
op.TargetNode_Identifier = copyCString(_op.TargetNode_Identifier);
You could start with const char*
, too:
char *copyString(const char* s) {
char *res = new char[strlen(s)+1]; // Add 1 for null terminator
strcpy(res, s);
return res;
}
Now you call it like this:
op.Name = copyString(_op.Name.toUtf8());
op.TargetNode_Identifier = copyString(_op.TargetNode_Identifier.toUtf8());
Of course you are responsible for deleting the copies when you are done:
delete[] op.Name;
delete[] op.TargetNode_Identifier;
It would be a good idea to define a function for this, too:
void freeCopiedString(char *s) {
delete[] s;
}
Upvotes: 1