0

i am not sure what the problem is. i have a c++ function returning a string as follows

extern "C++" __declspec(dllexport) std::string D()
{
    return "say hello";
}

and on my c#

[DllImport("MyMSG.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern string D();

when i run the wpf, i get an

'Unable to find an entry point named 'D' in DLL 'MyMSG.dll'.'

error. it seems to me that c++ and c# have a type mismatch on strings? i tried with other types like int and bool and i didnt get any problem. can someone explain please? thank you

EDIT first i would like to thank dxiv and andy for the response. i did more research and found that changing

public static extern string D();

to

public static extern System.IntPtr D();

then calling

string x = Marshal.PtrToStringAnsi(D());

seems to give me the right value.

Jim
  • 1
  • 1
  • 4
    The C++ `std::string` and .NET `System.String` (which the C# `string` is aliased to) are completely different, unrelated types. You cannot use standard C++ library types like `std::string` in APIs used from managed code. – dxiv May 07 '21 at 03:59
  • Look at how the Win32 API does strings. For example [GetWindowText](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowtexta). The calling application will allocate memory on the stack or heap, then pass the pointer to the DLL which will then copy the data over to that pointer. – Andy May 07 '21 at 04:08
  • The problem has nothing to do with a string. Read error message : "Unable to find an entry point named 'D' in DLL 'MyMSG.dll". I do not thing the latest version of the MyMSG.dll file is in the bin folder of the project or you are using the wrong bin folder (debug/release). Right click the MyMSG.dll in the solution explorer of project and check the location of where the file is located. Should be the debug folder of c++ project. – jdweng May 07 '21 at 06:23
  • 1
    `seems to give me the right value` - it only seems that way. You are leaking memory by creating `std:string`s that are not going to be destructed. – GSerg May 07 '21 at 07:10
  • @jdweng, i tried adding another function that returns like a bool or int. it works without any error. Only happens when I have string. I just cleaned the solution and build it again. I copied MyMSG.dll from debug folder of c++ project to the debug folder of my c# project. is that the right way to do? – Jim May 07 '21 at 16:27
  • @GSerg, doesn't c# does the clean up? any suggestion on the right path? – Jim May 07 '21 at 16:28
  • @Jim C# cannot know how to call the destructor of an unmanaged object. You [cannot even](https://stackoverflow.com/a/15146682/11683) pass `std::string` between unmanaged modules of different versions. – GSerg May 07 '21 at 16:36
  • A string in c# is a class object while a string in c++ is an array of btyes terminated with a '\0'. – jdweng May 08 '21 at 09:14

0 Answers0