Method not returning same result as a block of code in main. Identical code

62 views Asked by At

I am making a console application that sends and returns data in c# to a dll(c++), and returns it. I made it work but run into a problem I cant understand.

When I call a block of code in the main method it works, but when I make a method (with the same block of code) and call it from the main method, it breaks. I don't know how to explain better so I'll put the code for you to see.

 [DllImport("ActivatorDll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
 public static extern IntPtr fullname(byte[] firstname, byte[] lastname);

 static void Main(string[] args) 
 {
     string fn = "Foo";
     string ln = "United";

     IntPtr nameResult  = fullname(Encoding.Default.GetBytes(fn), Encoding.Default.GetBytes(ln));

     
     int len = 0;
     while (Marshal.ReadByte(nameResult, len) != 0) ++len;
     byte[] buffer = new byte[len];
     Marshal.Copy(nameResult, buffer, 0, buffer.Length);
     string res = Encoding.Default.GetString(buffer);

     string res2 = StringFromNative(nameResult);

     Console.WriteLine(res);
     Console.WriteLine(res2);

     Console.ReadLine();
 }

 public static string StringFromNative(IntPtr native)
 {
     int len = 0;
     while (Marshal.ReadByte(native, len) != 0) ++len;
     byte[] buffer = new byte[len];
     Marshal.Copy(native, buffer, 0, buffer.Length);
     return Encoding.Default.GetString(buffer);
 }

res is working as intended. res2 however is not working

result

Thanks!

I tried looking for a solution or explanation on here and on other platforms but couldn't get an answer anywhere.

the fullname function from the cpp of the dll

char* fullname(char* firstname, char* lastname)
{
    char result[1000] = ""; 
    strcpy_s(result, firstname);
    strcat_s(result, " ");
    strcat_s(result, lastname);
    
    return result;
}
0

There are 0 answers