Valhalla Legends Archive

Programming => General Programming => .NET Platform => Topic started by: MyndFyre on December 03, 2003, 11:51 PM

Title: Marshaling String __gc *ptr to char *cptr
Post by: MyndFyre on December 03, 2003, 11:51 PM
Hey everyone,

I have some functions I want to use in C# that someone else wrote in C++ 6.  I undertook the task of creating the wrapper MC++ class for it, like it said in the docs.  Here's basically what I'm doing:


// original api (header file):
extern "C" void __stdcall get_Response(const char *inpBuf,
                          const char *outBuf,
                          int bufLen);
extern "C" void __stdcall do_Command(const char *inpBuf,
                          const char *outBuf,
                          int bufLen);
extern "C" void __stdcall get_VerInfo(const char *outBuf,
                          int bufLen);
}

// my managed .h file:
#using <mscorlib.dll>

using System::String;
public __gc class ManagedAI
{
public:
  __gc String *GetResponse(String *input);
  __gc String *DoCommand(String *input);
  __gc String *GetVerInfo();
}

// impl. file
#import "ManagedAI.h"

String *ManagedAI::GetResponse(String *input)
{
  return String::Empty;
}

String *ManagedAI::DoCommand(String *input)
{
  return String::Empty;
}

String *ManagedAI::GetVerInfo()
{
  char *rep = new char[512];
  get_VerInfo(rep, 512);
  return new String(rep);
}


So I got the third function in, but the other two I couldn't - I keep getting compiler errors, and I can't figure out how to go from the managed System::String to a character pointer array.

Thanks for the help!

--Rob
Title: Re:Marshaling String __gc *ptr to char *cptr
Post by: K on December 04, 2003, 12:23 PM
Here's some code I wrote a while back:

// Managed String to char*
void mstosz(String* sIn, char* szOut)
{
   const wchar_t __pin* tmp = PtrToStringChars(sIn);

   wcstombs(szOut, tmp, sIn->Length);
   
   szOut[sIn->Length] = 0;
      return;
}

// managed string to basic_string via char *
string mstobs(String* sIn)
{
   string result;
   char* szTmp = new char[sIn->Length + 1];
   mstosz(sIn, szTmp);
   result = szTmp;
   delete [] szTmp;
   return result;
}


Edit: You will need to include <vcclr.h>  Also note that the above code doesn't check the length of the buffer in the first case.