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

2
  • 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 Commented Apr 8, 2020 at 15:12
  • I'd guess it's marshalling the C# string as a C string, not a C++ std::string Commented Apr 8, 2020 at 15:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks +1. I would like to add that in C# side we need to use StringBuilder where ever string is to be inserted

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.