views:

212

answers:

2

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?

+1  A: 

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.

Jim Mischel
Surfbutler
Surfbutler: In my version of VS 2008, the C# compiler handles negation of #defined constants just fine. Are you sure the constant you're trying to negate is defined?
Jim Mischel
Looking at the negation issue further, yes you're right, VS does handles negation of directives fine, except when the line you're trying to hide from C# is another directive e.g. #define. Looks like it only works for code, not directives.
Surfbutler
A: 

Call me funny, but I think the best way to do this is using C++/CLI and C++.

This lets you #include the same strings into two different contexts and let the compiler do the magic. This will give you arrays of strings

// some header file
L"string1",
L"string2",
L"string3",

// some C++ file
static wchar_t*[] string = {
#include "someheaderfile.h"
};

// in some C++/CLI file
array<String^>^ myArray = gcnew array<String^> {
#include "someheaderfile.h"
};

otherwise you can use the C preprocessor straight out:

// in somedefineset
#define SOME_STRING_LITERAL L"whatever"

// in some C++ file
#include "somedefineset.h"
const wchar_t *kSomeStringLiteral = SOME_STRING_LITERAL

// in some C++/CLI file
literal String ^kSomeStringLiteral = SOME_STRING_LITERAL;
plinth
Hi plinth, I'd like to try this, but how can I access it from my C# app?
Surfbutler
When you write a C++/CLI assembly it is accessible to every other .NET language.
plinth