Passing and retrieving a string calling a c++ function from c#

R

roben

I want to call a function in C++ (external dll) from C#.
However the string is still empty after returning from the function.

-------------------
C#
-------------------
[DllImport("ccw.dll", CharSet=CharSet.Auto)] public static extern int
HelloWorld(StringBuilder abc);

StringBuilder mytext= new StringBuilder(1000);
AuthResult = HelloWorld(mytext);

//Here the string is still empty

-------------------
C++
-------------------
int HelloWorld(char *mytext)
{
mytext = "Hi..Test";
return 0;
}


Hope you can help!
Any suggestions?
 
N

Nicholas Paldino [.NET/C# MVP]

roben,

The reason it is still empty is because the pointer that you are passing
in is not able to be modified. You are trying to reassign the pointer to
the character array, which can't be done. If you want to perform a
reassignment of the pointer, then you have to pass a pointer to a pointer.

What you should be doing is calling strcpy on the pointer being passed
in, and passing the other string you want to copy it to. Then, it should
work.

Hope this helps.
 
R

roben

hi,

perfect... You're right...Thanks!

I just needed to change it to strcpy(mytext, "Hello...");


Nicholas Paldino said:
roben,

The reason it is still empty is because the pointer that you are passing
in is not able to be modified. You are trying to reassign the pointer to
the character array, which can't be done. If you want to perform a
reassignment of the pointer, then you have to pass a pointer to a pointer.

What you should be doing is calling strcpy on the pointer being passed
in, and passing the other string you want to copy it to. Then, it should
work.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

roben said:
I want to call a function in C++ (external dll) from C#.
However the string is still empty after returning from the function.

-------------------
C#
-------------------
[DllImport("ccw.dll", CharSet=CharSet.Auto)] public static extern int
HelloWorld(StringBuilder abc);

StringBuilder mytext= new StringBuilder(1000);
AuthResult = HelloWorld(mytext);

//Here the string is still empty

-------------------
C++
-------------------
int HelloWorld(char *mytext)
{
mytext = "Hi..Test";
return 0;
}


Hope you can help!
Any suggestions?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top