Question

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?

Was it helpful?

Solution

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;

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top