Papa John
Papa John

Reputation: 3794

c# string to unmanaged c++ dll

I need to write something like

switch (nameOfType) 
{
  case "burk":
    return "zzzz";

in my c++ DLL (I need this to compare type names)

Where nameOfType is a string that came from c# (via DLLImport) but I am quite new in c++ - what type I must use to operate in c++ with strings the same way as it is in c#?

Upvotes: 0

Views: 180

Answers (2)

parapura rajkumar
parapura rajkumar

Reputation: 24413

You cannot use char* in switch statements in C++ like C#. One thing you can do is replace it with an enum

enum StringEnum { burk , foo , bar };

map<string,StringNum> m;

m["burk"] = burk;
m["foo"]  = foo;
m["bar"]  = bar;

Now you can use a switch statement like below

StringEnum e = m[nameOfType];
switch(e)
{
  case bruk;

etc etc

Upvotes: 1

adelphus
adelphus

Reputation: 10326

The simplest strings in C/C++ are NULL terminated character arrays. You can normally marshal a managed string from C# into a const char* type.

The code you posted will not work in C++. The switch statement in C++ only permits integral types as the operand. The simplest way to get what you want is repeated if:

if (strcmp(nameOfType, "burk") == 0)
   return "zzzz";
else if (strcmp(nameOfType, "xyz") == 0)
   return "yyyy";
else ... 

If you need more string functionality, you should consider using the std::string class. It supports the normal searching, comparison, inserting and substring operations.

Upvotes: 2

Related Questions