char* from c code via dllimport loses last character

Hello,

Im using dllimport to get a char* from a c function like this:

<code>

[DllImport("RasWrapper.dll")]

private static extern String findIpOfRasConnection(String conn);

public static string RasConnectionIP(string connection)

{

return findIpOfRasConnection(connection);

}

</code>

In the C function, the char* looks as it should, but in c# it has lost the last character. The C function ends like this:

<code>

char* retValue = raspppip.szIpAddress;

return retValue;

</code>

where raspppip is the structure http://msdn.microsoft.com/library/en-us/rras/rras/raspppip_str.asp

Anyone knows whats going on thanks!

/ Rolle



Answer this question

char* from c code via dllimport loses last character

  • JennaG

    Yes, that is pretty fundamental and you'll shoot yourself in the foot many times if you don't grok it. Variables that are declared locally inside the function body are allocated on the CPU stack. This is a very efficient way to allocate memory, many, many times faster than allocating memory on the heap. However, that allocated stack memory is only valid as long as the function executes. When it returns, the compiler "deletes" the stack memory. The variable values are still there but subject to be overwritten when another function needs stack space.

    Using the static keyword tells the compiler to not allocate the variable on the stack but permanently in the data segment. It is almost always a bad idea because there will be only one instance of that variable. In your case, if you store the returned char*, then call the function again, you will see that the 2nd function call modified your original char* value.

    The real solution is to return a string allocated on the heap. Depending on the framework you're using, that is best done by a CString, String, std::string, etc. The "C" way to solve this is to pass your function a buffer that it fills with a copy of the string.



  • Redfish1409

    Ok thanks again. Sometimes the compiler warns about this:

    "C4172: returing address of local variable or temporary"

    but not this time. If i rewrite the above by copying the char* (retValue) into a char[] and tries to return that array, I get the above warning... Strange, as I thought char* and char[] were constructed in exactly the same way.

    From now on I will only pass paramters out of the function using pointers in the parameter list...


  • Florim

    Thanks, seems to help, haven't got it again.

    Maybe I have misunderstood something fundamental, but how is my

    RASPPPIP rasp;

    declaration different from any other structure defintion, that is, why is it stored on the stack


  • BlackBean

    Guessing here: raspppip better be declared static. If it isn't, you're referring to a szIpAddress value that is on a stack frame that is already dismissed; anything could happen to it.



  • char* from c code via dllimport loses last character