Avatar of josgood
josgoodFlag for United States of America

asked on 

C# / C++ Interop: C++ DLL returns char*

I have a C++ DLL wrapping other C++ code and am calling from C#.

   [DllImport("MyDll.dll")]
   static unsafe private extern IntPtr StatusToString();

The function being called is
   extern "C" {
      __declspec(dllexport)
      const char* StatusToString() {
         //return std::string("def").c_str();
         return "def";
      }
   }

The calling code is
   IntPtr abc = StatusToString();

As shown, with
   return "def";
and examining abc in the memory window, abc points to "abc".

However, with the C++ code modified to
   return std::string("def").c_str();
and examining abc in the memory window, abc points to garbage.

Why is that and what do I do?

Thanks,
Joe

C#C++

Avatar of undefined
Last Comment
josgood
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of josgood
josgood
Flag of United States of America image

ASKER

Thank you, jkr.  I am suitably embarrassed!
Joe

C#
C#

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

98K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo