Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare constant strings for use in both an unmanaged C++ dll and in a C# application?

Curently I'm passing my const string values up from my C++ into my C# at startup via a callback, but I'm wondering if there's a way of defining them in a C++ header file that I can then also refer to in C#.

I already do this with enums as they are easy. I include a file in both my C++ library project (via a .h file with a pragma once at the top), and my C# application (as a link):

#if _NET
public
#endif
enum ETestData
{
    First,
    Second
};

I know it sounds messy, but it works :)

But...how can I do the same with string constants - I'm initially thinking the syntax is too different between the platforms, but maybe there's a way?

Using clever syntax involving #if _NET, #defines etc?

Using resource files?

Using a C++/CLI library?

Any ideas?

like image 657
Surfbutler Avatar asked Mar 15 '10 18:03

Surfbutler


1 Answers

A C# string constant would take the form:

public const string MyString = "Hello, world";

I think the preferred way in C++ is:

const std::string MyString ="Hello, world";

string in C# is just an alias for the .NET type, String. One way to do this would be make a C++ #define:

#define String const std::string

And your common code would look like this:

   // at the beginning of the file
   #if !_NET
   #define String const std::string
   #endif

   // For each string definition
   #if _NET
   public const
   #endif
   String MyString = "Hello, world";

I have to admit that I haven't tried it, but it looks like it'll work.

like image 79
Jim Mischel Avatar answered Sep 21 '22 13:09

Jim Mischel