Reputation: 351
When I pass a char* as a parameter to a DLL, I can get a new char* when I "return" a char* from DLL, but I can't get it done when I just use that char* parameter and return nothing.
This DLL function is OK, seems I can pass a char* to DLL.
void getStr(char *str){
print("%s\n", str);
}
This is OK, too. It seems I can modify a pointer inside DLL.
void setInt(int a, int b, int *sum){
*sum = a + b;
}
But there is no any luck when the pointer points to a char array.
void setStr(char* str) {
char tmp[] = "From DLL";
int len = strlen(tmp) + 1;
str = (char*)malloc(len);
memcpy(str, tmp, len);
}
I try to call this DLL function from a c++ program like this:
int main()
{
char tmp[] = "Hello World!";
setStr(tmp); // I hope I can get "From DLL" here.
std::cout << tmp;
}
The output is still "Hello World!", nothing happened after I try to get a new char*. If I set the return value of DLL function to char* and get the return value in c++ program, everything is fine, but I can't just use parameter to do it.
Did I miss something?
Upvotes: 0
Views: 484
Reputation: 75062
To modify given string buffer, modify given string buffer.
void setStr(char* str) {
char tmp[] = "From DLL";
int len = strlen(tmp) + 1;
memcpy(str, tmp, len);
}
int main()
{
char tmp[] = "Hello World!";
setStr(tmp); // I hope I can get "From DLL" here.
std::cout << tmp;
}
To modify the pointer, pass a pointer to the pointer.
void setStr(char** str) {
char tmp[] = "From DLL";
int len = strlen(tmp) + 1;
*str = (char*)malloc(len);
memcpy(*str, tmp, len);
}
int main()
{
char tmp[] = "Hello World!";
char* ptmp = tmp; // character array is NOT a pointer, so add a pointer to modify
setStr(&ptmp); // I hope I can get "From DLL" here.
std::cout << ptmp;
}
Upvotes: 3