0

I have a dll written in c++. The function takes string as input and returns a long based on some internal algorithm. The function works completely as expected when run in c++ but when the dll is used with c#, although it throws no exception or gives no error but the program stops working. Can someone help me?

C++

static __declspec(dllexport) long long WriteUserData(string userId, int userIdLen)
 {
    cout<<"ID is: "<<userId<<endl;//In c++ displays output but not when called in c#
    cout<<userIdKen<<endl;
    .
    .SomeCode
    .
    return (some long value)
 }

C#

using System;
    using System.Text;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;

    namespace Extreme.Numerics.QuickStart.CSharp
    {

        class Program
        {
        [DllImport(".dll path..",EntryPoint = @"?...entryPoint....",CallingConvention = CallingConvention.Cdecl)]
        public static extern long WriteUserData(string id, int idLen)

    static void Main(string[] args)
     {
        long Serial= WriteUserData("@@rpan@@@@@@@",13);
        Console.WriteLine("test test test");
     }
    }
}

C# Output:

Id is:

It displays nothing more. The last line Console.WriteLine("test test test"); is also not displayed

MyCopy
  • 155
  • 1
  • 8
  • Did you try to step in with a debugger? Also you need a conversion between managed (System.String or sth.) and unmanaged (std::string) data types – RoQuOTriX Apr 08 '20 at 15:12
  • I'd guess it's marshalling the C# string as a C string, not a C++ std::string – Rup Apr 08 '20 at 15:12

1 Answers1

1

On the C++ side, change from string to const char*. Leave the C# side be. That's what the default expectation is for P/Invoke when it sees a C# string on the declaration side.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
  • Thanks +1. I would like to add that in C# side we need to use StringBuilder where ever string is to be inserted – MyCopy Apr 08 '20 at 18:49