-1

We want to pass a string to the vc++ from a csharp programme.

Following is the code : In C#

    [DllImport("ConsoleApplication2.dll")]
    public static extern int main_c(StringBuilder IpAddr, int p);
    public string[] tcp()
    {            
        StringBuilder buffer = new StringBuilder("192.168.1.100");                       
        int i = main_c(buffer, 34318);

In vc++

extern __declspec( dllexport ) int main_c(char *peer,int port)

{

This gives a error as ":main_c' has unbalanced the stack." How can this be done ?

  • C# code run properly? I mean, if you run it from a .net app will run without producing any errors? – kostas ch. Jun 27 '13 at 11:41
  • 1
    possible duplicate of [Pass C# string to C++ and pass C++ result (string, char\*.. whatever) to C#](http://stackoverflow.com/questions/2179270/pass-c-sharp-string-to-c-and-pass-c-result-string-char-whatever-to-c-s) – stijn Jun 27 '13 at 11:41
  • I have tried the above link it does not work. i.e. the solution is not working – A Shrinivas Rao Jun 27 '13 at 11:43
  • @kostasch. yes it is running without errors. The errors is fired from the c dll – A Shrinivas Rao Jun 27 '13 at 11:44
  • Yes you r right, i wanted to say the opposite. – kostas ch. Jun 27 '13 at 11:45
  • You need to send a pointer to the string. You would be better have reference to a character array. The possible duplicate is solution your looking for. Be sure your `CallingConvention` is the same – Security Hound Jun 27 '13 at 12:22
  • For the "unbalancing the stack" part, see Ramhound's message. For the buffer, maybe the `MarshalAs` attribute can help you (With `UnmanagedType.LPStr` and `SizeParamIndex`). – Medinoc Jun 27 '13 at 12:53

1 Answers1

0

Personnally, I'd try declaring it so:

[DllImport("ConsoleApplication2.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern int main_c([MarshalAs(UnmanagedType.LPStr)] String IpAddr, int port);

And declare the pointer const in the VC++ function, since it's not supposed to write there. You don't even need a StringBuilder.

Medinoc
  • 6,577
  • 20
  • 42