Click here to Skip to main content
15,892,517 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello
i try to return back a value from c++ to c#
when i run my code on c#
my vshost32.exe has stopped working
can somebody tell me what actually just happen?
is there any problem on my code?

What I have tried:

on c#

[DllImport("C:\\Users\\user\\Desktop\\bookbarConnector\\Debug\\bookbarConnector.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        [return:MarshalAs(UnmanagedType.LPStr)]
        public static extern string helloCsharp();

        static void Main(string[] args)
        {
            Console.WriteLine(helloCsharp());
            Console.ReadLine();
        }


on c++

__declspec(dllexport) char* __stdcall helloCsharp() {
		return "hello world";
	}
Posted
Updated 21-Aug-17 21:38pm

1 solution

Your C# application tries to deallocate the string returned by the C++ DLL. But this fails with undefined behaviour because the string is not allocated but a static object. I don't know how and if this is related to vshost32.exe.

You can change the C++ code to return an allocated string using CoTaskMemAlloc, or the C# code to treat the return value as IntPtr and call Marshal.PtrToString. Note that the latter should only be used with constant objects (when your C++ function returns a const char*).

You might have a look at Returning Strings from a C++ API to C# | limbioliong[^] which explaias the different methods in detail.
 
Share this answer
 
Comments
newbie1992 22-Aug-17 4:48am    
thank you sir.
btw what does convention use for?
something like stdcall, fastcall and etc..
Jochen Arndt 22-Aug-17 4:59am    
You are welcome, and thank you for accepting my solution.

The calling method does not matter provided you specify matching methods.
With C++, stdcall is common. Because you are passing no arguments, using fastcall would be of no benefit.

For a description of the calling methods see for example https://en.wikipedia.org/wiki/X86_calling_conventions.
newbie1992 23-Aug-17 20:16pm    
ok sir,
thank you :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900