hi friend,
When I call the C++ dll function, the following error occurred:
Error Message=Attempts to read from or write to protected memory. This is often an indication that other memory is corrupt.
C++ codes:
string test(string s[]){string t="";for(int i=0;i<2;i++){t+=s[i];}return t;}
C# codes:
class Program
{
[DllImport("safeTest.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern string test(string[] s);static void Main(string[] args){
string[] city = { "London ", "San Francisco " };string temp = test(city);Console.WriteLine(temp);Console.ReadKey();
}
}
Thanks.

VulpesRank #55 · 29.2K reputationPosted Aug 2, 2014, 11:12 AM EDT
You need to use C-style strings instead.
Also rather than return a string, it's better to pass the function a pointer to a buffer which it can fill with the result. Bearing in mind that strings are immutable in C#, this can be done using a StringBuilder.
The following code is working OK for me:
// C++ code
// C# code
// work out capacity needed for buffer
London San Francisco
Ken HRank #2,315 · 610 reputationPosted Aug 2, 2014, 7:55 PM EDT
public static extern string test(StringBuilder buffer, string[] s, int len); // error
public static extern void test(StringBuilder buffer,string[] s,int len); // right
Thank for you,Vulpes. :)
VulpesRank #55 · 29.2K reputationPosted Aug 3, 2014, 1:39 AM EDT
It still worked OK as we were not using it.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts